Skip to content

Per-token CPU: penalties walk history, ballpark-first sampling, save points without scratch, spec prompt only for n-gram drafters - #122

Open
joelteply wants to merge 11 commits into
codex/s4-per-mind-integrationfrom
fable/per-token-sampling
Open

joelteply wants to merge 11 commits into
codex/s4-per-mind-integrationfrom
fable/per-token-sampling

Conversation

@joelteply

@joelteply joelteply commented Nov 16, 2026 •

Copy link
Copy Markdown

Five exact per-token savings, rebased onto the line that carries the canary pin (b5534b5) and #118. No token changes: identity is proven, not assumed.

Change Before After
Penalties walk the recent history (in place when id-aligned, binary search on an id-sorted subset) 366.8 us/token 0.7 us
Ballpark-first sampling: carried absolute threshold, vectorized block scan, exact top-k on the few; full array while the reasoning budget forces or grammar-first 116.9 us/token 82.3 us
Sampler save point (spec verify) carries state, never the cur scratch 42 + 39 us/verify step 2.1 + 0.2 us
spec_prompt (whole-context copy) built only when an n-gram drafter reads it; MTP never did ~544 KB copy/token at 136k 0

Measured (this branch, d76bf42, M5, 2026-11-16, qwen35-0.8b)

  • test-sampler-penalties: reference 366.8 us vs history walk 0.7 us, identical logits; ok.
  • test-sampler-coarse: identical token at every one of 400 steps in each of plain, reasoning budget (incl. forced end), lazy tool grammar, clone each step; ok.
  • Regression, kept in the claim: the clone each step case (a fresh common_sampler_clone sampled from every step) is SLOWER with the ballpark path: 136.7 us vs 128.5 us full. A fresh clone carries no learned threshold, so every sample re-seeds. The live server does not sample from clones (speculative verify samples on the slot's sampler; the clone is only a save point, restored on rollback), so the live path is the plain/budget/grammar rows. A workload that samples from fresh clones should expect ~6% more CPU per token.
  • llama-server --spec-type draft-mtp, two prompts at temperature 0: text identical to the pre-change build, draft acceptance identical (29/50, 31/47).
  • 0 build warnings.

Measured after deploy

Owner Fable, with the next pin bump: 15-minute live read on the M5 residents (acts/h, /props step_budget host time, gpu_time busy share, tok/s) against the current pin. Card stays open until posted.

Conflict notes: tests/CMakeLists.txt kept only the penalties/coarse tests (the parked-seq test belongs to an unmerged line); spec_reads_prompt re-anchored without the parked pool.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

joelteply and others added 5 commits November 16, 2026 10:21
…us -> ~1 us per token)

CONTINUUM-ENGINE 4.7.13 clog audit, row 2 (verified by reading src/llama-sampler.cpp): the
penalties sampler did an unordered_map::find for EVERY candidate (the whole vocabulary, 248,320 on
Qwen3.5/3.6) though only the at most penalty_last_n tokens in the recent history can match; the core
always sends repeat_penalty, so this ran on every token of every act, in series after the GPU sync.

Now it walks the history map. While the candidates are still in token-id order (data[id].id == id,
penalties first in the chain as by default) each penalty applies in place at data[id]; when an
earlier sampler reordered or truncated the array, the original per-candidate loop runs (the array is
then the smaller side). The arithmetic is unchanged (one shared lambda).

test-sampler-penalties (no model, V = 248,320, 400 accepted tokens over a 256 window, 206 distinct):
results equal the reference loop bit for bit on id-ordered, shuffled, truncated and reversed arrays;
per token: reference 293.5-378.6 us, history walk 0.7-1.2 us (3 runs, M5 Pro). 0 build warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit e3824bb)
…identical tokens)

Joel 2026-11-16: "get the size down that you need the more expensive sorting, filtering or
calculation on. Get in the ballpark first"; "Think about why something might be slower first."

When every sampler before top-k can only LOWER a logit (penalties with repeat >= 1, freq/presence
>= 0, negative biases, disabled DRY/top-n-sigma) the post-adjustment top-k lies inside the raw
top-(k + h), h = the tokens that can be lowered, plus any positively biased token. So the chain runs
unchanged on the logits at or above a threshold that keeps at least that many: the same token as
over the whole vocabulary, without building a vocabulary-sized array. Grammar-first passes and a
grammar rejection's resample still use the full array; clones (speculative verify) keep the path.

How it got here (each step reasoned from counters, not just timed):
- the per-block test is an OR of comparisons (vectorizes; a float max reduction does not without
  fast-math);
- the threshold is carried from the previous step as an ABSOLUTE logit at an adaptive RANK: the cut
  is a tail quantile of the bulk distribution, stable step to step (carrying it relative to the
  spiky max tripled the misses; a margin in logit units swept in thousands of candidates);
- a three-point cost model (~23 us per full scan, ~27 ns per candidate) showed candidates were
  expensive, mostly the penalties hash per candidate: penalties now binary-search an id-sorted
  subset (llama-sampler.cpp), beside the full-array in-place path;
- the rank balances ONLINE between the two costs (a miss raises it, a hit lowers it slowly), and a
  miss re-seeds from a strided-sample estimate instead of crawling.

test-sampler-coarse (qwen35-0.8b, M5, 600 steps, temperature 0.8, top-k 40, top-p 0.95, min-p 0.05,
penalties 256/1.1/0.2/0.1, two samplers with one seed, alternating which runs first): IDENTICAL
tokens at every step, 3 runs; per token 77.5-78.0 us vs 112.3-114.4 us for the full path; counters:
cap 296, 1 seed, 46 widens in 600 steps, 1,501 mean candidates. test-sampler-penalties still
bit-identical (0.8 us). 0 build warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit db67276)
…rces; identity proven under budget, lazy grammar and clones

Writing the reasoning-budget case found a real bug before it ran: while the budget is FORCING it sets
every candidate but the forced token to -inf, and the forced token need not be inside a ballpark
subset, so every logit would be -inf. While forcing, the full array is used (only one token matters).

test-sampler-coarse now runs four cases on qwen35-0.8b, each two samplers (ballpark-eligible and the
full-vocabulary reference, same seed, alternating order), 400 steps, IDENTICAL tokens at every step:
plain 84.6 vs 123.8 us per token; reasoning budget (40 tokens, forcing the end of the think block)
75.4 vs 123.0; lazy tool grammar 85.2 vs 121.4; clone each step (speculative verify) 138.6 vs 130.2.
The clone case first FAILED at step 40: the test cloned only the ballpark side, so the original's RNG
never advanced while the reference's did (a test asymmetry, not a sampler bug); both sides now sample
through clones. A discarded clone also discards its carried threshold, so each clone re-seeds:
carrying it back on discard is a follow-up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 51278e6)
…ratch (42 us + 39 us per verify step -> 2.1 us + 0.2 us)

Asking what a clone's consumer needs: speculative verify clones the slot's sampler as a SAVE POINT
(server-context.cpp, smpl_save) and copies it back on a rollback. common_sampler_clone and
common_sampler_copy both copied `cur`, the candidate scratch array, which set_logits rebuilds before
every read: on the full path a 248k-entry (~3 MB) copy per verify step, and with MTP the M5 verifies
on every token. Now the scratch is never copied; the save point carries the state (chain, grammar,
reasoning budget, penalty history, RNG, the ballpark threshold).

Measured (qwen35-0.8b, M5, 2,000 reps): full path clone 42.2 us -> 2.1 us, copy 39.3 us -> 0.2 us;
ballpark path 2.2 -> 2.1 us. test-sampler-coarse: identical tokens in all four cases (plain, reasoning
budget, lazy grammar, clone each step). 0 build warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit f880d02)
…ead it (not per token for MTP)

