Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
0dd5c61
spec : capability-gate the DFlash2 draft path
Nathanw1014 Aug 19, 2026
27a2f84
common: use full checkpoints for MTP rollback
Nathanw1014 Aug 21, 2026
fc9ea65
models : fix GDN state updates scheduled out of graph order in qwen35moe
gaetan-puleo Aug 17, 2026
0a2663c
server: keep speculative checkpoints on device
gaetan-puleo Aug 20, 2026
60e7333
server : do not re-verify replayed draft tokens after a checkpoint re…
Nathanw1014 Aug 22, 2026
4984dcc
vocab : read the special token ids of no_vocab models
Nathanw1014 Aug 22, 2026
a2fafdc
qwen4exp: load NextN/MTP draft tensors (sidecar and in-file)
Nathanw1014 Aug 27, 2026
c25831f
qwen4exp: NextN/MTP draft graph and context - spec decode works end t…
Nathanw1014 Aug 27, 2026
3cbc02f
convert: export the qwen4exp MTP draft head
Nathanw1014 Aug 27, 2026
dabc1af
convert: size qwen4exp compress_ratios by block count, not layer count
Nathanw1014 Aug 27, 2026
80462d5
convert: dequant the qwen4exp PLE table from FP8 checkpoints
Nathanw1014 Aug 30, 2026
34d7962
qwen4exp: gather the PLE table host-side
Nathanw1014 Aug 30, 2026
f523477
llama: batched gather prefetch for lazily-read host tables
Nathanw1014 Aug 30, 2026
8b7696e
qwen4exp: follow-up fixes from upstream PR #27941
Nathanw1014 Aug 30, 2026
374d333
qwen4exp: reduce the generation slowdown as context grows (upstream P…
Nathanw1014 Aug 30, 2026
e3185c6
server: keep prompt-phase checkpoints on device
Nathanw1014 Aug 30, 2026
3c77259
speculative : port rejection-sampling verifier onto upstream DFlash2
Nathanw1014 Aug 30, 2026
b3c3dbd
speculative : truncate proposal dists together with the draft
Nathanw1014 Aug 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion common/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ struct common_params_speculative {

uint32_t need_n_rs_seq() const {
bool needs_rs_seq = std::any_of(types.begin(), types.end(), [&](auto t) {
return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP || t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK;
return t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK;
});

return needs_rs_seq ? draft.n_max : 0u;
Expand Down
101 changes: 101 additions & 0 deletions common/sampling.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include "fit.h"
#include "log.h"
#include "reasoning-budget.h"
#include "speculative.h"

#include "ggml.h"

Expand All @@ -12,6 +13,7 @@
#include <climits>
#include <cmath>
#include <cstring>
#include <random>
#include <unordered_map>
#include <vector>

Expand Down Expand Up @@ -121,10 +123,14 @@ struct common_sampler {

llama_token_data_array cur_p;

uint32_t speculative_seed;
std::mt19937 speculative_rng;

void reset() {
prev.clear();

llama_sampler_reset(chain);
speculative_rng.seed(speculative_seed);
}

void set_logits(struct llama_context * ctx, int idx) {
Expand Down Expand Up @@ -446,6 +452,8 @@ struct common_sampler * common_sampler_init(
params.backend_sampling = false;
}

// Keep verifier randomness independent from both target and draft sampling.
const uint32_t speculative_seed = llama_sampler_get_seed(chain) ^ 0x9e3779b9U;
auto * result = new common_sampler {
/* .params = */ params,
/* .grmr = */ grmr,
Expand All @@ -454,6 +462,8 @@ struct common_sampler * common_sampler_init(
/* .prev = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
/* .cur = */ {},
/* .cur_p = */ {},
/* .speculative_seed = */ speculative_seed,
/* .speculative_rng = */ std::mt19937(speculative_seed),
};

return result;
Expand Down Expand Up @@ -537,6 +547,8 @@ struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
/* .prev = */ gsmpl->prev,
/* .cur = */ gsmpl->cur,
/* .cur_p = */ gsmpl->cur_p,
/* .speculative_seed = */ gsmpl->speculative_seed,
/* .speculative_rng = */ gsmpl->speculative_rng,
};
}

Expand All @@ -557,6 +569,8 @@ void common_sampler_copy(const common_sampler * src, common_sampler * dst) {
dst->cur = src->cur;
dst->cur_p = src->cur_p;
dst->cur_p.data = src->cur_p.data ? dst->cur.data() : nullptr; // re-point to dst's buffer
dst->speculative_seed = src->speculative_seed;
dst->speculative_rng = src->speculative_rng;
dst->t_total_us = src->t_total_us;
}

Expand Down Expand Up @@ -727,6 +741,79 @@ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sample
return result;
}

std::vector<llama_token> common_sampler_sample_and_accept_n(
struct common_sampler * gsmpl,
struct llama_context * ctx,
const std::vector<int> & idxs,
const llama_tokens & draft,
const std::vector<common_speculative_token_dist> & dists,
bool grammar_first) {
GGML_ASSERT(idxs.size() == draft.size() + 1);
GGML_ASSERT(dists.size() == draft.size());

std::vector<llama_token> result;
result.reserve(idxs.size());

std::uniform_real_distribution<float> uniform(0.0f, 1.0f);
size_t i = 0;
for (; i < draft.size(); ++i) {
// Residual sampling needs the target distribution after every constraint.
const llama_token fallback = common_sampler_sample(gsmpl, ctx, idxs[i], true);
const auto & q = dists[i];
GGML_ASSERT(q.ids.size() == q.probs.size());

std::unordered_map<llama_token, float> q_probs;
q_probs.reserve(q.ids.size());
for (size_t j = 0; j < q.ids.size(); ++j) {
q_probs[q.ids[j]] += q.probs[j];
}
const auto q_prob = [&](llama_token id) {
const auto it = q_probs.find(id);
return it == q_probs.end() ? 0.0f : it->second;
};

auto * p = common_sampler_get_candidates(gsmpl, false);
float p_draft = 0.0f;
const float q_draft = q_prob(draft[i]);
for (size_t j = 0; j < p->size; ++j) {
if (p->data[j].id == draft[i]) {
p_draft = p->data[j].p;
break;
}
}

if (q_draft > 0.0f && uniform(gsmpl->speculative_rng) * q_draft <= p_draft) {
common_sampler_accept(gsmpl, draft[i], true);
result.push_back(draft[i]);
continue;
}

std::vector<float> residual(p->size);
float residual_sum = 0.0f;
for (size_t j = 0; j < p->size; ++j) {
residual[j] = std::max(0.0f, p->data[j].p - q_prob(p->data[j].id));
residual_sum += residual[j];
}

llama_token id = fallback;
if (residual_sum > 0.0f) {
std::discrete_distribution<size_t> sample(residual.begin(), residual.end());
id = p->data[sample(gsmpl->speculative_rng)].id;
}
common_sampler_accept(gsmpl, id, true);
result.push_back(id);
break;
}

if (i == draft.size()) {
const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
common_sampler_accept(gsmpl, id, true);
result.push_back(id);
}

return result;
}

std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first) {
std::vector<int> idxs(draft.size() + 1);
for (size_t i = 0; i < idxs.size(); ++i) {
Expand All @@ -736,6 +823,20 @@ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sample
return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
}

std::vector<llama_token> common_sampler_sample_and_accept_n(
struct common_sampler * gsmpl,
struct llama_context * ctx,
const llama_tokens & draft,
const std::vector<common_speculative_token_dist> & dists,
bool grammar_first) {
std::vector<int> idxs(draft.size() + 1);
for (size_t i = 0; i < idxs.size(); ++i) {
idxs[i] = i;
}

return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, dists, grammar_first);
}

uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
return llama_sampler_get_seed(gsmpl->chain);
}
Expand Down
18 changes: 18 additions & 0 deletions common/sampling.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
//

struct common_sampler;
struct common_speculative_token_dist;

// llama_sampler API overloads

Expand Down Expand Up @@ -85,6 +86,23 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co
//
std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first = false);

// maximal-coupling verification for stochastic speculative decoding
std::vector<llama_token> common_sampler_sample_and_accept_n(
struct common_sampler * gsmpl,
struct llama_context * ctx,
const std::vector<int> & idxs,
const llama_tokens & draft,
const std::vector<common_speculative_token_dist> & dists,
bool grammar_first = false);

// assume idxs == [ 0, 1, 2, ..., draft.size() ]
std::vector<llama_token> common_sampler_sample_and_accept_n(
struct common_sampler * gsmpl,
struct llama_context * ctx,
const llama_tokens & draft,
const std::vector<common_speculative_token_dist> & dists,
bool grammar_first = false);

// assume idxs == [ 0, 1, 2, ..., draft.size() ]
std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first = false);

Expand Down
59 changes: 58 additions & 1 deletion common/speculative.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@

#include <algorithm>
#include <cassert>
#include <chrono>
#include <cinttypes>
#include <cmath>
#include <cstring>
#include <iomanip>
#include <map>
#include <cinttypes>
#include <random>

#define SPC_DBG(fmt, ...) LOG_DBG("spec %12.*s: " fmt, 12, __func__, __VA_ARGS__)
#define SPC_TRC(fmt, ...) LOG_TRC("spec %12.*s: " fmt, 12, __func__, __VA_ARGS__)
Expand Down Expand Up @@ -1009,6 +1011,8 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl {
bool is_dflash2 = false;
bool is_mrope = false;
int32_t selector_top_k = 0;
std::vector<std::mt19937> selector_rng;
std::vector<bool> selector_reset;

// draft-dspark: the draft carries a Markov head and uses an anchor-first block layout
const bool is_dspark;
Expand Down Expand Up @@ -1063,6 +1067,12 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl {

selector_top_k = llama_model_dflash_selector_top_k(model_dft);
is_dflash2 = selector_top_k > 0;
if (!is_dflash2) {
char buf[32] = {};
if (llama_model_meta_val_str(model_dft, "dflash.selector_top_k", buf, sizeof(buf)) >= 0 && std::atoi(buf) > 0) {
LOG_WRN("%s: draft model has DFlash2 selector metadata but its decode graph does not build the selector lattice, using the DFlash draft path\n", __func__);
}
}
mask_token_id = llama_vocab_mask(llama_model_get_vocab(model_dft));

if (is_dspark && this->params.p_min > 0.0f) {
Expand Down Expand Up @@ -1111,6 +1121,9 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl {
s.reset(common_sampler_init(model_dft, sparams));
}

selector_rng.resize(n_seq);
selector_reset.assign(n_seq, true);

// offload draft sampling to the backend
backend_chains.assign(n_seq, nullptr);
if (this->params.backend_sampling && !is_dflash2) {
Expand Down Expand Up @@ -1166,6 +1179,8 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl {
return;
}

selector_reset[seq_id] = true;

const llama_pos pos_max = llama_memory_seq_pos_max(llama_get_memory(params.ctx_dft), seq_id);
if (pos_max < N - 1) {
LOG_WRN("%s: ctx_dft pos_max=%d < N-1=%d - process() did not run on every prefill ubatch. "
Expand Down Expand Up @@ -1389,15 +1404,50 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl {

auto & result = *dp.result;

if (dp.dists) {
dp.dists->clear();
}

if (is_dflash2) {
GGML_ASSERT(dp.temperature <= 0.0f || dp.dists);
const float * lattice = llama_get_embeddings_nextn(ctx_dft);
GGML_ASSERT(lattice && "DFlash2 selector produced no lattice");

if (selector_reset[seq_id]) {
uint32_t seed = dp.seed;
if (seed == LLAMA_DEFAULT_SEED) {
seed = (uint32_t) std::chrono::high_resolution_clock::now().time_since_epoch().count();
}
selector_rng[seq_id].seed(seed ^ 0x85ebca6bU);
selector_reset[seq_id] = false;
}

int32_t predecessor = 0;
for (int32_t i = 1; i < n_block_tokens; ++i) {
const float * row = lattice + (size_t) (beg + i) * n_embd_dec;
const float * scores = row + selector_top_k + (size_t) predecessor * selector_top_k;

if (dp.temperature > 0.0f) {
common_speculative_token_dist dist;
dist.ids.resize(selector_top_k);
dist.probs.resize(selector_top_k);
const float max_score = *std::max_element(scores, scores + selector_top_k);
float sum = 0.0f;
for (int32_t k = 0; k < selector_top_k; ++k) {
dist.ids[k] = (llama_token) row[k];
dist.probs[k] = std::exp((scores[k] - max_score) / dp.temperature);
sum += dist.probs[k];
}
for (float & p : dist.probs) {
p /= sum;
}
std::discrete_distribution<int32_t> sample(dist.probs.begin(), dist.probs.end());
predecessor = sample(selector_rng[seq_id]);
result.push_back(dist.ids[predecessor]);
dp.dists->push_back(std::move(dist));
continue;
}

predecessor = (int32_t) std::distance(scores,
std::max_element(scores, scores + selector_top_k));
if (params.p_min > 0.0f) {
Expand All @@ -1415,6 +1465,9 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl {

if (result.size() < (size_t) params.n_min) {
result.clear();
if (dp.dists) {
dp.dists->clear();
}
}
continue;
}
Expand Down Expand Up @@ -3005,6 +3058,10 @@ void common_speculative_draft(common_speculative * spec) {
if (!result.empty() && (int) result.size() > dp.n_max) {
SPC_DBG("truncating draft to %d tokens\n", dp.n_max);
result.resize(dp.n_max);
// keep the proposal distributions aligned with the truncated draft
if (dp.dists && dp.dists->size() > result.size()) {
dp.dists->resize(result.size());
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions common/speculative.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@

struct common_speculative;

struct common_speculative_token_dist {
llama_tokens ids;
std::vector<float> probs;
};

// comma separated list the provided types
std::string common_speculative_type_name_str(const std::vector<enum common_speculative_type> & types);

Expand Down Expand Up @@ -69,6 +74,12 @@ struct common_speculative_draft_params {

// the generated draft from the last _draft() call
llama_tokens * result;

// optional sparse proposal distributions, one per draft token
std::vector<common_speculative_token_dist> * dists = nullptr;

float temperature = 0.0f;
uint32_t seed = LLAMA_DEFAULT_SEED;
};

common_speculative_draft_params & common_speculative_get_draft_params(common_speculative * spec, llama_seq_id seq_id);
Expand Down
Loading
Loading