diff --git a/common/sampling.cpp b/common/sampling.cpp index 06dea1e1ccea..3222c7d81f2f 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -121,40 +121,159 @@ struct common_sampler { llama_token_data_array cur_p; + // Continuum fork (CONTINUUM-ENGINE 4.7.13): BALLPARK FIRST, EXACT ON THE FEW. When every sampler before + // top-k can only LOWER a logit, the post-adjustment top-k lies inside the raw top-(k + h), h = how many + // tokens can be lowered, plus any token a bias raises. So the chain runs unchanged on the logits at or + // above a threshold that keeps at least `coarse_cap` of them: the same token as over the whole + // vocabulary. The threshold comes from the PREVIOUS step (consecutive tokens' logit distributions are + // close, frame-to-frame coherence); a sampled estimate seeds it, and a miss widens it. The scan asks + // per block "is any logit >= the threshold?" (an OR of comparisons, which vectorizes; a float max + // reduction does not without fast-math). 0 = disabled. + size_t coarse_cap = 0; + std::vector coarse_raised; // tokens a positive bias can raise: always candidates + std::vector coarse_ids; + std::vector coarse_vals; + // The cut is carried as an ABSOLUTE logit: the k-th largest of ~250k logits is a tail quantile of + // the bulk distribution, which is stable step to step, while the max (one confident token) spikes + // (measured: carrying it relative to the max tripled the misses). The margin below last step's cut + // is the measured step-to-step drift of that cut (a running mean of |change|), not a constant. + float coarse_thr = 0.0f; + float coarse_cut = 0.0f; // last step's cap-th largest + float coarse_drift = 0.0f; // running mean of |cut change| between steps + // which RANK of this step's logits becomes the next threshold (candidates scale with rank; a margin + // in logit units swept in thousands, measured). Balanced ONLINE between the two costs it trades (a + // miss = another full scan, ~23 us; each extra candidate ~ tens of ns through the chain): a miss + // raises it, a hit lowers it slowly, never below cap. + float coarse_margin = 2.0f; // rank = margin * cap + bool coarse_known = false; + struct coarse_stats_t { uint64_t calls = 0, reseeds = 0, widens = 0, candidates = 0; } coarse_stats; + + // the ids of every logit >= thr, in id order; returns how many + size_t coarse_scan(const float * logits, int n_vocab, float thr) { + coarse_ids.clear(); + constexpr int BLOCK = 32; + int i = 0; + for (; i + BLOCK <= n_vocab; i += BLOCK) { + int any = 0; + for (int j = 0; j < BLOCK; ++j) { + any |= logits[i + j] >= thr; // vectorizes: an OR of comparisons, no serial dependency + } + if (any) { + for (int j = 0; j < BLOCK; ++j) { + if (logits[i + j] >= thr) coarse_ids.push_back(i + j); + } + } + } + for (; i < n_vocab; ++i) { + if (logits[i] >= thr) coarse_ids.push_back(i); + } + return coarse_ids.size(); + } + + // a first threshold from a strided sample (once, or after a miss): keeps ~2x cap on average + float coarse_seed(const float * logits, int n_vocab) { + constexpr int STRIDE = 16; + coarse_vals.clear(); + for (int i = 0; i < n_vocab; i += STRIDE) { + if (!std::isnan(logits[i])) coarse_vals.push_back(logits[i]); // NaN breaks nth_element's ordering + } + if (coarse_vals.empty()) { + return -INFINITY; + } + const size_t want = std::min(coarse_vals.size() - 1, (coarse_cap * 2) / STRIDE + 1); + std::nth_element(coarse_vals.begin(), coarse_vals.begin() + (ptrdiff_t) want, coarse_vals.end(), std::greater()); + return coarse_vals[want]; + } + + // false when no threshold can admit `cap` candidates (fewer than cap logits are not NaN): the caller + // then takes the full array, the exact path, never a different sampler (Codex on #122: the widening + // loop never ended on NaN logits) + bool coarse_candidates(const float * logits, int n_vocab) { + const size_t cap = coarse_cap; + coarse_stats.calls++; + float thr = coarse_known ? coarse_thr : (coarse_stats.reseeds++, coarse_seed(logits, n_vocab)); + size_t n = coarse_scan(logits, n_vocab, thr); + float step = 0.0f; + if (n < cap) { + // a miss: keep more next time, never past the whole vocabulary (an unbounded margin made the + // rank cast below undefined) + coarse_margin = std::min(coarse_margin * 1.5f, (float) n_vocab / (float) std::max(cap, 1)); + } else { + coarse_margin = std::max(1.0f, coarse_margin * 0.97f); // a hit: keep a little less + } + while (n < cap) { // a miss: re-seed from the strided-sample estimate (aims at ~2x cap), then double the gap + if (thr == -INFINITY) { + // every logit that is not NaN is already in: no threshold admits more + coarse_known = false; + return false; + } + coarse_stats.widens++; + const float seeded = coarse_seed(logits, n_vocab); + step = step == 0.0f ? std::max(thr - seeded, 1e-3f) : step * 2.0f; + const float next = std::min(seeded, thr - step); + // progress or the end: a widening that does not strictly lower the threshold (an infinite or + // NaN seed, +inf - +inf, a step that overflowed) goes straight to -inf, where the check above + // ends it (Codex on #122: a +inf seed never moved the threshold) + thr = next < thr ? next : -INFINITY; + n = coarse_scan(logits, n_vocab, thr); + } + // next step's threshold: the value at rank margin*cap among this step's logits (the candidates hold + // every logit at or above the threshold, so ranks up to their count are exact; past it, keep the + // threshold this step used) + coarse_vals.clear(); + for (const auto id : coarse_ids) coarse_vals.push_back(logits[id]); + const size_t rank = std::min(coarse_vals.size(), (size_t) (coarse_margin * (float) cap)); + if (rank >= 1) { + std::nth_element(coarse_vals.begin(), coarse_vals.begin() + (ptrdiff_t) (rank - 1), coarse_vals.end(), std::greater()); + coarse_thr = rank < (size_t) (coarse_margin * (float) cap) ? thr : coarse_vals[rank - 1]; + } + coarse_known = true; + if (!coarse_raised.empty()) { + coarse_ids.insert(coarse_ids.end(), coarse_raised.begin(), coarse_raised.end()); + std::sort(coarse_ids.begin(), coarse_ids.end()); + coarse_ids.erase(std::unique(coarse_ids.begin(), coarse_ids.end()), coarse_ids.end()); + } + coarse_stats.candidates += coarse_ids.size(); + cur.resize(coarse_ids.size()); + for (size_t k = 0; k < coarse_ids.size(); ++k) { + cur[k] = llama_token_data{ coarse_ids[k], logits[coarse_ids[k]], 0.0f }; + } + return true; + } + void reset() { prev.clear(); llama_sampler_reset(chain); } - void set_logits(struct llama_context * ctx, int idx) { - const float * sampled_probs = llama_get_sampled_probs_ith (ctx, idx); - const float * sampled_logits = llama_get_sampled_logits_ith (ctx, idx); - const llama_token * sampled_ids = llama_get_sampled_candidates_ith(ctx, idx); + void set_logits(const common_sampler_row & row, bool coarse = false) { + const float * sampled_probs = row.sampled_probs; + const float * sampled_logits = row.sampled_logits; + const llama_token * sampled_ids = row.sampled_ids; - const llama_model * model = llama_get_model(ctx); - const llama_vocab * vocab = llama_model_get_vocab(model); - - const int n_vocab = llama_vocab_n_tokens(vocab); + const int n_vocab = row.n_vocab; if (sampled_probs) { - const uint32_t sampled_probs_count = llama_get_sampled_probs_count_ith(ctx, idx); + const uint32_t sampled_probs_count = row.n_sampled_probs; cur.resize(sampled_probs_count); for (uint32_t i = 0; i < sampled_probs_count; ++i) { cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], sampled_probs[i]}; } } else if (sampled_logits) { - const uint32_t sampled_logits_count = llama_get_sampled_logits_count_ith(ctx, idx); + const uint32_t sampled_logits_count = row.n_sampled_logits; cur.resize(sampled_logits_count); for (uint32_t i = 0; i < sampled_logits_count; i++) { cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], 0.0f}; } } else { - const auto * logits = llama_get_logits_ith(ctx, idx); + const auto * logits = row.logits; GGML_ASSERT(logits != nullptr); - cur.resize(n_vocab); - for (llama_token token_id = 0; token_id < n_vocab; token_id++) { - cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f}; + if (!(coarse && coarse_cap > 0 && coarse_cap < (size_t) n_vocab && coarse_candidates(logits, n_vocab))) { + cur.resize(n_vocab); + for (llama_token token_id = 0; token_id < n_vocab; token_id++) { + cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f}; + } } } @@ -432,8 +551,52 @@ struct common_sampler * common_sampler_init( /* .prev = */ ring_buffer(std::max(32, params.n_prev)), /* .cur = */ {}, /* .cur_p = */ {}, + /* .coarse_cap = */ 0, + /* .coarse_raised = */ {}, + /* .coarse_ids = */ {}, + /* .coarse_vals = */ {}, + /* .coarse_thr = */ 0.0f, + /* .coarse_cut = */ 0.0f, + /* .coarse_drift = */ 0.0f, + /* .coarse_margin = */ 1.0f, + /* .coarse_known = */ false, + /* .coarse_stats = */ {}, }; + // ballpark-first eligibility (common_sampler::coarse_cap): exact only when everything before top-k can + // only lower a logit and needs no whole-vocabulary statistic, and no full distribution is wanted + { + bool eligible = params.mirostat == 0 && params.top_k > 0 && params.n_probs == 0 && + params.penalty_repeat >= 1.0f && params.penalty_freq >= 0.0f && params.penalty_present >= 0.0f; + size_t lowered = params.penalty_last_n > 0 ? (size_t) params.penalty_last_n : 0; + std::vector raised; + const llama_token n_vocab = llama_vocab_n_tokens(vocab); + for (const auto & b : params.logit_bias) { + // a bias on an id outside the vocabulary moves nothing on the full path either: never a candidate + // (Codex on #122: -1 or >= n_vocab indexed logits out of bounds); duplicates collapse with the scan's + if (b.token < 0 || b.token >= n_vocab) { + continue; + } + if (b.bias > 0.0f) raised.push_back(b.token); else lowered++; + } + bool has_top_k = false; + for (const auto t : params.samplers) { + if (t == COMMON_SAMPLER_TYPE_TOP_K) { has_top_k = true; break; } + switch (t) { + case COMMON_SAMPLER_TYPE_PENALTIES: break; // lowers only + case COMMON_SAMPLER_TYPE_DRY: eligible &= params.dry_multiplier == 0.0f; break; // disabled = empty + case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: eligible &= params.top_n_sigma <= 0.0f; break; // needs all-V stats + default: eligible = false; break; + } + } + if (eligible && has_top_k) { + int32_t n_suppress = 0; + llama_vocab_get_suppress_tokens(vocab, &n_suppress); // -inf biases: lowered + result->coarse_cap = (size_t) params.top_k + lowered + (size_t) n_suppress; + result->coarse_raised = std::move(raised); + } + } + return result; } @@ -498,6 +661,12 @@ void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, boo gsmpl->prev.push_back(token); } +// Continuum fork: the ballpark path's counters (cap, calls, reseeds, widens, mean candidates) +void common_sampler_coarse_stats(const struct common_sampler * gsmpl, size_t * cap, uint64_t * calls, uint64_t * reseeds, uint64_t * widens, uint64_t * candidates) { + *cap = gsmpl->coarse_cap; *calls = gsmpl->coarse_stats.calls; *reseeds = gsmpl->coarse_stats.reseeds; + *widens = gsmpl->coarse_stats.widens; *candidates = gsmpl->coarse_stats.candidates; +} + void common_sampler_reset(struct common_sampler * gsmpl) { if (!gsmpl) { return; @@ -513,8 +682,21 @@ struct common_sampler * common_sampler_clone(common_sampler * gsmpl) { /* .rbudget = */ llama_sampler_clone(gsmpl->rbudget), /* .chain = */ llama_sampler_clone(gsmpl->chain), /* .prev = */ gsmpl->prev, - /* .cur = */ gsmpl->cur, - /* .cur_p = */ gsmpl->cur_p, + // cur / cur_p are per-sample SCRATCH (set_logits rebuilds them before any read): a save point + // carries state, never the scratch (on the full path that was a 248k-entry, ~3 MB copy per + // speculative verify step; measured 42 us per clone, 39 us per restore on the 0.8B) + /* .cur = */ {}, + /* .cur_p = */ { nullptr, 0, -1, false }, + /* .coarse_cap = */ gsmpl->coarse_cap, // a clone (speculative verify) keeps the ballpark path + /* .coarse_raised = */ gsmpl->coarse_raised, + /* .coarse_ids = */ {}, + /* .coarse_vals = */ {}, + /* .coarse_thr = */ gsmpl->coarse_thr, + /* .coarse_cut = */ gsmpl->coarse_cut, + /* .coarse_drift = */ gsmpl->coarse_drift, + /* .coarse_margin = */ gsmpl->coarse_margin, + /* .coarse_known = */ gsmpl->coarse_known, + /* .coarse_stats = */ {}, }; } @@ -532,10 +714,16 @@ void common_sampler_copy(const common_sampler * src, common_sampler * dst) { dst->params = src->params; dst->prev = src->prev; - 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 + // cur / cur_p are scratch, rebuilt by set_logits before any read: never copied (see common_sampler_clone) + dst->cur_p = { nullptr, 0, -1, false }; dst->t_total_us = src->t_total_us; + dst->coarse_cap = src->coarse_cap; + dst->coarse_raised = src->coarse_raised; + dst->coarse_thr = src->coarse_thr; + dst->coarse_cut = src->coarse_cut; + dst->coarse_drift = src->coarse_drift; + dst->coarse_margin = src->coarse_margin; + dst->coarse_known = src->coarse_known; } void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) { @@ -591,9 +779,30 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl) { return gsmpl->chain; } -llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) { +common_sampler_row common_sampler_row_ith(struct llama_context * ctx, int idx) { llama_synchronize(ctx); + common_sampler_row row; + row.sampled_probs = llama_get_sampled_probs_ith (ctx, idx); + row.sampled_logits = llama_get_sampled_logits_ith (ctx, idx); + row.sampled_ids = llama_get_sampled_candidates_ith(ctx, idx); + if (row.sampled_probs) { + row.n_sampled_probs = llama_get_sampled_probs_count_ith(ctx, idx); + } else if (row.sampled_logits) { + row.n_sampled_logits = llama_get_sampled_logits_count_ith(ctx, idx); + } else { + row.logits = llama_get_logits_ith(ctx, idx); + } + row.sampled_token = llama_get_sampled_token_ith(ctx, idx); + row.n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + return row; +} + +llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) { + return common_sampler_sample_row(gsmpl, common_sampler_row_ith(ctx, idx), grammar_first); +} + +llama_token common_sampler_sample_row(struct common_sampler * gsmpl, const common_sampler_row & row, bool grammar_first) { // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations const auto tm = gsmpl->tm(); @@ -604,12 +813,16 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co auto & chain = gsmpl->chain; auto & cur_p = gsmpl->cur_p; // initialized by set_logits - gsmpl->set_logits(ctx, idx); + // ballpark first unless the grammar must see the whole vocabulary now, or the reasoning budget is + // FORCING (it sets every candidate but the forced token to -inf, and the forced token need not be in + // a ballpark subset); a grammar rejection below resamples over the full array + const bool forcing = rbudget && common_reasoning_budget_get_state(rbudget) == REASONING_BUDGET_FORCING; + gsmpl->set_logits(row, /*coarse=*/!forcing && !(grammar_first && grammar_should_apply(gsmpl))); // Check if a backend sampler has already sampled a token in which case we // return that token id directly. { - id = llama_get_sampled_token_ith(ctx, idx); + id = row.sampled_token; if (id != LLAMA_TOKEN_NULL) { LOG_DBG("%s: Backend sampler selected token: '%d'. Will not run any CPU samplers\n", __func__, id); @@ -658,7 +871,7 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co // resampling: // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain - gsmpl->set_logits(ctx, idx); + gsmpl->set_logits(row); llama_sampler_apply(rbudget, &cur_p); @@ -676,14 +889,23 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co } std::vector common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector & idxs, const llama_tokens & draft, bool grammar_first) { - GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1"); + std::vector rows; + rows.reserve(idxs.size()); + for (const int idx : idxs) { + rows.push_back(common_sampler_row_ith(ctx, idx)); + } + return common_sampler_sample_and_accept_rows(gsmpl, rows, draft, grammar_first); +} + +std::vector common_sampler_sample_and_accept_rows(struct common_sampler * gsmpl, const std::vector & rows, const llama_tokens & draft, bool grammar_first) { + GGML_ASSERT(rows.size() == draft.size() + 1 && "rows.size() must be draft.size() + 1"); std::vector result; - result.reserve(idxs.size()); + result.reserve(rows.size()); size_t i = 0; for (; i < draft.size(); i++) { - const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first); + const llama_token id = common_sampler_sample_row(gsmpl, rows[i], grammar_first); common_sampler_accept(gsmpl, id, true); @@ -695,7 +917,7 @@ std::vector common_sampler_sample_and_accept_n(struct common_sample } if (i == draft.size()) { - const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first); + const llama_token id = common_sampler_sample_row(gsmpl, rows[i], grammar_first); common_sampler_accept(gsmpl, id, true); diff --git a/common/sampling.h b/common/sampling.h index ced3c8364b32..e1eb3ffd41ad 100644 --- a/common/sampling.h +++ b/common/sampling.h @@ -46,6 +46,10 @@ void common_sampler_free(struct common_sampler * gsmpl); // if is_generated is true, the token is accepted by the sampling chain, the reasoning budget sampler, and the grammar sampler void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool is_generated); void common_sampler_reset (struct common_sampler * gsmpl); + +// Continuum fork: the ballpark sampling path's counters (CONTINUUM-ENGINE 4.7.13) +void common_sampler_coarse_stats(const struct common_sampler * gsmpl, size_t * cap, uint64_t * calls, + uint64_t * reseeds, uint64_t * widens, uint64_t * candidates); struct common_sampler * common_sampler_clone (struct common_sampler * gsmpl); void common_sampler_copy (const struct common_sampler * src, struct common_sampler * dst); @@ -67,6 +71,28 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl); // llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first = false); +// One output row's sampling input, gathered from the context by the thread that owns it. Sampling from a +// row reads no context state, so the rows of one decode step sample on many lanes at once (continuum +// CONTINUUM-ENGINE 4.7.14). common_sampler_row_ith synchronizes the context first. +struct common_sampler_row { + const float * logits = nullptr; + const float * sampled_probs = nullptr; + const float * sampled_logits = nullptr; + const llama_token * sampled_ids = nullptr; + uint32_t n_sampled_probs = 0; + uint32_t n_sampled_logits = 0; + llama_token sampled_token = LLAMA_TOKEN_NULL; // a backend sampler's choice, if any + int32_t n_vocab = 0; +}; + +common_sampler_row common_sampler_row_ith(struct llama_context * ctx, int idx); + +// common_sampler_sample over a gathered row: touches only `gsmpl` +llama_token common_sampler_sample_row(struct common_sampler * gsmpl, const common_sampler_row & row, bool grammar_first = false); + +// common_sampler_sample_and_accept_n over gathered rows (rows.size() == draft.size() + 1): touches only `gsmpl` +std::vector common_sampler_sample_and_accept_rows(struct common_sampler * gsmpl, const std::vector & rows, const llama_tokens & draft, bool grammar_first = false); + // generalized version of common_sampler_sample // // will cross-reference the sampled tokens with a batch of draft tokens and accept those that match diff --git a/common/speculative.cpp b/common/speculative.cpp index 4b67bbb88599..cd9fb2eb588f 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -2677,8 +2677,8 @@ void common_speculative_draft(common_speculative * spec) { } if (!result.empty()) { - SPC_DBG("called impl %s, hist size = %zu, call_count = %zu, gen = %zu\n", - common_speculative_type_to_str(impl.get()->type).c_str(), dp.prompt->size(), + SPC_DBG("called impl %s, n_past = %zu, call_count = %zu, gen = %zu\n", + common_speculative_type_to_str(impl.get()->type).c_str(), (size_t) dp.n_past, impl.get()->n_call_draft, result.size()); // remember which implementation was used diff --git a/src/llama-sampler.cpp b/src/llama-sampler.cpp index 34a7988262ea..c5561f58ae5f 100644 --- a/src/llama-sampler.cpp +++ b/src/llama-sampler.cpp @@ -2954,26 +2954,66 @@ static void llama_sampler_penalties_apply(struct llama_sampler * smpl, llama_tok return; } - // Apply frequency and presence penalties to the cur_p - for (size_t i = 0; i < cur_p->size; ++i) { - const auto token_iter = ctx->token_count.find(cur_p->data[i].id); - if (token_iter == ctx->token_count.end()) { - continue; + // The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong. + // This is common fix for this problem, which is to multiply by the penalty instead of dividing. + const auto penalize = [ctx](llama_token_data & d, int count) { + assert(count > 0 && count <= ctx->penalty_last_n); + if (d.logit <= 0) { + d.logit *= ctx->penalty_repeat; + } else { + d.logit /= ctx->penalty_repeat; } + d.logit -= float(count) * ctx->penalty_freq + float(count > 0) * ctx->penalty_present; + }; - const int count = token_iter->second; - - assert(count > 0 && count <= ctx->penalty_last_n); + // Continuum fork (CONTINUUM-ENGINE 4.7.13): only tokens in the recent history can be penalized, at most + // penalty_last_n of them, so walk THEM, not the whole vocabulary. While the candidates are still in + // token-id order (data[id].id == id: penalties ran first, as in the default chain) each one is applied + // in place at data[id]: O(history) per token instead of O(vocab) hash lookups. + if (cur_p->size > ctx->token_count.size()) { + bool aligned = true; + for (const auto & [id, count] : ctx->token_count) { + if (id < 0 || (size_t) id >= cur_p->size || cur_p->data[id].id != id) { + aligned = false; + break; + } + } + if (aligned) { + for (const auto & [id, count] : ctx->token_count) { + penalize(cur_p->data[id], count); + } + cur_p->sorted = false; + return; + } + } - // The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong. - // This is common fix for this problem, which is to multiply by the penalty instead of dividing. - if (cur_p->data[i].logit <= 0) { - cur_p->data[i].logit *= ctx->penalty_repeat; - } else { - cur_p->data[i].logit /= ctx->penalty_repeat; + // a candidate SUBSET still in token-id order (e.g. a ballpark cut, common/sampling.cpp): find each + // history token by binary search, O(history x log n), instead of a hash lookup per candidate + if (cur_p->size > 1) { + bool by_id = true; + for (size_t i = 1; i < cur_p->size; ++i) { + if (cur_p->data[i].id <= cur_p->data[i - 1].id) { by_id = false; break; } + } + if (by_id) { + const auto first = cur_p->data, last = cur_p->data + cur_p->size; + for (const auto & [id, count] : ctx->token_count) { + const auto it = std::lower_bound(first, last, id, [](const llama_token_data & d, llama_token v) { return d.id < v; }); + if (it != last && it->id == id) { + penalize(*it, count); + } + } + cur_p->sorted = false; + return; } + } - cur_p->data[i].logit -= float(count) * ctx->penalty_freq + float(count > 0) * ctx->penalty_present; + // candidates reordered or truncated by an earlier sampler: the array is the smaller side + for (size_t i = 0; i < cur_p->size; ++i) { + const auto token_iter = ctx->token_count.find(cur_p->data[i].id); + if (token_iter == ctx->token_count.end()) { + continue; + } + penalize(cur_p->data[i], token_iter->second); } cur_p->sorted = false; @@ -3921,12 +3961,13 @@ static void llama_sampler_logit_bias_apply(struct llama_sampler * smpl, llama_to return; } - // search for the remaining candidates that were not found in the previous step + // search for the remaining candidates that were not found in the previous step. Every matching bias + // applies, as on the in-place path above: two biases on one token sum on both paths (Continuum fork: + // the subset path stopped at the first, which ballpark sampling exposed; Codex on #122) for (size_t i = 0; i < cur_p->size; ++i) { for (const auto & lb : ctx->to_search) { if (cur_p->data[i].id == lb.token) { cur_p->data[i].logit += lb.bias; - break; } } } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 10ec890fe2af..51d135ab9a1b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -181,6 +181,8 @@ if (LLAMA_LLGUIDANCE) endif () llama_build(test-recurrent-state-rollback.cpp) +llama_build_and_test(test-sampler-penalties.cpp) +llama_build(test-sampler-coarse.cpp) # needs -m : ballpark sampling picks exactly the full path's token llama_build_and_test(test-server-view-end.cpp) # GGML_TENSOR_FLAG_GRAD: a leaf whose gradient the backward computes, never optimized (the walk reads the cached prefix K/V gradient) diff --git a/tests/test-sampler-coarse.cpp b/tests/test-sampler-coarse.cpp new file mode 100644 index 000000000000..a21cc8e7e0ff --- /dev/null +++ b/tests/test-sampler-coarse.cpp @@ -0,0 +1,263 @@ +// what this catches: the ballpark-first sampler (common/sampling.cpp, coarse_cap; CONTINUUM-ENGINE 4.7.13) +// picks EXACTLY the token the full-vocabulary path picks, on a real model's logits, step after step: +// two samplers with the same parameters and seed, one eligible for the ballpark path and one forced onto +// the full path (n_probs = 1 makes it ineligible), sample every step of a long generation with penalties +// active and the window sliding; any difference fails. Prints each path's per-token time (alternating +// which goes first) and the ballpark path's counters (cap, reseeds, widens, mean candidates). +// +// usage: test-sampler-coarse -m +#include "arg.h" +#include "common.h" +#include "sampling.h" +#include "llama.h" + +#include +#include +#include +#include +#include +#include + +int main(int argc, char ** argv) { + std::setlocale(LC_NUMERIC, "C"); + common_params params; + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + common_init(); + llama_backend_init(); + auto init = common_init_from_params(params); + llama_model * model = init->model(); + llama_context * ctx = init->context(); + if (model == nullptr || ctx == nullptr) { std::fprintf(stderr, "FAILED: model did not load\n"); return 1; } + + const llama_vocab * vocab = llama_model_get_vocab(model); + common_params_sampling base; + base.temp = 0.8f; base.top_k = 40; base.top_p = 0.95f; base.min_p = 0.05f; + base.penalty_last_n = 256; base.penalty_repeat = 1.1f; base.penalty_freq = 0.2f; base.penalty_present = 0.1f; + base.seed = 1234; + + // one case: two samplers (ballpark-eligible, and the full-vocabulary reference), the same prompt, the + // same seed; `clone_each_step` samples the ballpark side through a fresh clone (speculative verify); + // `prefix_accept` is accepted as generated by both before sampling (e.g. an opened think block) + auto run_case = [&](const char * name, common_params_sampling sp, bool clone_each_step, const std::string & prefix_accept) { + llama_memory_seq_rm(llama_get_memory(ctx), 0, -1, -1); + common_params_sampling sp_full = sp; + sp_full.n_probs = 1; // ineligible for the ballpark path: the full-vocabulary reference + common_sampler * coarse = common_sampler_init(model, sp); + common_sampler * full = common_sampler_init(model, sp_full); + std::vector prompt = common_tokenize(vocab, "Write a long story about a lighthouse keeper who repeats himself." + prefix_accept, true, true); + for (const auto t : common_tokenize(vocab, prefix_accept, false, true)) { + common_sampler_accept(coarse, t, true); + common_sampler_accept(full, t, true); + } + llama_batch batch = llama_batch_init(512, 0, 1); + for (size_t i = 0; i < prompt.size(); ++i) common_batch_add(batch, prompt[i], (llama_pos) i, { 0 }, i + 1 == prompt.size()); + if (llama_decode(ctx, batch) != 0) { std::fprintf(stderr, "FAILED: %s: prompt decode\n", name); std::exit(1); } + llama_pos pos = (llama_pos) prompt.size(); + const int steps = 400; + double us_coarse = 0, us_full = 0; + int done = 0; + for (int s = 0; s < steps; ++s) { + llama_synchronize(ctx); + llama_token a, b; + auto time = [&](common_sampler * smpl, double & acc, bool clone) { + common_sampler * use = clone ? common_sampler_clone(smpl) : smpl; + auto t0 = std::chrono::steady_clock::now(); + const llama_token id = common_sampler_sample(use, ctx, -1); + acc += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (clone) common_sampler_free(use); + return id; + }; + // both sides sample through a clone when cloning, so their random streams stay in step (a clone's + // RNG advances, the original's does not: cloning one side only is a test asymmetry, not a check) + if (s % 2 == 0) { a = time(coarse, us_coarse, clone_each_step); b = time(full, us_full, clone_each_step); } + else { b = time(full, us_full, clone_each_step); a = time(coarse, us_coarse, clone_each_step); } + if (a != b) { + std::fprintf(stderr, "FAILED: %s: step %d: ballpark picked %d, the full vocabulary picked %d\n", name, s, a, b); + std::exit(1); + } + common_sampler_accept(coarse, a, true); + common_sampler_accept(full, b, true); + done++; + if (llama_vocab_is_eog(vocab, a)) break; + common_batch_clear(batch); + common_batch_add(batch, a, pos++, { 0 }, true); + if (llama_decode(ctx, batch) != 0) { std::fprintf(stderr, "FAILED: %s: decode\n", name); std::exit(1); } + } + size_t cap = 0; uint64_t calls = 0, reseeds = 0, widens = 0, cands = 0; + common_sampler_coarse_stats(coarse, &cap, &calls, &reseeds, &widens, &cands); + std::printf("%-18s identical over %3d steps; per token ballpark %.1f us, full %.1f us; cap %zu, ballpark calls %llu, widens %llu, mean candidates %.0f\n", + name, done, us_coarse / done, us_full / done, cap, (unsigned long long) calls, (unsigned long long) widens, + calls ? (double) cands / (double) calls : 0.0); + common_sampler_free(coarse); + common_sampler_free(full); + llama_batch_free(batch); + }; + + run_case("plain", base, false, ""); + + // a reasoning budget that FORCES the end of a think block mid-generation + { + common_params_sampling sp = base; + sp.reasoning_budget_start = common_tokenize(vocab, "", false, true); + sp.reasoning_budget_end = { common_tokenize(vocab, "", false, true) }; + sp.reasoning_budget_forced = common_tokenize(vocab, "\n", false, true); + sp.reasoning_budget_tokens = 40; + run_case("reasoning budget", sp, false, "\n"); + } + + // a lazy tool grammar (inactive until its trigger word appears) + { + common_params_sampling sp = base; + sp.grammar = common_grammar(COMMON_GRAMMAR_TYPE_USER, "root ::= \"\" [a-z ]+ \"\""); + sp.grammar_lazy = true; + sp.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "", LLAMA_TOKEN_NULL }); + run_case("lazy tool grammar", sp, false, ""); + } + + // logit biases (Codex on #122): ids outside the vocabulary are ignored on both paths (never read out of + // bounds), two biases on one token sum on both paths, and a raised token joins the candidates + { + common_params_sampling sp = base; + const llama_token the = common_tokenize(vocab, " the", false, false).at(0); + const llama_token n_v = llama_vocab_n_tokens(vocab); + sp.logit_bias = { + { -1, 5.0f }, { n_v, 5.0f }, { n_v + 1000, -5.0f }, // outside the vocabulary + { the, 3.0f }, { the, 4.0f }, // duplicates: +7 on both paths + { the + 1, -2.0f }, + }; + run_case("logit biases", sp, false, ""); + } + + // NaN logits (Codex on #122): the widening loop must end and the step must sample exactly as the full + // array does, whether every logit is NaN, all but a few are, or a few are + { + const int n_v = llama_vocab_n_tokens(vocab); + std::vector logits(n_v); + for (const int finite : { 0, 100, n_v - 1000 }) { + for (const float poison : { NAN, INFINITY }) { + for (int i = 0; i < n_v; ++i) { + // distinct finite values (7919 is prime, so i*7919 mod finite permutes them): with ties, top-k's + // order among equals is unspecified on both paths and "the same token" means nothing + logits[i] = i < finite ? 10.0f * (float) (((int64_t) i * 7919) % finite) / (float) finite : poison; + } + common_sampler_row row; + row.logits = logits.data(); + row.n_vocab = n_v; + common_sampler * coarse = common_sampler_init(model, base); + common_params_sampling full_params = base; + full_params.n_probs = 1; // not ballpark-eligible: the full array + common_sampler * full = common_sampler_init(model, full_params); + for (int step = 0; step < 8; ++step) { + const llama_token a = common_sampler_sample_row(coarse, row); + const llama_token b = common_sampler_sample_row(full, row); + // +inf ties every poisoned token at the maximum: top-k's order among equals is unspecified on + // both paths, so the meaningful identity is that both pick a maximal (+inf) token; NaN never ties + const bool same = std::isinf(poison) && finite < n_v ? (std::isinf(logits[a]) && std::isinf(logits[b])) : a == b; + if (!same) { + std::fprintf(stderr, "FAILED: non-finite logits (%d finite): ballpark %d, full %d\n", finite, a, b); + return 1; + } + } + common_sampler_free(coarse); + common_sampler_free(full); + std::printf("%-18s %d finite of %d, the rest %s: the ballpark step ended and matched the full array (a maximal token under +inf ties)\n", + "non-finite logits", finite, n_v, std::isnan(poison) ? "NaN" : "+inf"); + } + } + } + + // a +inf seed (Codex on #122): +inf on exactly the strided seed sample's positions, fewer than cap tokens, + // so the seed is +inf, the first scan finds too few, and +inf - +inf made the widening step NaN forever + { + const int n_v = llama_vocab_n_tokens(vocab); + std::vector logits(n_v); + for (int i = 0; i < n_v; ++i) { + logits[i] = (i % 16 == 0 && i < 16 * 40) ? INFINITY : 10.0f * (float) (((int64_t) i * 7919) % n_v) / (float) n_v; + } + common_sampler_row row; + row.logits = logits.data(); + row.n_vocab = n_v; + common_sampler * coarse = common_sampler_init(model, base); + for (int step = 0; step < 8; ++step) { + const llama_token a = common_sampler_sample_row(coarse, row); + if (!std::isinf(logits[a])) { + std::fprintf(stderr, "FAILED: +inf seed: picked %d, not one of the 40 maximal tokens\n", a); + return 1; + } + } + common_sampler_free(coarse); + std::printf("%-18s 40 +inf tokens on the seed's sample positions: the step ended on a maximal token\n", "+inf seed"); + } + + // Codex on #122, to keep the identity claim precise: + // (a) finite ties: which tied token wins is unspecified on both paths, so with greedy sampling both must + // pick a token holding the maximum logit; + // (b) +inf then finite on ONE sampler: the degenerate step ends on a maximal token, and the threshold it + // leaves behind never skews the finite steps after it (exact identity, step by step) + { + const int n_v = llama_vocab_n_tokens(vocab); + std::vector tied(n_v); + for (int i = 0; i < n_v; ++i) { + tied[i] = (float) ((i * 7919) % 1000) / 100.0f; // 1,000 distinct values: every value ~248 times + } + common_params_sampling greedy = base; + greedy.temp = 0.0f; + common_params_sampling greedy_full = greedy; + greedy_full.n_probs = 1; + common_sampler_row tied_row; + tied_row.logits = tied.data(); + tied_row.n_vocab = n_v; + common_sampler * gc = common_sampler_init(model, greedy); + common_sampler * gf = common_sampler_init(model, greedy_full); + const float top = *std::max_element(tied.begin(), tied.end()); + for (int step = 0; step < 8; ++step) { + const llama_token a = common_sampler_sample_row(gc, tied_row); + const llama_token b = common_sampler_sample_row(gf, tied_row); + if (tied[a] != top || tied[b] != top) { + std::fprintf(stderr, "FAILED: finite ties: ballpark %d (%.2f), full %d (%.2f), max %.2f\n", a, tied[a], b, tied[b], top); + return 1; + } + } + common_sampler_free(gc); + common_sampler_free(gf); + std::printf("%-18s 1,000 values over %d tokens, greedy: both paths pick a maximal token\n", "finite ties", n_v); + + std::vector spiked(n_v), clean(n_v); + for (int i = 0; i < n_v; ++i) { + clean[i] = 10.0f * (float) (((int64_t) i * 7919) % n_v) / (float) n_v; // distinct + spiked[i] = (i % 16 == 0 && i < 16 * 40) ? INFINITY : clean[i]; + } + common_sampler_row spiked_row, clean_row; + spiked_row.logits = spiked.data(); spiked_row.n_vocab = n_v; + clean_row.logits = clean.data(); clean_row.n_vocab = n_v; + common_params_sampling full_params = base; + full_params.n_probs = 1; + common_sampler * c = common_sampler_init(model, base); + common_sampler * f = common_sampler_init(model, full_params); + const llama_token a0 = common_sampler_sample_row(c, spiked_row); + const llama_token b0 = common_sampler_sample_row(f, spiked_row); + if (!std::isinf(spiked[a0]) || !std::isinf(spiked[b0])) { + std::fprintf(stderr, "FAILED: +inf then finite: the +inf step picked %d / %d, not maximal\n", a0, b0); + return 1; + } + for (int step = 1; step <= 8; ++step) { + const llama_token a = common_sampler_sample_row(c, clean_row); + const llama_token b = common_sampler_sample_row(f, clean_row); + if (a != b) { + std::fprintf(stderr, "FAILED: +inf then finite: step %d ballpark %d, full %d\n", step, a, b); + return 1; + } + } + common_sampler_free(c); + common_sampler_free(f); + std::printf("%-18s one sampler: the +inf step ends on a maximal token, then 8 finite steps identical\n", "+inf then finite"); + } + + // speculative verify: the ballpark side samples through a clone every step + run_case("clone each step", base, true, ""); + + std::printf("test-sampler-coarse: ok\n"); + return 0; +} diff --git a/tests/test-sampler-penalties.cpp b/tests/test-sampler-penalties.cpp new file mode 100644 index 000000000000..a7f412e05eea --- /dev/null +++ b/tests/test-sampler-penalties.cpp @@ -0,0 +1,93 @@ +// what this catches: the penalties sampler walks the recent history, not the vocabulary +// (CONTINUUM-ENGINE 4.7.13). Without a model: on id-ordered (the default chain), shuffled and truncated +// candidate arrays at a real vocabulary size, the result equals the reference per-candidate loop +// exactly; and the per-token time of the fast path is printed against the reference. +#include "llama.h" + +#include +#include +#include +#include +#include +#include +#include + +static void require(bool ok, const char * what) { + if (!ok) { std::fprintf(stderr, "FAILED: %s\n", what); std::exit(1); } +} + +// the reference: upstream's loop, one hash lookup per candidate +static void reference(std::vector & cur, const std::unordered_map & counts, + float repeat, float freq, float present) { + for (auto & d : cur) { + auto it = counts.find(d.id); + if (it == counts.end()) continue; + const int count = it->second; + if (d.logit <= 0) d.logit *= repeat; else d.logit /= repeat; + d.logit -= float(count) * freq + float(count > 0) * present; + } +} + +int main() { + const int32_t V = 248320; // Qwen3.5/3.6 vocabulary + const int32_t last_n = 256; + const float repeat = 1.1f, freq = 0.2f, present = 0.1f; + std::mt19937 rng(7); + std::uniform_real_distribution logit(-20.0f, 20.0f); + std::uniform_int_distribution tok(0, V - 1); + + llama_sampler * smpl = llama_sampler_init_penalties(V, last_n, repeat, freq, present); + std::unordered_map counts; + std::vector history; + for (int i = 0; i < 400; ++i) { // more than last_n: the window slides + const llama_token t = i % 5 == 0 ? 42 : tok(rng); // some repeats + llama_sampler_accept(smpl, t); + history.push_back(t); + } + for (size_t i = history.size() - (size_t) last_n; i < history.size(); ++i) counts[history[i]]++; + + std::vector base(V); + for (int32_t i = 0; i < V; ++i) base[(size_t) i] = { i, logit(rng), 0.0f }; + + auto run = [&](std::vector cur) { + llama_token_data_array arr = { cur.data(), cur.size(), -1, false }; + llama_sampler_apply(smpl, &arr); + cur.resize(arr.size); + return cur; + }; + auto same = [](const std::vector & a, const std::vector & b) { + if (a.size() != b.size()) return false; + for (size_t i = 0; i < a.size(); ++i) if (a[i].id != b[i].id || a[i].logit != b[i].logit) return false; + return true; + }; + + // id-ordered (the default chain: penalties first) + { auto ref = base; reference(ref, counts, repeat, freq, present); require(same(run(base), ref), "id-ordered equals the reference"); } + // shuffled (an earlier sampler reordered) + { auto sh = base; std::shuffle(sh.begin(), sh.end(), rng); auto ref = sh; reference(ref, counts, repeat, freq, present); require(same(run(sh), ref), "shuffled equals the reference"); } + // truncated (top-k ran first) + { std::vector tr(base.begin(), base.begin() + 40); auto ref = tr; reference(ref, counts, repeat, freq, present); require(same(run(tr), ref), "truncated equals the reference"); } + // a sorted head that is NOT aligned but large + { auto rv = base; std::reverse(rv.begin(), rv.end()); auto ref = rv; reference(ref, counts, repeat, freq, present); require(same(run(rv), ref), "reversed equals the reference"); } + + // the per-token receipt + const int reps = 200; + auto time_us = [&](auto && f) { + auto work = base; + const auto t0 = std::chrono::steady_clock::now(); + for (int r = 0; r < reps; ++r) { work = base; f(work); } + auto copy_t0 = std::chrono::steady_clock::now(); + for (int r = 0; r < reps; ++r) { work = base; } + const auto t1 = std::chrono::steady_clock::now(); + // subtract the per-rep copy of the candidate array (both variants pay it in this harness) + return (std::chrono::duration(copy_t0 - t0).count() - std::chrono::duration(t1 - copy_t0).count()) / reps; + }; + const double ref_us = time_us([&](std::vector & w) { reference(w, counts, repeat, freq, present); }); + const double fast_us = time_us([&](std::vector & w) { llama_token_data_array a = { w.data(), w.size(), -1, false }; llama_sampler_apply(smpl, &a); }); + std::printf("penalties per token, V = %d, %zu distinct recent tokens: reference %.1f us, history walk %.1f us\n", + V, counts.size(), ref_us, fast_us); + + llama_sampler_free(smpl); + std::printf("test-sampler-penalties: ok\n"); + return 0; +} diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index af5d3fff080e..1745c8cca2c2 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -982,6 +982,9 @@ struct server_context_impl { common_params params_base; // note: keep these alive - they determine the lifetime of the model, context, etc. + // whether any configured drafter reads the prompt's tokens (the n-gram family); set at load + bool spec_reads_prompt = false; + common_init_result_ptr llama_init; llama_context * ctx_tgt = nullptr; @@ -1417,6 +1420,13 @@ struct server_context_impl { n_swa = params_base.swa_full ? 0 : llama_model_n_swa(model_tgt); + spec_reads_prompt = std::any_of(params_base.speculative.types.begin(), params_base.speculative.types.end(), + [](common_speculative_type t) { + return t == COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE || t == COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K || + t == COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V || t == COMMON_SPECULATIVE_TYPE_NGRAM_MOD || + t == COMMON_SPECULATIVE_TYPE_NGRAM_CACHE; + }); + // Necessary similarity of prompt for slot selection slot_prompt_similarity = params_base.slot_prompt_similarity; @@ -3511,7 +3521,11 @@ struct server_context_impl { return; // no draft this step } - slot.spec_prompt = slot.prompt.tokens.get_text_tokens(); + // only the n-gram drafters read the prompt's tokens (MTP and model drafters do not): build + // the whole-context copy for them alone, never per step for nobody (CONTINUUM-ENGINE 4.7.13) + if (spec_reads_prompt) { + slot.spec_prompt = slot.prompt.tokens.get_text_tokens(); + } common_speculative_get_draft_params(spec.get(), slot.id) = { /* .drafting = */ true,