CONTINUUM-ENGINE 4.7.13 audit row 7/9, verified: every draft step rebuilt slot.spec_prompt with
get_text_tokens(), a fresh allocation and a filtered copy of the slot's WHOLE token list (~544 KB at
136k tokens), per token. Its consumer is only the n-gram drafters (ngram_simple, ngram_map_k, _k4v,
ngram_mod, ngram_cache read dp.prompt each step); MTP, eagle3, dflash and draft-model drafters read
the prompt once in begin() (common_speculative_begin at task start), and the only other reader was a
debug log of its size (now n_past). The M5 runs draft-mtp, so the copy was pure waste there. Now it is
built only when an n-gram drafter is configured (spec_reads_prompt, set at load).

Receipt, qwen35-0.8b --spec-type draft-mtp, the afternoon's two prompts at temperature 0: text
identical to the earlier build and draft acceptance identical (29/50, 31/47). 0 build warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit 1b5c258)
@joelteply

Copy link
Copy Markdown
Author

Blocking review finding on d76bf42: positive logit-bias token IDs are copied into coarse_raised without a vocabulary-range check, then coarse_candidates indexes logits[coarse_ids[k]]. A bias {-1,+1} or {n_vocab,+1} therefore becomes an out-of-bounds read whenever the coarse path is eligible. The existing full-array logit-bias apply only updates candidates whose IDs match, so these entries previously did not index the logit array directly. Please validate token IDs at the sampler input owner before storing them, with negative and upper-bound tests; do not silently map them to another token.

Also exercise duplicate bias entries on one valid token in the subset identity test: the id-aligned full-array apply accumulates each bias, whereas the current to_search subset loop breaks on the first matching entry. Introducing the subset can expose a different distribution even though both samplers see the same bias list. Either prove the public sampler boundary forbids duplicates or give both candidate shapes the same defined accumulation semantics.

Review not complete; do not merge this head yet. The measured plain/budget/grammar cases do not cover these bias configurations.

…nd two biases on one token sum on every path (Codex's review of #122)

- common_sampler_init: a positive bias on an id outside [0, n_vocab) no longer joins the raised candidates
  (it indexed logits out of bounds); the full path ignores such ids too.
- llama_sampler_logit_bias_apply: the search path stopped at a token's first bias while the in-place path
  added each, so duplicate biases summed on one path and not the other; ballpark sampling takes the search
  path routinely. Every matching bias now applies on both.

test-sampler-coarse "logit biases" (ids -1, n_vocab, n_vocab+1000; +3 and +4 on one token; a negative
bias): identical over 400 steps (ballpark 73.3 us vs full 363.9 us per token). With the old break restored
it fails at step 0 (ballpark 271, full 279), so the case guards the defect. Every other case still
identical; penalties test ok; 0 warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Follow-up on f83f556: the bias-range and duplicate-accumulation fixes address the two concrete findings; the reported red-before duplicate case is the right regression.

One remaining fault-path blocker: coarse_candidates widens while n < cap with no termination for NaN logits. coarse_scan never includes a NaN (even at -infinity), so if fewer than cap vocabulary entries compare successfully, the engine loops forever on that step. This is especially important for a model/backend fault: it must report failure rather than wedge all residents on the server loop. Bound widening and route invalid logits through the existing sampling failure contract; add an all-NaN and mixed-NaN fixture. I am not requesting a different sampler/distribution as a fallback.

…en, the exact path); a row is sampled without the context

Codex's review of #122: `while (n < cap)` never ended when fewer than cap logits are not NaN (NaN never
compares at or above any threshold, even -inf), so an all-NaN or mostly-NaN model output wedged the slot.
Now, once the threshold reaches -inf with fewer than cap candidates, every non-NaN logit is already in:
coarse_candidates reports that and the step samples the full array, which is the exact path itself, so
NaN input behaves exactly as it does without the ballpark (never a different sampler). The strided seed
sample skips NaN (it breaks nth_element's ordering), and the miss margin is capped at the vocabulary
(an unbounded margin made the rank cast undefined).

The row seam (common_sampler_row, sample_row, sample_and_accept_rows) moves down from #125: sampling from
a gathered row reads only the sampler, which is what lets the test feed fabricated logits.

test-sampler-coarse "NaN logits": 0, 100 and 247,320 finite of 248,320 (distinct values, NaN for the
rest): the step ends and matches the full array over 8 steps each. With the bound removed the test hangs
until a 60 s alarm kills it, printing no NaN line. Every earlier case still identical over 400 steps;
penalties ok; 0 warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Follow-up review of exact 580284c: the negative-infinity exit handles the reported NaN-shortfall case, but widening still has a non-terminating positive-infinity case.

Give the strided sample enough +inf entries for coarse_seed to return +inf, while the total number of +inf entries is below cap (for cap about 296, roughly 40 +inf values at sampled positions suffice). Then n < cap, thr - seeded is inf - inf = NaN, step becomes NaN, and std::min(seeded, thr - step) retains +inf. Every rescan has the same n forever; the new thr == -INFINITY branch never fires.

Please bound widening by actual progress, and cover +inf and a carry-over +inf threshold followed by a finite row as well as the NaN rows. Retain the existing full-chain numerical behavior rather than introducing a different sampling policy. This is still a merge blocker until the fault replay terminates.

…d NaN steps end it (Codex's re-review of #122)

A +inf seed made the widening step +inf - +inf = NaN, and min(+inf, NaN) kept the threshold at +inf
forever. Now a widening that does not strictly lower the threshold goes straight to -inf, where the
existing check ends it and the step takes the full array (the exact path). Termination no longer depends
on which non-finite value stalled it.

test-sampler-coarse "+inf seed": 40 +inf tokens placed on exactly the strided seed sample's positions
(fewer than cap), so the seed is +inf and the first scan finds too few: the step ends on a maximal (+inf)
token, 8 steps. Without the progress bound the test hangs until a 60 s alarm (no "+inf seed" line).
"non-finite logits" now also poisons with +inf (0, 100, 247,320 finite): under +inf ties top-k's order
among equals is unspecified on both paths, so the asserted identity is that both pick a maximal token;
NaN cases still match exactly. Every earlier case identical; penalties ok; 0 warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Rechecked the widening delta at e52217b: the strict next < thr progress guard resolves my +inf non-termination finding. The earlier invalid/duplicate bias corrections remain intact.

Before a blanket token-identity claim, please also retain a finite-logit tie replay against the unchanged full path (both the chosen top-k boundary and equal maxima), plus an infinite-threshold step followed by a finite step on the same sampler. The new +inf fixture intentionally checks only maximal-token membership, which is a useful fault-termination claim but is not identical-token evidence. Keep those claims separate in the receipt. Exact-head CI is not reported on this branch yet, so this is not merge approval.

…(Codex's re-review of #122)

finite ties: 1,000 values over 248,320 tokens, greedy: both paths pick a token holding the maximum logit
(which tied token wins is unspecified on both). +inf then finite: one ballpark and one full sampler see
the +inf-seed row (ends on a maximal token), then 8 finite distinct rows: identical every step, so the
threshold a degenerate step leaves never skews the next. Every earlier case still identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply and others added 2 commits November 16, 2026 12:47
@joelteply

Copy link
Copy Markdown
Author

Re-review currentccf32dd1681468209aad5f6e0318829708ea43dd: finite-tie regression tests only membership in the maximum-score set, not token identity; comments still claim the same token as the full vocabulary. Please make the acceptance claim precise. For the ordinary finite-logit path, test tied scores with the live stochastic chain and identical RNG state, as well as greedy. If the optimized subset changes tied-token order and therefore seeded outputs, either preserve the full-path tie behavior or explicitly document the changed guarantee instead of calling the test token-identical. +inf degenerate behavior can remain separately classified; finite ties are valid ordinary input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant