Skip to content

qwen4_exp: MTP past the QSA inert bound (opt-in per-row verify) + three speculative-path safety fixes - #51

Merged
AzeezIsh merged 6 commits into
Atlas-Inf:feat/flashnext-nvidiafrom
andrew-vogulkin:flashnext/mtp-past-qsa-bound
Sep 22, 2026
Merged

AzeezIsh merged 6 commits into
Atlas-Inf:feat/flashnext-nvidiafrom
andrew-vogulkin:flashnext/mtp-past-qsa-bound

Conversation

@andrew-vogulkin

@andrew-vogulkin andrew-vogulkin commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Makes MTP speculation engage past the QSA inert bound (2,051 tokens) on Qwen3.8-Flash-Next — roadmap item W1 for #35 — behind an opt-in switch, plus three small speculative-path safety fixes and a top-k contract tidy-up found along the way. Targets feat/flashnext-nvidia so it lands in #35. Six commits, each standalone; the last one (a kernel edit) can be dropped without affecting the rest.

Why speculation was inert. The batched multi-row attention path (qwen3_attention/trait_impl/multi_seq/mod.rs, shared by MTP verify, n-gram verify and concurrent decode) ran dense batched attention and only afterwards looped over rows calling decode_select for ingest, erroring on Some. There was no selection hook, so the scheduler latched every sequence serial one step before 2,051. It was not the host top-k and not rollback: rewind_verify is already exact and reached exactly once per verify on every MTP lane and the n-gram lane.

The change (ATLAS_QSA_VERIFY_ACTIVE=1; unset = behaviour unchanged).

  • multi_seq/qsa_rows.rs (new): for each row, in order, decode_select → the same bs=1 selected attention the serial path uses (dense bs=1 for a row still inside the bound). It is R serial indexer steps by construction, so indexer state equals serial state. Select → gather → attend is strictly interleaved per row, because a QsaSelection points at layer-owned scratch that the next decode_select overwrites. The batched dense pass it replaces is skipped. No new kernels.
  • guard.rs: the pre-mutation refusal becomes an allow-list decided by a pure function — highway layer, non-MLA, BF16 KV, rows of one sequence, no parallel comm, no high-speed-swap, switch on. The same static predicate drives verify_context_limit(), so scheduler and layer cannot disagree.
  • First landing is the MTP lane at C=1 only: multi-sequence verify batches and the n-gram lane keep today's limit. Every risk found in review needs ≥2 concurrent sequences (KV exhaustion inside a batched verify finishes the whole batch instead of preempting; batched MTP bootstrap reads stale hidden rows once decode_a2 routes per-sequence).

Measured on one GB10

RadixArk NVFP4 pack, this exact tree, --speculative --num-drafts 1 --mtp-gate force, --max-seq-len 32768 --kv-cache-dtype bf16, util 0.88, ATLAS_QSA_DEVICE_TOPK=1, C=1, greedy, thinking off, 384-token completions. One request per cell — indicative, not a gate record.

leg 1.1K prompt (below the bound) 6.3K prompt 21.6K prompt (host top-k arm)
no --speculative 18.4 tok/s 17.9 tok/s 17.7 tok/s
speculative, switch off — 18.3 tok/s · mtp=0.00 · mtp declined: qsa_active seq_len=6269 … lim=2051 18.0 tok/s · mtp=0.00
speculative, switch on + ATLAS_QSA_TOPK_VERIFY=1 — 22.4 tok/s · mtp=1.00 · p1 0.707 22.9 tok/s · mtp=1.00 · p1 0.722
speculative, switch on 24.6 tok/s · p1 0.714 23.1 tok/s (+26 %) · p1 0.707 · 159 accepted 22.9 tok/s (+27 %) · p1 0.722 · 161 accepted
  • 0 errors, 0 mtp declined, 0 indexer desyncs, 0 device-vs-host top-k mismatches with the switch on. TTFT unchanged (11.2 s / 55.4 s).
  • Cost of the per-row indexer work: speculative decode is 24.6 tok/s below the bound and 23.1 just past it, about 6 %. Acceptance is the same below and above the bound (0.71 / 0.71 / 0.72).
  • Greedy text is not identical to serial, and that is not new. Speculative vs serial on this binary diverges after 29 of 274 words below the bound (the existing batch-K numerics effect, cf. the match_frac 0.51 note), and after 151 / 28 words past it. Same order, so W1 shows no divergence beyond the known effect; the exit criterion should be the accuracy floor, not text identity. The cross-check leg and the plain leg produce identical text; the switch-off leg is identical to the no---speculative leg.
  • The #[ignore] GPU test for the top-k kernel (last commit) passes on the GB10.

Not measured: the nvidia pack, ST-995 / agentic with mtp>0, K>1, C>1, and anything against the accuracy floor. Those need the queue box.

Test plan

  • cargo fmt --all -- --check
  • cargo clippy -p atlas-core -p spark-model -p spark-server --tests -- -D warnings (real exit status 0; the template's --workspace --all-features form was not run)
  • SPDX check (scripts/check_spdx.py); 500-line cap: no touched file newly over (qwen3_attention/trait_impl.rs is at 496)
  • Tested against a real model / hardware — see above (RadixArk pack only)
  • Added tests: 26 new (25 GPU-free + one #[ignore] kernel test), one existing test moved — CPU-oracle (verify row == serial row for every block phase and widths 2–4; one shared selection cannot serve a window; rejection leaves exactly the accepted prefix intact, the boundary rewind_verify clamps to), selection geometry, rewind_verify (had none), the allow-list, scheduler limit selection, prefix-cache/finish, ceiling, self-spec, top-k order. On this tree: spark-model --lib 825 passed / 0 failed, scheduler + serve_phases 297 passed, atlas-core QSA reference 10 passed.

Notes for reviewers

  • ⚠️ Shared-trait change (AGENTS.md): a new defaulted verify_context_limit_multi_seq() on the Model and layer traits. Existing impls and test stubs are unaffected.
  • Commit 4, three fixes, no numerics change:
    • finish_sequence no longer writes a prefix-cache finish leaf after an engine error (tokens un-advanced, live recurrent state advanced → the retry of the same conversation restored it). The decision is read once at the top, because the blocking branch take()s engine_error before the caching line — a check placed there never fires for blocking clients (mutation-tested).
    • No speculative dispatch predicate looked at max_seq_len: with ≥2 drafts a verify row can land AT the ceiling and the indexer refuses it mid-forward ("error" instead of "length"). The MTP arm now declines that step. No effect at the default depth.
    • --self-speculative is refused at load on models with per-sequence aux state: the draft pass ingests indexer rows that are never rewound, so the first verify fails pos == ingested on every request.
  • Commits 5–6, top-k contract. Both host top-k sites share one total order (rank_cmp). The device kernel no longer excludes -inf blocks, so it always writes every id the gather reads. This is latent only: qsa_score takes the relu as fmaxf, so scores are never NaN (no fast-math on gb10; pinned by a reference test). Commit 6 is bit-identical for every reachable score but edits a decode-path kernel — drop it, or land it with a gate re-record.
  • trait_impl.rs sits at 496 lines; the next edit there needs a split.
  • Second opinion wanted: whether C≥2 should stay excluded until the bootstrap-hidden and KV-exhaustion issues are fixed (recommendation: yes).

CLA

AI-authored (Claude Code), in a session directed by @andrew-vogulkin; the design went through two independent adversarial review passes before implementation.

🤖 Generated with Claude Code

andrew-vogulkin and others added 6 commits September 21, 2026 22:00
…PU reference

Three GPU-free oracle tests for serving an ACTIVE QSA selection on the
verify path: each row of a (K+1)-row window selects exactly what serial
decode would at that position (sets and scores, every block phase, widths
2..=4); one shared selection cannot serve the window (a draft token closes
a block mid-window); and rejecting drafts leaves exactly the accepted prefix
intact - the blocks at or above kept/ratio are the ones a rollback must
re-pool, which is the boundary QsaIndexer::rewind_verify clamps to.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…nd the rewind

- select_geometry(pos, ratio, block_topk): the decode selection shape as a
  pure function, used by decode_select (behaviour unchanged) and table-tested
  at the inert bound and across block boundaries, where consecutive rows of a
  multi-row step each get their own shape.
- QsaIndexer::is_active_at(pos) on top of it, so callers stop re-deriving the
  bound.
- rewind_verify had no tests: counters land on the serial state of the
  accepted prefix for every block phase, never raise the pooled count, no-op
  on zero, and error without clamping on an over-rewind.
- Module header: prefill past the bound is NOT dense any more (prefill_select
  is wired into both prefill paths); say what vetoes graph capture today.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… one sequence, opt-in)

Past the QSA inert bound (2051 tokens) every speculative lane was latched
off, because the batched multi-row attention path had no selection hook: it
ran dense batched attention, then a per-row decode_select loop that errored
on Some. So MTP never engaged on any real prompt.

With ATLAS_QSA_VERIFY_ACTIVE=1 a verify window owned by ONE sequence is now
served per row (multi_seq/qsa_rows.rs): for each row in order, decode_select
then the bs=1 selected attention the serial path uses (dense bs=1 for a row
still inside the bound). It is R serial indexer steps by construction, so
indexer state equals serial state and rewind_verify stays exact. Select ->
gather -> attend is interleaved per row: a QsaSelection points at
layer-owned scratch that the next decode_select overwrites. The batched
dense pass it replaces is skipped, not computed and discarded.

- guard.rs: the pre-mutation refusal becomes an ALLOW-list decided as a pure
  function - highway layer, non-MLA, BF16 KV, rows of one sequence, no
  parallel comm, no high-speed-swap, switch on. Anything else refuses exactly
  as before, before any layer state is touched.
- verify_context_limit() lifts the bound from the same static allow-list, so
  scheduler and layer cannot disagree; a parallel serve keeps the bound.
- New verify_context_limit_multi_seq(): multi-sequence verify batches and the
  n-gram lane keep the conservative limit. Every risk found in review needs
  >= 2 concurrent sequences (batch-wide kill on KV exhaustion in verify,
  batched MTP bootstrap reading stale hidden rows when decode routes
  per-seq), so the first landing is the MTP lane at C = 1 only.
- Off (the default): behaviour is unchanged; below the bound the batched path
  is the same code as before (the ingest loop moved, verbatim, to qsa_rows.rs).

No new kernels. Measured on one GB10 (RadixArk NVFP4 pack, C=1, --num-drafts 1,
gate forced, greedy, thinking off): switch off -> "mtp declined" past 2051 and
18.3 / 18.0 tok/s at 6.3K / 21.6K prompt tokens; switch on -> mtp=1.00, 71-72%
acceptance, 23.1 / 22.9 tok/s, 0 errors, 0 top-k mismatches under
ATLAS_QSA_TOPK_VERIFY=1 (the 21.6K leg runs the host top-k arm). Not yet run on
the nvidia pack or against the accuracy floor.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…wing QSA verify

1. No prefix-cache finish leaf after an engine error (lifecycle.rs).
   finish_sequence cached every finished sequence. A finish leaf pairs
   seq.tokens with a snapshot of the LIVE recurrent state; after a step that
   failed mid-forward the tokens are un-advanced while the layers before the
   failing one have consumed it, so the pair is inconsistent and the retry of
   the same conversation restores it. The decision is read ONCE at the top:
   the blocking branch take()s engine_error to build the HTTP 500, so a check
   at the caching line never fires for blocking clients (mutation-tested: that
   variant fails an_engine_error_on_a_blocking_sink_skips_the_cache...).
   The prompt prefix stays cached from prefill; blocks are freed as before.

2. Verify rows stay below the context ceiling (mtp_gate/ceiling.rs).
   The serial force-stop leaves a live sequence at max_seq_len - 2, and no
   speculative dispatch predicate looked at the ceiling. One draft fits; two
   or more can run a row AT max_seq_len, which state sized to --max-seq-len
   (the QSA indexer) refuses mid-forward - "error" instead of "length" on the
   last step. The MTP arm now declines such a step; it decodes serially into
   the existing force-stop. No effect at the default draft depth.

3. --self-speculative is refused on models with per-sequence aux state
   (serve_phases::self_spec_supported, + the offline loop). The draft pass
   runs the attention layers, which advance the QSA indexer / PLE history;
   only seq_len and tokens are rewound, so the verify fails its position
   check on the first speculative step of every request. The flag could not
   work; now it says so at load.

Tests: 8 new (3 lifecycle, 3 ceiling, 2 self-spec) plus one existing lifecycle
test moved next to them; no GPU needed.
lifecycle_tests.rs was at 496/500 lines, so the cache tests live in
lifecycle_cache_tests.rs and the stub counts calls per test thread.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… never reaches it

The decode host arm (select_blocks) and the prefill top-k ranked blocks with
partial_cmp(..).unwrap_or(Equal).then(index) - a total order only while no
score is NaN. They now share rank_cmp: NaN ranks below every real score,
-0.0 folds into +0.0 (the device kernel compares with > and ==, which treat
them as equal; total_cmp alone would not), ties go to the lower index. Same
result for every score the kernels can produce.

NaN scores are NOT reachable today: both scoring kernels take the relu as
fmaxf(dot, 0), which returns the non-NaN operand, so a NaN query or key
contributes 0 (GB10 kernels build without fast-math). That invariant is now
pinned on the CPU reference (nan_activations_score_zero_not_nan), so a relu
rewritten in a NaN-propagating form fails a test first.

Tests (no GPU): the host selection equals a transcription of the device
kernel rule over 4000 random reachable score vectors (ties, both zeros,
+inf); signed zeros tie to the lower index; NaN inputs never panic the sort
or change the selected count.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…any scores

The device top-k staged NaN as -inf and then EXCLUDED -inf blocks from
selection, while n_sel is derived from the position alone and qsa_gather
reads all of it. With fewer than block_topk rankable blocks the launch would
leave sel[] entries unwritten, and the gather would index the block table
with stale ids from an earlier step - or another sequence, sel being
layer-owned scratch.

Not reachable today: qsa_score / qsa_score_rows take the relu as fmaxf, which
returns the non-NaN operand, so scores are never NaN (GB10 builds without
fast-math; pinned on the CPU reference in the previous commit). This removes
the trap rather than a live bug: drop the special case, rank -inf like any
other value (ties by index). The order is then total for any input and
exactly block_topk blocks are always selected. Bit-identical for every score
the scoring kernels can produce - the removed condition was always true.

Test: an #[ignore] GPU test pre-fills sel with -1, launches the kernel on
distinct / tied / signed-zero / +inf / some-NaN / all-NaN scores, and requires
every id to be written, in range, and equal to the host arm. The host
property test now also covers NaN inputs against the device rule.

The GPU test passes on a GB10. A decode-path kernel edit: land it with a gate
re-record.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@AzeezIsh
AzeezIsh merged commit 4460284 into Atlas-Inf:feat/flashnext-nvidia Sep 22, 2026
21 of 22 checks passed
AzeezIsh added a commit that referenced this pull request Sep 23, 2026
Brings the branch tip (incl. #51: MTP past the QSA inert bound, active-QSA
verify, QSA total-order/topk fixes, simhash fence fix, certified-gemv
restore) into the lane alongside the validated DFlash batched-verify stack.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants