Skip to content

qwen4_exp: land #23 (review branch) + nvidia/Qwen3.8-Flash-Next-NVFP4 pack, PLE scratch bound, aux-snapshot buffer reuse - #35

Merged
AzeezIsh merged 80 commits into
mainfrom
feat/flashnext-nvidia
Sep 24, 2026
Merged

AzeezIsh merged 80 commits into
mainfrom
feat/flashnext-nvidia

Conversation

@AzeezIsh

Copy link
Copy Markdown
Contributor

Summary

Lands the Qwen3.8-Flash-Next long-form serving line for GB10 in one branch, plus the nvidia/Qwen3.8-Flash-Next-NVFP4 (ModelOpt MIXED_PRECISION) pack:

  • PR qwen4_exp: seven fixes for long-form serving of Qwen3.8-Flash-Next on a GB10 #23's 21 commits (Andrew's assist/flashnext-longform-fixes: >8K prompts, QSA cap from --max-seq-len, finish_reason=error, fault latch, watchdog rollback with aux snapshots, MTP/QSA inert-bound latch, hc_pre scratch alignment, BF16 head default, --attn-proj-dtype, PLE event, device QSA top-k, hc_pre_finish_x4, first-index-wins argmax) as reviewed on review/pr23-fixes — merging this makes qwen4_exp: seven fixes for long-form serving of Qwen3.8-Flash-Next on a GB10 #23's head reachable from main;
  • the review/pr23-fixes additions already posted on qwen4_exp: seven fixes for long-form serving of Qwen3.8-Flash-Next on a GB10 #23 (NoAuxSnapshot decline under --speculative, engine_error on 28 abort paths, the n-gram lane fixed end-to-end and extended to llama.cpp-style chains + dynamic table + SSD persistence, sampled-request decline, per-token logprobs through verify) with the gate records that ran all ten required gates green at 77e0f96c;
  • new, this line: loader support for the nvidia pack — quantized_layers MIXED_PRECISION map parsing (9923d498), per-expert FP8-block-scale MTP experts + MIXED_PRECISION detection that excludes mtp.*/*.ple.*/*.visual.* (dbe6f7d2), MODEL.toml hf_id → nvidia with RadixArk in match_names, a BENCH.toml scaffold for the nvidia subjects (0902edb6), PLE forward scratch bounded by ATLAS_PLE_CHUNK spans (4.7 GB → 1.17 GB at 32K prefill, 9c1ca517), and aux-snapshot host buffers reused instead of reallocated per save (45f5b355).

Stacked on review/pr23-fixes; merges cleanly with main @ e56db0a6. Record: docs/porting/QWEN38_NVIDIA_PORT_LOG_2026-09-15.md (on review/pr21-fixes @ 7dec982e) §B/§D carries every run-record id below and the queue scripts that produced them.

Measured on GB10 (gx10-e3a3, nvidia pack, wt-fnext-nv)

leg fingerprint result
loader smoke dbe6f7d2 MTP shard F8_E4M3 + g128 weight_scale_inv as designed; first request 1.5 s
MTP-on probe 9c1ca517, --speculative --num-drafts 1, util 0.93 healthy in 80 s; gate arbitrated K=1
ST-995 bfcl-subset (n=995, seed 42, temp 0, thinking ON) 9c1ca517, util 0.95 / 16K, no spec 83.52 / 82.45 (run-1789433036569430053)
ST-995, corrected memory profile 9c1ca517, util 0.88 / 32K / prefill 16K, --ngram-speculative (lane never engaged) 83.52 / 82.45 (run-1789501991840065669) — profile is accuracy-neutral
agentic-webserver, 50 iterations 9c1ca517, util 0.88 / 32K 50/50 webserver_ok, 49/50 directions, 816 turns, 32 multi-chunk prompts to 25K, 0 CUDA faults; Σwall 19,351 s → perf FAIL at 23.7 s/turn (serial decode floor of this pack) (run-1789474170004681458)
bs4 concurrency probe 9c1ca517, util 0.88 C1 17.5–18.5 → C4 35–37 agg tok/s, outputs identical across lanes
KL / coherence, serial vs --ngram-speculative 9c1ca517, temp 0, penalties 0, top-10 logprobs coherent, tool call OK; lane inert (tok_step 1.000)

No committed floors yet for the nvidia subjects (BENCH.toml bootstrap protocol) — these are the records the floors get derived from.

The Flash-Next OOM, root-caused and fixed in two parts

  1. GB10 memory is unified: --gpu-memory-utilization is also the host's ceiling. At 0.93 the box sat at 0.87 GB MemAvailable; at 0.95 the OOM killer fired (024). The KV pool absorbs whatever the pledge leaves (12 GB for a bs1 workload that needs < 1 GB) — profile moved to 0.88 / 32K.
  2. The serve's RssAnon grew 2 → 9.8 GB over the 5.4 h agentic run. An 8-leg bisect (fresh serve per leg) showed growth ∝ context depth, halved by ATLAS_SSM_DECODE_RING=0, flat on prefix-cache hits ⇒ aux-state snapshots: QsaIndexer::snapshot_aux / PleLayer::snapshot_aux allocated a fresh host Vec of ingested×hd×2 bytes per indexer (12 × 4.6 MB at 18K) at every boundary token (decode ring) and every Marconi checkpoint, fragmenting glibc arenas. 45f5b355 snapshots into caller-owned, capacity-retaining buffers for both paths and applies restores under the pool lock instead of .cloned() (bytes unchanged; 6 unit tests). Verified on the same bisect legs: ring-on ≡ ring-off (7.9 vs 7.8 MB/1K tok; was 9.5 vs 4.9). The residual matches the retained-by-design 16-slot Marconi aux footprint (~1.3 GB at 27K); the end-to-end agentic rerun on the fixed binary is queued.

Known / not fixed here

Test plan

  • cargo fmt --all -- --check; ATLAS_SKIP_BUILD=1 CUDARC_CUDA_VERSION=13000 cargo clippy -p spark-model --tests clean (pinned 1.93.1); SPDX on new files
  • cargo test -p spark-model — parser/detection tests, 3 MTP layout tests, PLE chunking tests, 6 aux-reuse tests
  • GB10: loader smoke, MTP probe, 2× ST-995, 50-iteration agentic, bs4 probe, KL harness (table above)
  • GB10: agentic rerun on 45f5b355 with host-memory trace (queued)
  • --pull-request-gate on the nvidia subjects once BENCH.toml floors are derived from the records above

Generated with Devin

andrew-vogulkin and others added 30 commits September 4, 2026 03:58
…LE_MAX_TOKENS up to the floor

Two independent caps refused every prompt past 8192 tokens on a default
serve of Qwen3.8-Flash-Next. The prefill chunk is max_batch_tokens =
prefill_budget + max_batch_size = 8193 wide, but the n-gram row cache was a
fixed 65536 slots (sized for 2048 x 16 heads), so an 8193-token chunk pinned
131,088 rows and the cache bailed with "every one of 65536 slots is pinned
by the batch in flight". Derive the default from max_batch_tokens x
ngram_heads (rounded up to a power of two, floored at 65536; ~84 MB at the
default chunk) and keep ATLAS_PLE_CACHE_SLOTS as the override; the load
line now prints where the number came from.

An ATLAS_PLE_MAX_TOKENS override below the derived floor was honoured after
a warning and then refused the first wide prefill as a 500; it is now
clamped up to the floor with the same warning.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
ATLAS_QSA_MAX_TOKENS defaulted to 32768 regardless of the served context,
so a --max-seq-len 65536 serve of Qwen3.8-Flash-Next died mid-stream the
moment a sequence reached position 32768 ("QSA: pos 32768 >=
ATLAS_QSA_MAX_TOKENS"), discarding 14.5K generated tokens.

ModelConfig now carries max_seq_len the same way it carries
max_batch_tokens (serve-time, serde-skipped), serve sets it from
--max-seq-len, and QsaIndexer::new sizes its per-sequence key caches from
it. The env var remains an override that can only raise the capacity; a
lower value is clamped up with a warning, and the two bounds guards name
the flag that actually controls them. A config built outside serve keeps
the historical 32768.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…"; log cuBLASLt fallbacks

Every verify/MTP step handled an engine failure with `a.finished = true`,
so the response layer reported a normal completion: on Qwen3.8-Flash-Next a
speculative verify that hit an active QSA selection at position 2,051
ended a 1,679-token answer with a clean "stop". The client could not tell
the truncation from success.

ActiveSeq now records the cause (`engine_error`, set at every such site;
`abort_on_engine_error` for the k3 step where the stamp pushed the file
past the LoC cap). finish_sequence reports "error" — a new FinishReason
variant on the wire — and a blocking client receives the error itself, so
the request fails as a 500 instead of a completion with a strange reason.

The GDN QKVZ projection also swallowed the cuBLASLt error before falling
back to the scalar dense_gemm; that fallback is the kernel that faulted
with CUDA_ERROR_MISALIGNED_ADDRESS on continuation prefill chunks. It now
logs the cuBLASLt failure with M/N/K and the operands' low address bits and
debug-asserts their alignment, so the next fault names its operand.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
After a sticky CUDA error (CUDA_ERROR_MISALIGNED_ADDRESS in a continuation
prefill chunk on Qwen3.8-Flash-Next) the fault latch fired, /health went
503 and main.rs was ready to exit EXIT_GPU_FAULT — but the scheduler loop
never returned control to it. The process kept the port open, answered
/tokenize, 500'd every completion and held ~100 GB for hours until it was
killed by hand.

Check the global latch at the top of every scheduler iteration: mark the
in-flight sequences as engine errors (they finish with reason "error"
through the existing drain) and break, so the exit path that already
exists runs. /health needs no change: it already reports the latched
fault (api::tests::health_fault).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The content-loop watchdog's rollback restored the SSM recurrent state
from the decode ring and lowered seq_len, but nothing rewound the QSA
indexer cursor or the PLE n-gram history: on Qwen3.8-Flash-Next the very
next decode failed "QSA: decode at pos 2864 but 2932 tokens ingested — the
indexer cache lost sync" and the request died with a 500. The only aux
rewind in the tree was the speculative-verify commit hook; the watchdog
path never touched aux state.

Mirror the SSM treatment with the audited snapshot path instead of a new
arithmetic rewind: the model gains save/restore_decode_aux_snapshot
(byte-exact blobs from collect_aux_states/apply_aux_states, keyed by the
same (slot, ring_slot) as the SSM ring) and requires_aux_state.
snapshot_boundary_if_ssm saves both or drops the ring entry;
rollback_to_boundary restores both, and declines with the new
RollbackFallback::NoAuxSnapshot — a stream-safe hard stop — when the aux
companion is missing or fails to restore.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The MTP lane's gate declines a batch only when a sequence is ALREADY at or
past verify_context_limit (the QSA inert bound, 2051 on this card). A
sequence admitted just below it gets a verify that ingests num_drafts + 1
rows across the bound, and the next verify runs with selection active on
the batched multi-seq path, which refuses it — on Qwen3.8-Flash-Next with
--speculative --num-drafts 1 every long answer died at position 2051.

Latch a.disable_mtp one step early (seq_len + num_drafts + 1 >= limit),
logged once per sequence; the serial lane handles active selection. The
batched multi-seq entry also refuses before any QSA ingest when a row is
already past the bound, so a future caller cannot mutate state before the
late check fires.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e GEMM

Chunked prefill of Qwen3.8-Flash-Next faulted with
CUDA_ERROR_MISALIGNED_ADDRESS on continuation chunks — a 1,117-token last
chunk, or the default 8,193-wide chunk — while 1,074 / 1,862 / 4,092-token
chunks were fine. Under CUDA_LAUNCH_BLOCKING the faulting launch is
dense_gemm_bf16_pipelined with grid [80, 9] = [10240/128, 1117/128]: the
`up_pre = low x up_wt^T` GEMM in hc_pre_gemm.

Its scratch was packed as raw byte products: `inj_pre` is `lay * hc_mult *
2` = `lay * 8` bytes, so for an odd slab `up_wt` started 8 bytes off a
16-byte boundary and the kernel's vector loads faulted. Even slabs happened
to align, which made the fault look random (and had the earlier
odd-chunk-width theory half right).

Place the sub-buffers with one shared layout function in spark-runtime
(256-byte aligned) and size the region from the same function, so sizing
and placement cannot disagree. Unit test covers odd and even slabs
including the historical 1,117. Verified on the GB10: the 13,397-token
prompt prefills at both 4,096 and the default 8,192 chunking.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Resolves the one conflict in multi_seq/mod.rs: main's nemotron serial
early-return runs first, then the QSA pre-mutation guard from this branch.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Atlas fills request fields a client leaves unset from the selected
MODEL.toml [sampling.*] category. For penalties this happened
unconditionally, so Qwen3.8-Flash-Next's card presence_penalty = 1.5
(tuned for short chat turns) reached every plain chat/completions
request. On a 20K-token single-file build it suppresses every token
already emitted and the engine shipped dead/inert files; with presence 0
the identical engine and sampler wrote a working 51 KB game.

New [behavior] key use_sampling_preset_penalties_for_core (default true,
so no other model changes). Tool-calling requests always keep the
[sampling.tools] penalties; explicit request values always win.
Flash-Next's MODEL.toml opts out.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The checkpoint ships lm_head in BF16 and Atlas requantized it to NVFP4
at load. The 27B recipe already pins --lm-head-dtype bf16 for exact
argmax; long-form single-file generation on Flash-Next is the same
regime. --lm-head-dtype nvfp4 still forces the packed head.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Watchdog rollbacks fire from logits processing, after decode(last_token)
pushed that token, so seq.tokens holds every generated token including
the boundary token. apply_rollback re-points last_token at the boundary
token and the next step decodes it again, but rewind_buffers popped only
the dropped tokens: the boundary token was decoded twice, one position
past the SSM/aux snapshot (taken before it was fed). Pure-attention
models got a duplicate KV row; hybrid models with the QSA indexer failed
with 'QSA: decode at pos 6050 but 6049 tokens ingested' after the aux
restore landed. Pop dropped + 1.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…int precision

The NVFP4 loader arm runtime-quantizes BF16-shipped attention
projections to NVFP4 even though ModelOpt's own ignore list keeps every
self_attn projection at BF16 (the qwen4_exp checkpoint does). The BF16
Q/K/V sources are already resident for the dense fallbacks; with the
flag the layer gets no NVFP4 Q/K/V (dense GEMV/GEMM arms run) and keeps
a BF16 O copy via set_o_dense_bf16. Serve-time config field, validated
enum, default unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…iscarded context

Two watchdog sites roll back at different points of the step. The
content-loop / inter-tool-prose handler runs BEFORE the step pushes its
sampled token, so seq.tokens holds every generated token; the fuzzy
detector runs AFTER the push, so the newest output token is not decoded
yet. A fixed pop count is wrong at one of them: popping dropped decoded
the boundary token twice at the before-push site ('QSA: decode at pos
N+1 but N tokens ingested'), popping dropped+1 discarded a real token at
the after-push site ('pos N but N+1 ingested', seen once the first fix
landed). rewind_buffers now takes the unfed tail (0 / 1) and pops every
fed token from the boundary onwards, which lands the re-fed boundary
token exactly where the SSM/aux snapshot expects it.

The before-push site also kept appending the token it had just sampled
from the discarded context: a phantom, never-decoded token that reached
the client and put every later rollback one position off.
handle_content_token now returns true on a rollback, refunds that
token's budget and content count, and the step drops it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The single PLE layer released the previous gather's row pins behind a full
stream synchronize once per token and uploaded the resolved slot list from
a pageable Vec. Record an event behind the gather kernel and wait on that;
stage the slot list through a pinned buffer rewritten only after that wait.
GpuBackend gains thin event wrappers with a stream-sync fallback.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…oE through the grouped-GEMM arm

A/B lever from the llama.cpp gap study: the scalar FP32-FMA decode arm vs the
tensor-core grouped-GEMM arm (forward_prefill M=1) for all 48 layers. Default
unchanged (scalar). Measured on the GB10: grouped 5.3 tok/s vs scalar 15.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… host-parity check

decode_select copied the block scores device-to-host (a stream sync per
attention layer per token), sorted on the host and uploaded the selection.
qsa_select_topk does the selection on the device with torch.topk's
tie-break (lower index wins), in ascending block order, straight into
sel_dev; n_sel never depended on the scores. Default stays on the host arm;
ATLAS_QSA_TOPK_VERIFY=1 runs both and fails on the first mismatch.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ccumulation order

nsys on the GB10 (C=1, 3.9K ctx) had this kernel at 121 us x 97 launches =
11.7 ms of a 69 ms token, ~54 GB/s on 6.5 MB of up_w: latency-bound, one
dependent load+FMA per rank step per stream, and nvcc does not pipeline the
runtime-bound loop. Unroll r by 8 with the 32 loads hoisted ahead of the 32
accumulations. Every accumulator still sums r = 0,1,2,... in that order into
one FP32 register (--fmad=false), so the output is bit-for-bit unchanged;
this is scheduling, not the reassociation the kernel's note rejected.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…cal accumulation order

Stage 3 of the hyper-connection decode collapse is capped at H = 2560
threads per token (thread-per-d walking four dependent rank-320 chains):
nsys measured 121 us x 97 launches = 11.7 ms of a 69 ms token. Give each
of the four INDEPENDENT stream accumulators its own warp, lanes over 32
consecutive dims, so a token spans 80 blocks x 4 warps; the per-(d, s)
sum still runs r = 0,1,... in one FP32 register (--fmad=false) and the
four products still fold in s order in one thread, so the output is
bit-for-bit the previous kernel's. ATLAS_HC_FIN_X4=0 keeps the old path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The rank loop read every score from global memory complete times; nsys
had the kernel at ~71 us x 12 launches per token. One staged copy
(16 KB for the 4096-block cap) and NaN folded to -inf once.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
rollback.rs (511) -> rollback_rewind.rs child: rewind_buffers +
apply_rollback (pure token-buffer rewind + ActiveSeq glue), re-exported.
ple/layer.rs (501) -> seq_state.rs child: PleSeqState with pub(super)
fields, re-exported. No behaviour change.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Measured with the same params as main's records (2026-09-03-077552182d):
vision/video fidelity, decode-floor (22.1 tok/s), warm/cold TTFT, SSM
state poisoning, concurrency sweep, agentic webserver and bfcl-subset-echolp
all PASS.

bfcl-subset FAILS at 86.23 overall / 83.10 normalized (bars 83.42 / 83.32).
This is not this branch: main@077552182d served with the recipe's flags and
driven by main's own harness scores the identical 86.23 / 83.10 on this
GB10 today, and a 207-sample replay of the subsets that moved (parallel,
parallel_multiple, simple_javascript) gives byte-identical tool calls from
the two binaries. The committed 0775521 record repeats the 61f6976
measurement (2026-09-02) to the digit, including sm clocks; between that
tree and 0775521 the qwen3.8-27b kernel target grew from 182 to 198
modules (0775521 touches prefill_paged_compute.cuh, argmax_bf16.cu,
w8a16_gemv_batch4.cu, mamba2_ssm_decode.cu and the paged-sink prefills).
The record is committed as measured so the gap is visible.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…aths)

0775521 switched the greedy tie-break from "first strict maximum wins" to
"value descending, then higher vocabulary index" in argmax_bf16.cu and moved
the host verify argmax and the greedy logit processor to the same last-wins
rule. With BF16 logits at temperature 0 exact ties are common, so the rule
change moves tokens: on the bfcl-subset gate draw for unsloth/Qwen3.8-27B-
NVFP4 it flipped 9 of 207 replayed answers, cost 3 correct ones, and took
the checkpoint from 86.53/83.38 to 86.23/83.10 (bars 83.42/83.32) — main
itself fails its own committed record under the new rule. Reverting only the
kernel on top of main restored all nine samples; reverting the other
accumulation-order change in the same commit restored none.

First-index-wins is also what llama.cpp's greedy sampler and vLLM's
torch.argmax do, so it is the rule the recorded baselines and the other
engines share. This restores:
  * kernels/gb10/common/argmax_bf16.cu — the 61f6976 kernel, verbatim
  * scheduler/verify_pipeline_helper/argmax.rs — argmax_first_wins
  * scheduler/verify_pipeline_helper.rs, logit_processors/mod.rs — call the
    first-wins helper (spark_runtime::sampler::argmax_first_wins_f32)
  * atlas-kernels/tests/argmax_tiebreak_contract.rs — now locks the
    first-wins rule instead of the last-wins comparator

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Same params as main's records. With first-index-wins tie-breaking restored
(db0bc09), bfcl-subset is back at 86.53 overall / 83.38 normalized on the
full 995-sample draw — the 2026-09-02 numbers to the digit (bars 83.42 /
83.32). bfcl-subset-echolp 87.95 / 87.99, decode-floor and the TTFT, SSM,
fidelity and agentic gates unchanged.

Two gates needed a second run at this head and the records are from those:
decode-floor's first attempt died before serving ("No memory left for KV
cache") because the previous gate's server had not yet released ~3 GB — a
settle-time artefact, not a measurement; concurrency-sweep's first attempt
was INCONCLUSIVE because one of the eight natural prompts at conc 8
paraphrase-looped and the SimHash watchdog cut it at 243/320 tokens (below
the 80% vacuity floor). On the re-run the same prompt was cut at 309 and
every floor was met (C1 19.0 · C4 50.8 · C8 58.8 · C16 85.6 tok/s). The
loop is greedy-path behaviour of this checkpoint under first-wins; the
last-wins run on 2026-09-07 did not hit it. Worth knowing when reading the
sweep's vacuity rule.

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

rollback_to_boundary gates the snapshot-aware boundary search on
has_ssm_layers() && ring.is_enabled(). Under --speculative the decode
ring is skipped at model init, so a qwen4_exp sequence takes the
plain any-boundary search, finds a boundary, and rewinds seq.tokens
and the KV cache while the twelve QSA indexers keep their post-loop
ingested counts. The next decode dies on the desync check
("decode at pos N but M tokens ingested") and the request 500s —
observed live on GB10 (spec + watchdog, 16.7K prompt): watchdog fired
at content_tokens=453, rolled back 91 tokens, decode_batch then failed
with ingested ahead of pos.

requires_aux_state() && ssm_slot.is_none() now declines with
NoAuxSnapshot before any buffer mutation, so the caller takes the
hard-stop fallback — the same outcome the watchdog produced before
rollback existed, instead of a corrupted sequence and a 500.
…paths

The engine_error plumbing covered the single-sequence verify steps,
mtp_step and the scheduler-loop fault latch, but the same
"abort -> finished -> finish_reason=stop" laundering still applied on:
the batched DFlash verify step (all nine error exits), the batched K=4
verify, the K=4 verdict commit_accepted_prefix arms, the batched MTP
bootstrap decode/sample errors, the self-spec and ngram-spec steps
(spec_step.rs), and the per-token EP broadcast in verify_k2 — the cmd
broadcast two lines above it already latched engine_error. Every one of
those now sets a.engine_error before finishing, so the sequence reports
"error" rather than "stop".
…SS on gb10

Full suite re-measured on the review-fix head (rollback aux-decline +
engine_error coverage). gx10-e3a3, NVIDIA GB10 119.6 GB, driver
580.126.09, CUDA 13.0. All recipes ran with --serve-override
gpu_memory_utilization=0.92 — recorded in provenance — because the
pinned 0.85 budgets were sized for a 121.7 GB box and OOM here.

bfcl-subset 86.53/83.38 and echolp 88.05/88.08 match the db0bc09
records exactly — the review fixes did not perturb the scored draw.
…E aux rewind)

step_ngram_verify used start_rollback_and_checkpoint_async on reject —
that restores SSM h/conv but never rewinds per-row aux state. On QSA
models every rejected ngram draft left the indexer watermark one ahead
of seq_len; the next verify died with "decode at pos N but N+1 tokens
ingested". The K=2 verify canonical commit (commit_accepted_prefix)
rewinds QSA + PLE aux by k - num_accepted; adopt it on both ngram arms
so the path shares the aux contract instead of open-coding the SSM half.

Live-verified on qwen3.8-flash-next NVFP4 (GB10): requests that died at
7 tokens now run to completion with clean accept/reject cycling.
…QSA/off-by-one

The --ngram-speculative path was effectively broken end-to-end. Three
correctness fixes plus the llama.cpp feature set:

Correctness
- spec_step: propose/observe on tokens + [last_token]. last_token is
  sampled-but-not-pushed, so the old context ended one token short and
  every draft predicted the already-emitted token (100% reject).
- scheduler/mod: honor verify_ctx_limit on the ngram lane — a seq
  crossing the QSA inert bound used to die on VerifyUnsupportedWithActiveQsa.
- spec_step verify: commit via commit_accepted_prefix so the QSA indexer
  and PLE carry rewind by the rejected tail (was SSM-only).

Features
- Multi-token draft chains: prompt-lookup continuation extended through a
  learned n-gram table; width clamps to model.verify_max_drafts (K=2 on
  flash-next mHC) and dispatches to the K=2/3/4 graphed verifies.
- Dynamic n-gram table (hash -> next-token counts) learned on every
  observed token, mirroring llama.cpp ngram_mod.
- SSD persistence: table auto-saves to <hf-cache>/atlas-ngram/<model>.bin
  on shutdown + every 8k observations, warm-loads at boot.

Measured on qwen3.8-flash-next NVFP4 (GB10): 25.3 tok/s vs 18.8 serial
(+34%), ~93% draft acceptance, zero draft-weight memory (the MTP module
cannot even fit this box at 0.85 util).
# Conflicts:
#	crates/atlas-kernels/tests/argmax_tiebreak_contract.rs
#	crates/spark-server/src/main_modules/serve_load.rs
#	kernels/gb10/common/argmax_bf16.cu
@github-actions github-actions Bot removed the needs-rebase Conflicts with main — its green checks are NOT real (GitHub skips merge-commit workflows) label Sep 18, 2026
The gfx1151 port landed on atlasinf/main added `try_kernel` probes for
Strix-only kernels inside the shared dense_ffn / qwen3_attention /
qwen3_ssm constructors — which every gb10 model instantiates too. The
upstream kernel-resolution audit (phase 7, fail-closed) then refuses the
boot with 12 unresolved lookups for (qwen3.8-27b, sm_121, nvfp4):
w4a16_gemv_dp4a::* (9), w8a16_gemm_n_m128, w4a16::w4a16_gemm_t_m128_k16
and the dense_gemv_fp8w redundant probe.

Every site is `handle != 0`-gated, so gb10 correctly falls back to the
compiled w4a16_gemv / w8a16 / gemv_fp8w arms — these are absent BY DESIGN
on sm_121 (porting them is a perf question for gfx1151, not a correctness
one). Declare them [expected_absent] with stated reasons, mirroring the
symmetric declarations strix-hip/*/MODEL.toml already carries for the
gb10-only kernels it probes. This repairs a latent main-side regression
the merge exposed: post-#33, no gb10 dense model could boot.
…sh-next

Same latent main regression as qwen3.8-27b: the gfx1151 port's
handle!=0-gated try_kernel probes (dense_gemv_fp8w, w4a16_gemv_dp4a
batch4_d4 family, w8a16_gemm_n_m128) resolve to 0 on sm_121 where the
compiled gb10 arms serve the shapes. --check-kernels reported 5
unresolved lookups for (qwen3.8-flash-next, sm_121, nvfp4); all five
are declared here with their fallback paths.
Measured on reiner (GB10, driver 580.126.09) against
nvidia/Qwen3.8-27B-NVFP4 via the pinned pull-request-gate recipes.

concurrency-sweep: PASS — C1 23.2/16.2, C4 43.9/33.5, C8 57.6/50.5,
C16 86.0/72.0 agg tok/s; every populated floor met, zero errors.

decode-floor: FAIL/INCONCLUSIVE — all three pinned runs stopped at 660
tokens, under the 700-token vacuity floor. Root-caused by a serial-vs-
spec A/B on the same binary: serial decode reaches the 1500 budget
(finish_reason=length); under MTP the trajectory diverges benignly then
lands in a paraphrased-repeat attractor the SimHash loop watchdog stops
at ~660-757. Non-lossless K4-verify trajectories are an acknowledged
engine property (spec is serialized inside <think> for the same
reason); the record documents the honest state rather than a loader or
pack defect.
@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Status update — flash-next verified serving end-to-end on GB10

Fixed in this round (all pushed):

  • a8742a036 — spark-model: MIXED_PRECISION global variant vote now lets NVFP4 win over FP8 (fixes Expected FP8E4M3 ... got UInt8 on the nvidia 27B pack's mixed FP8-attn/NVFP4-MLP map; regression test added)
  • d4c6749a8 — merge atlasinf/main, preserving the branch's argmax lowest-index tie-break and QSA max_seq_len carry alongside main's DFlash pool wiring
  • 2d871d385 / 9264bf4ec — declare Strix-HIP-only try_kernel probes [expected_absent] on gb10/qwen3.8-27b (12) and gb10/qwen3.8-flash-next (5). Latent main regression from DFlash2 speculative decoding: land #21 (review branch) + Strix Halo gfx1151 port, HDIM=128 Option-B fix #33: the gfx1151 port's optional probes resolve to handle 0 on sm_121 and the merged kernel audit fail-closed on them. All sites are handle != 0-gated with compiled gb10 fallbacks.

Flash-Next serve smoke (nvidia/Qwen3.8-Flash-Next-NVFP4, recipe-rendered flags, 9264bf4ec): boot → "Server live" with kernel audit clean; thinking scaffold (reasoning_effort: low) and thinking-off both answer; MTP spec engaged (24/49 draft tokens accepted, ~27.7 tok/s on the probe); qwen3_coder emits get_weather({"city":"Tokyo"}). Zero errors in serve log.

Benchmark gate state — honest, not worked around:

  • concurrency-sweep: PASS record committed (C1 23.2 · C4 43.9 · C8 57.6 · C16 86.0, all floors met)
  • decode-floor: INCONCLUSIVE record committed — pinned runs stop at 660 < 700 vacuity floor. Serial-vs-spec A/B on the same binary: serial reaches the 1500 budget; the MTP trajectory diverges benignly then hits a paraphrased-repeat attractor the SimHash watchdog stops. Non-lossless K4-verify is an acknowledged engine property (same reason spec is serialized inside <think>).
  • The remaining required gates need Qwen/Qwen3.6-35B-A3B-FP8 / unsloth/Qwen3.6-27B-NVFP4, absent on the box — gate stays red by design, not by silence.

Memory note: the merged engine consumes ~107 GB for this model at max_seq_len 32768 before KV (MTP draft module 1.77 GB + verify pools + per-token arena are new since the recipe's ~90 GB calibration). At the recipe's shipped max_seq_len 8192 / gpu_memory_utilization 0.95 it fits comfortably; the smoke ran 16384/0.95.

Recipe: sparkrun-recipes model: fields now name the nvidia pack (PR Atlas-Inf/sparkrun-recipes#10) — the RadixArk mirror it named was a refs-only stub on the validation box.

Not included: FP8-source reclaim for mixed-precision loads (work in flight on a local tree).

AzeezIsh and others added 2 commits September 19, 2026 15:20
…rote

PR #9 (Strix Halo Windows leg, f2ec96d) replaced kernels/gb10/common/
dense_gemv_bf16.cu with the gfx1151 "v2" kernel while its own header says
"the gb10 symlink is replaced by this copy so the certified NVIDIA target
is untouched". The gb10 blob changed (805c07e -> 779f60c); the symlink
that was replaced was strix-hip's, pointing AT gb10.

v2 is not bit-identical to v1 on gb10, contrary to its comment: v1 splits
each output's K range over 64 threads (BLOCK_SIZE 256 / N_PER_BLOCK 4,
stride 64, two-warp shuffle + smem add); v2 over 32 (stride 32, one warp).
Each thread therefore accumulates a different subset of products in FP32,
and the final BF16 rounding differs at near-ties. Flash-Next dispatches
this kernel on its BF16 lm_head and on all 36 GDN projections
(qwen3_ssm/init.rs, impl_a1.rs, ops/qwen4exp.rs), and several kernels
document a "bit-identical to dense_gemv_bf16 at M=1" contract
(qwen3_attention/decode/attention_forward.rs:762, multi_seq/qkv.rs:159).

Observed: nvidia/Qwen3.8-Flash-Next-NVFP4 ST-995 (golden draw, n=995,
temp 0, serial) on the same serve profile and box: 83.52/82.45 at
45f5b35+tiebreak (run-1789591710115920743) vs 83.42/81.40 at 1cec998,
whose only engine delta is the merge of main incl. #9
(run-1789856554862860168); twelve subsets moved by 1-2 samples each in
both directions, the signature of near-tie flips, not of a category
regression. Restoring v1 on gb10 only; strix-hip keeps its v2 copy.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
AzeezIsh and others added 3 commits September 20, 2026 04:36
The sentence-level Jaccard guard split fenced code on `.` `:` and blank
lines and tripped on the first near-duplicate "sentence". Docstrings make
that a false positive by construction: `_left_child`/`_right_child` twins
share almost every bigram. Streaming the decode-floor MinHeap prompt
against nvidia/Qwen3.8-27B-NVFP4 stopped at 660 tokens on three heads
with `paraphrased sentence repeat`, while the identical unstreamed request
ran to the 1500-token budget with no repetition; the 717-718 "natural
stop" the gate's vacuity pin was calibrated on was the same cut.

The streaming consumer now tracks ``` fences: inside a block no sentence
boundary or 1 KB force-flush is evaluated, the block is hashed once at
its closing fence (the design the F22 note describes), and the pending
buffer is bounded at 16 KB. Prose outside fences is unchanged, and the
token-level period watchdog stays active everywhere. Tests cover
docstring twins inside an open fence, a prose loop after the fence, two
identical blocks, a marker split across chunks, and the cap.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ypothesis leg)

Restores the NVIDIA bodies of `w4a16_gemv_qg` and `w4a16_gemv_qkvz` to their
45f5b35 text (blob 1d80c55): the per-element `acc += a*lut[nibble]*scale`
k8 loop. The Strix merges (f2ec96d / c467b90 via e4417a8) rewrote them
onto the shared `w4a16_gemv_partial` accumulation (per-group partial, then
`fmaf(scale, part, acc)`), which is a different FP32 summation order. The
gfx1151 side keeps the partial helper under `__HIP_PLATFORM_AMD__` (the
strix-hip file is a symlink to this one). `w4a16_gemv`, `_sw`, `_logits` and
the batch tiers were already on the helper at 45f5b35 and are untouched.

These two kernels are the fused GDN q/g and q/k/v/z serial-decode projections
of Flash-Next, so this is a candidate for the ST-995 drift 82.45 -> 81.40
(45f5b35 -> 1cec998); with dense_gemv_bf16 restored in #39 it is the last
gb10 M=1 kernel on that path whose NVIDIA arithmetic changed in the segment.
Unmeasured until the ST-995 leg at this head reports; reverted if the score
does not move.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@AzeezIsh

Copy link
Copy Markdown
Contributor Author

Consolidation + state, 2026-09-21. This branch now carries everything Flash-Next needs, so the side PRs are closed into it:

  • 0513921e5 gb10 dense_gemv_bf16 v1 restore (was kernels(gb10): restore the certified v1 dense_gemv_bf16 that #9 overwrote #39)
  • 7190719fe merge of the fence-aware semantic-loop guard (was spark-server: hash fenced code blocks once in the semantic-loop guard #47) — the 27B decode-floor gate's 660-token INCONCLUSIVE was this guard splitting a ```python block on docstring boundaries; with it, job 183 streamed 960/1500/1500 tokens, 0 fires, PASS
  • cfb03a953 gb10 w4a16_gemv_qg / w4a16_gemv_qkvz M=1 bodies restored to their 45f5b35 text — hypothesis leg, not a conclusion. The ST-995 slide 82.45 → 81.40 → 80.61 is deterministic (job 181 reproduced 175 exactly under a different prefill chunking), so it is code, and these two fused GDN serial-decode projections are the last gb10 M=1 kernels on the path whose NVIDIA arithmetic changed in 45f5b355..1cec9989. Job 191 measures it; reverted if the score does not move.

Gate status at the integration head 3b4f7c2e0 (= main + this branch + #46): concurrency-sweep PASS (C1 22.9 · C4 45.3 · C8 62.6 · C16 85.4); kernel audits clean for both targets; Flash-Next 4-surface smoke PASS on the recipe profile. Two gate legs (185/186) ran against a stale local recipe cache (~/.atlas/atlas-recipes/index.json from Sep 1 — --pull-request-gate reads fetch::cached, never refreshes): 27B bfcl served thinking-off, Flash-Next gates OOMed on the old prefill 32768 recipe. Cache refreshed to recipes tree 4e9ec407 (#8/#11/#12 merged); reruns 187/188 in flight — 187 has booted and is scoring.

Still open before this can go green: the Flash-Next bfcl floor (191/192), and decode-floor's 700-token vacuity pin sitting inside the model's natural 660–960-token answer to the MinHeap prompt (gate-design fix pending a decision on prompt vs pin).

@andrew-vogulkin

andrew-vogulkin commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

W1 (MTP past the QSA inert bound) — design reviewed, implemented, host-tested. Not run on a GPU yet, nothing pushed yet. Work is on top of cfb03a953; say how you want it delivered (branch on this repo, PRs against feat/flashnext-nvidia, or patches) and I'll push.

What blocks speculation past 2,051 tokens (read from source, not measured). The batched multi-row attention path (qwen3_attention/trait_impl/multi_seq/mod.rs, shared by MTP verify, n-gram verify and concurrent decode) runs dense batched attention and only afterwards loops over rows calling decode_select for ingest — and errors if a row returns Some. There is simply no selection hook. It is not the host top-k and not rollback: rewind_verify is already exact and is reached exactly once per verify on every MTP lane (K=2/3/4, batched multi-seq) and the n-gram lane, through commit_accepted_prefix_dispatch.

The change (opt-in, ATLAS_QSA_VERIFY_ACTIVE=1; off = behaviour unchanged).

  • New multi_seq/qsa_rows.rs: per 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 the next decode_select overwrites. The batched dense pass it replaces is skipped. No new kernels.
  • guard.rs becomes a pre-mutation allow-list (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.
  • ⚠️ Shared-trait change, flagging per AGENTS.md: a new defaulted verify_context_limit_multi_seq() on the Model and layer traits. Multi-sequence verify batches and the n-gram lane keep today's limit; the first landing is the MTP lane at C=1 only. Every risk found in review needs ≥2 concurrent sequences: KV exhaustion inside a batched verify finishes the whole batch instead of preempting, and batched MTP bootstrap reads stale hidden rows once decode_a2 routes per-sequence (which would fake an "episodic 0 % acceptance" signal).
  • Per-row selection is also what vLLM (its PR 53896) and llama.cpp (its PR 27742) do for this model; a CPU-reference test shows why one shared selection per window is wrong (a draft token can close a block mid-window).

Evidence so far — host only. 13 new GPU-free tests (CPU-oracle: verify row == serial row for every block phase and widths 2–4; rejection leaves exactly the accepted prefix intact, which is the boundary rewind_verify clamps to; selection geometry; rewind_verify, which had no tests; the allow-list; scheduler limit selection). cargo fmt --check, clippy --tests -D warnings, SPDX, the 500-line cap; spark-model --lib 822 passed / 0 failed, scheduler + mtp_gate 265 passed. Design went through two independent adversarial review passes before implementation (both "go with changes"; the changes are in).

Not verified, and only the GB10 can answer: selection-set agreement between verify rows and serial decode (near-tie block flips from batch-K numerics), acceptance past the bound, whether R× indexer cost still leaves a K=1 win, and the host top-k arm's 12 × R stream drains per step past ~16.4K tokens. Proposed legs, after the ST-995 floor is back: ~6K essay control with --speculative --num-drafts 1 + ATLAS_QSA_TOPK_VERIFY=1 (expect no mtp declined, accepted > 0, per-step acceptance logged) → ~20K to exercise the host-arm fallback → the 179 agentic profile → ST-995 with mtp>0. Exit criterion should be the floor, not greedy-text identity.

Found along the way, separate branch, crates only (8 new tests):

  • finish_sequence writes a prefix-cache finish leaf even after an engine error — tokens un-advanced, live recurrent state advanced — so the retry of the same conversation restores it. Note the obvious one-liner is wrong: the blocking branch take()s engine_error before the caching line; the fix reads it once at the top (mutation-tested).
  • No speculative dispatch predicate looks 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"). Latent at the default depth, live with K>1.
  • --self-speculative cannot work on this model (the draft pass ingests indexer rows that are never rewound, so the first verify fails pos == ingested); now refused at load.
  • One thing that turned out NOT to be a bug: the device top-k never selects NaN blocks while n_sel is position-only, which looked like a stale-id read — but qsa_score takes the relu as fmaxf, so scores are never NaN (no fast-math on gb10; now pinned by a reference test). A kernel tidy-up exists but I would hold it for a planned gate re-record.

AI-authored (Claude Code), in a session directed by @andrew-vogulkin.

Edited: test counts corrected (13 and 8, not 14 and 9). Superseded by the GPU results below and by #51.

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]>
@andrew-vogulkin

Copy link
Copy Markdown
Contributor

W1 update — now run on a GB10, and opened as #51 against this branch.

feat/flashnext-nvidia is not writable from my account, so the work is a PR into it: #51 (6 commits on cfb03a953, mergeable, opt-in behind ATLAS_QSA_VERIFY_ACTIVE=1). The tree in #51 is byte-identical to the one measured below.

Setup: RadixArk NVFP4 pack, --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 6.3K prompt 21.6K prompt (host top-k arm)
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 23.1 tok/s (+26 %) · 159 accepted 22.9 tok/s (+27 %) · 161 accepted
  • Switch on: 0 errors, 0 mtp declined, 0 indexer desyncs, 0 device-vs-host top-k mismatches; TTFT unchanged.
  • Per-row indexer cost is small: speculative decode is 24.6 tok/s below the bound and 23.1 just past it (~6 %); acceptance is the same on both sides (0.71–0.72).
  • Greedy text differs from serial, but no more than it already does: on this binary speculative vs serial diverges after 29 of 274 words below the bound, and after 151 / 28 words past it. So the exit criterion should be the floor, not text identity.
  • The #[ignore] GPU test for the top-k kernel passes.

Still open, and it needs the queue box: the nvidia pack, ST-995 / agentic with mtp>0, K>1, C>1, anything against the accuracy floor. Suggested first leg once the floor is back: the 179 agentic profile with the switch on.

AI-authored (Claude Code), in a session directed by @andrew-vogulkin.

qwen4_exp: MTP past the QSA inert bound (opt-in per-row verify) + three speculative-path safety fixes
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