Skip to content

qwen4_exp: merge #754's serving port, keep what this branch does better, fix six silent defects - #16

Merged
AzeezIsh merged 252 commits into
mainfrom
feat/qwen4exp-serve
Sep 2, 2026
Merged

AzeezIsh merged 252 commits into
mainfrom
feat/qwen4exp-serve

Conversation

@AzeezIsh

@AzeezIsh AzeezIsh commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Serves Qwen3.8-Flash-Next (model_type: qwen4_exp, RadixArk NVFP4) on a single GB10. Now targets main and supersedes #13, which it contains exactly (212 commits; #13's head 2bcda1dc is an ancestor and has no commits this branch lacks).

Try it

./scripts/dev/qwen4exp_quickstart.sh /path/to/RadixArk-Qwen3.8-Flash-Next-NVFP4

Builds, serves, waits for health, runs coherence + tool-calling + perf, prints the numbers. Container equivalent in docker/gb10/qwen3.8-flash-next/nvfp4/Dockerfile; the recipe is crates/spark-server/tests/fixtures/recipes/qwen3.8-flash-next/. A workflow_dispatch job publishes ghcr.io/<owner>/qwen3.8-flash (arm64 only — GB10 is aarch64).

Weights are never in the image. The checkpoint is ~126 GB and is bind-mounted, and that mount must be local NVMe: the 51.2 GB PLE n-gram table is demand-paged off it by row, so mount latency is a direct per-token cost. A network mount serves correct tokens slowly, which reads as a model problem rather than a storage one.

Verified on a GB10 (sm_121, CUDA 13.0)

leg result
coherence 7/7 — Paris; 408; 15:40 for "14:05 + 95 min"; exact JSON; axolotl recalled; needle-in-context 94 at ~2000 tokens
BFCL-style tools 6/6 — native tool_calls, enum honoured, numerics typed, parallel calls, irrelevance declines
decode, 1 stream 14.5 tok/s, TTFT ~780 ms
decode, 4 streams 28.4 tok/s aggregate, 512 tokens, zero errors
trunk vs CPU reference 36/36 GDN layers agree; L01_in cosine 6.2e-5 → 0.999527
lib tests 900 (atlas-core 167, spark-storage 87, spark-model 646)

Eight defects, six of which needed hardware

# defect how it failed
1 PLE shards span 10 files, loader assumed one hard refusal at model build
2 PLE table is F8_E4M3; stride assumed BF16 read off the end of a shard
3 FP8 dequant scale never applied would have been silent
4 serve script contradicted its own recipe on KV dtype silent long-context loss
5 row-cache pin released before the gather kernel ran intermittent wrong rows
6 FP8 table gathered by the BF16 kernel 1e30 in the highway — the incoherence
7 no tool_call_parser, so tools never reached the prompt BFCL 1/6; model reported having no tools
8 batched decode rejected any batch off a padding boundary HTTP 500 at every concurrency > 1

1–3 and 6 are one story: the reference work was validated against the Inferact conversion; this serves RadixArk. On Inferact the PLE table is BF16 in a single file, so batched_embed is the correct kernel there — none of this could have surfaced on that branch.

#6 was found by bisect, not by reading. The tap diff on a 5-token prompt showed layer 0 correct to cosine 0.99999 and layer 1's input arriving at a norm ratio of 1.25e31; the GPU's post_moe tap then put it between layer 0's MoE (sane, max 0.1985) and the next layer's input (max 2.18e30), leaving only the PLE injection. #2's stride fix was necessary but converted an out-of-bounds crash into an in-bounds wrong answer, which is why it took the bisect.

That bisect needed an instrument that did not exist: the GPU has tapped the highway per sublayer for a while, but the reference side came from Python and the box has no torch. The reference now writes the same taps (ATLAS_QWEN4EXP_REF_DUMP) and scripts/dev/qwen4exp_tap_diff.py diffs them Rust-vs-Rust.

Numerics

scripts/dev/qwen4exp_logit_kl.py, with the two controls that make the number mean anything:

control: gpu vs gpu, 3 identical prompts — KL 0.000000000, bitwise identical
temp 1.0  KL(ref||gpu) 0.6218   top1 AGREE (5013)   rank_of_ref1 1   top20 13/20
          top-20 union renormalized:  0.3700

The GPU is bitwise deterministic, so the drift is systematic. Restricted to what top_k=20 sampling can reach it is 0.37 nats. Not softcapping (neither final_logit_softcapping nor attn_logit_softcapping is set; the GPU max of exactly 10.000 is BF16 spacing near 10). Not MoE routing either — the hypothesis I expected to confirm: flipping an expert in top-10-of-512 is discrete and would show as sporadic jumps at post_gdn → post_moe, but that term is a steady −0.0013/layer, about a third of the mHC collapse term. Reads as distributed NVFP4/BF16-vs-f32 accumulation.

Independent validation

@maplepaladin73 validated on their own GB10 without write access and independently found and fixed defects 1 and 2 with the same approach, as local patches. Their GPU multi-file byte-identical row read is adopted in 54553c7e; my version pinned only the shard→file mapping and could not have caught a plausible-but-wrong file index. Their finding that the 0.80 util default is ~1 GB short is documented.

Known not-done

  • Vision is unproven. The ViT tower loads (27 blocks under model.visual.*) and no image has been sent through it. Every leg here is text. Splitting to a separate PR.
  • A shared-parser robustness gap: the model can emit a spaced closing tag (</parameter >), which tool_parser's exact match does not recognise, so it becomes an optional argument's value. Fixing it touches shared code used by every XML-parser model, so it wants a maintainer's call rather than a unilateral change here.
  • CLA is unsigned, which is what blocks merge.

rsafier and others added 30 commits August 25, 2026 11:14
The host-side, kernel-independent heart of the n-gram embedding path
(LongCat-Flash-Lite / Qwen3.8-Flash-Next family): NgramDims (table
count/dims/row-counts from the config trio), the EOS-resetting shifted
context, per-table vocab_mods (V^d mod T), and ngram_ids — the
polynomial-rolling-hash row ids for all K*(N-1) tables over a context.

Cross-language parity: bench/ngram_ref/make_fixtures.py emits id
fixtures from the numpy reference (itself a line-faithful port of the
HF modeling file); the Rust unit test asserts BIT-EXACT ids on both a
synthetic config and real LongCat-Lite dims (12 tables x ~10.2M rows),
with a mid-sequence EOS exercising the document-boundary reset. A
second test pins the decode contract: ids for a new token computed over
only the trailing (n-1)-token window equal the full-sequence ids — the
NgramCache property the serving path will rely on.

Overflow contract documented at the top of the module: 64-bit products
mandatory, no intermediate reduction needed at LongCat scale.

Next (needs the downloading checkpoint to validate): GPU fused path
(batched_embed gathers + small GEMMs exist as ops already), table
loader with quantize-on-load, and the LongCat backbone port
(MLA-variant + zero-experts + dual-sublayer blocks).
…kpoint

The 138 GB snapshot landed; --dump now reads the needed embedder/proj
rows straight from the safetensors index and writes golden fused
embeddings for 16 fixed tokens. Committed as
ngram_golden_longcat_lite.npz (~200 KB) — the target the Atlas GPU
module must match.

Checkpoint verification against the formula model, all EXACT:
  embedders.{0..11}: [78*131072 + 2i + 1, 256] BF16
    (table 0 = 10,223,617 rows; table 11 = 10,223,639)
  post_projs.{0..11}: [3072, 256] BF16
  model.embed_tokens: [131072, 3072] BF16
  total n-gram tables ~62.8 GB BF16 — the quantize-on-load target.
Tensor names discovered for the loader:
  model.ngram_embeddings.embedders.{i}.weight
  model.ngram_embeddings.post_projs.{i}.weight

Also fixes a real bug in the dump: tensor names were sorted
LEXICOGRAPHICALLY, which puts embedders.10 before embedders.2 and
silently mismaps tables 2..9 — numeric sort by the trailing index now.
The GPU n-gram embedding module, composed entirely from existing
kernels: `batched_embed` gathers (word + the K*(N-1) tables),
`dense_gemm_bf16_pipelined` per-table projections, `bf16_scaled_add`
accumulation with the reference's 1/(1+T) scale folded into every
addend (out starts zeroed, so base and tables share one code shape).
Host-side hash ids feed device staging; a fused single-kernel version
is a later optimization — per-token cost is already negligible next to
a transformer layer.

Validation (`ngram_gpu_matches_golden`, #[ignore] GPU test, data dir
via ATLAS_NGRAM_TEST_DATA):
- make_gpu_testdata.py emits COMPACTED tables — only the rows the
  fixture tokens touch (~19 MB instead of 63 GB) — read row-wise from
  the real LongCat-Lite snapshot; the Rust test recomputes the hash ids
  itself and remaps them to the compact order, so the id math and the
  GPU op chain are exercised jointly.
- Result: worst-row relative Frobenius error 0.0050 vs the f32 golden.
- Criterion note: elementwise max-rel is the wrong instrument — the GPU
  accumulates 13 BF16-rounded adds while the golden accumulates in f32;
  sim_bf16_chain.py shows the reference's own BF16 chain hits
  elementwise 0.17 with per-row Frobenius 0.0067. Gate = 2% Frobenius
  (a single mis-mapped table would register ~27%).
…print

The 12 LongCat/Flash-Next n-gram tables are ~63 GB in shipped BF16; at
FP8 they fit alongside an NVFP4 backbone on one GB10. This adds the
storage lever end to end:

- kernels/gb10/common/embed_from_argmax.cu: batched_embed_fp8 — gather
  rows from an FP8-E4M3 table with per-row f32 scales, BF16 out. Uses
  the repo's SOFTWARE E4M3 decode (copied from dense_gemv_fp8w.cu's
  scl_fp8), matching quantize_bf16_to_fp8's encode convention.
- ops::batched_embed_fp8 launch wrapper (sampling.rs).
- ngram_embed.rs: NgramTable { Bf16, Fp8 } storage enum;
  NgramTable::quantize_bf16 (per-table GPU quantize via the existing
  quantize_bf16_to_fp8 kernel + Fp8DenseWeight); NgramEmbedding
  dispatches per table so mixed precision is possible.
- GPU parity test now runs BOTH legs against the real-checkpoint
  goldens: BF16 worst-row Frobenius rel 0.0050 (gate 2%), FP8-quantized
  0.0247 (gate 5%). A mis-mapped table or broken decode registers ~27%,
  so both gates stay discriminating.
Line-faithful port of transformers' modeling_longcat_flash.py: dual-
sublayer layers (2x MLA + 2x dense MLP + shortcut MoE added at the END
of sublayer 2), MLA with q/kv LoRA scaling and interleaved rope, softmax
router over 256 routed + 128 identity zero-experts (topk chosen WITH
e_score_correction_bias, weighted by UNBIASED scores * 6.0; classifier +
bias stored F32 in the checkpoint per _keep_in_fp32_modules).

Streams one layer's weights at a time (~10 GB peak vs 129 GB) and feeds
the already-validated fused n-gram embeddings as input, so the golden
composes with the ngram module. longcat_forward_golden.npz holds every
layer's output, layer-0 router topk/scores + shortcut, final hidden and
last-token logits for the seed-7 16-token fixture — the parity targets
for the Atlas port.
Phase A/B/C of the LongCat-Flash backbone port (#746 follow-up):

- parser: num_hidden_layers = 2x checkpoint num_layers (each checkpoint
  layer = 2 engine MLA sublayers, mirroring the HF modeling file's own
  expansion), head_dim = qk_nope+qk_rope, n_kv = n_heads, 28x
  FullAttention layer_types, scoring_func=softmax + norm_topk_prob=false;
  new ModelConfig.zero_expert_num.
- moe_topk_softmax_bias kernel (+_batched): fp32 softmax over
  routed+zero logits, top-k selected WITH e_score_correction_bias,
  weighted by UNBIASED softmax * routed_scaling_factor; the zero-expert
  FOLD happens in-kernel (selected identity experts accumulate into a
  per-token zero_accum and their slots become expert-0/weight-0 no-ops)
  so every downstream dispatch/blend kernel is untouched.
- moe_zero_expert_add kernel + MoeLayer::apply_zero_expert: the
  identity contribution out[t,:] += zero_accum[t] * x[t,:], invoked by
  the layer arm after the routed blend.
- Router width: gate GEMV/GEMM row count is router_logits_n
  (= experts + zero; equal to num_experts on every other model), and
  gate_logits buffers size to it. Routing arms added on the single-token
  decode + batched prefill paths; the five other dispatch variants carry
  a NAMED refusal when zero-experts are configured (v1 scope).
Phase D of the backbone port: LongcatWeightLoader builds the whole 27B
proxy backbone, and the two LongCat-specific MLA deltas are LOAD-TIME
WEIGHT TRANSFORMS so the shared MLA runtime is untouched.

- weight_loader/longcat/prep.rs: (1) rope convention — Atlas rope kernels
  are rotate_half (pairs i, i+rope/2) while LongCat stores the rope slice
  INTERLEAVED, so its de-interleave folds into the OUTPUT ROWS of
  q_b_proj (per head) and kv_a_proj_with_mqa at load; (2) MLA LoRA
  scaling — mla_scale_q_lora folds over q_b_proj, mla_scale_kv_lora folds
  into kv_a_layernorm.weight (RMSNorm is input-scale-invariant, so
  scaling the gain reproduces scale*norm(x)); k_rot correctly stays
  unscaled since it bypasses the norm. Unit-tested row permutation.
- weight_loader/longcat/mod.rs: two Qwen3AttentionLayer sublayers per
  checkpoint layer (attn_layer_idx = 2l+s, so KV indexing is the engine
  layer index), MLA precompute REUSED from the Mistral phase pipeline
  (per-head transpose / absorbed-QK / block-diagonals are name-
  independent — their visibility is bumped to pub(crate), no behavior
  change), per-sublayer NVFP4 dense SwiGLU FFN, and the block's shortcut
  MoE installed on sublayer 0.
- Shortcut carry: sublayer 0 computes the MoE on its post-attention
  normed input, folds zero-experts, and stashes into a per-block carry
  buffer BEFORE the dense FFN reuses moe_output; sublayer 1 adds it after
  its own FFN residual — matching the reference, where the shortcut is
  produced in sublayer 1 and consumed at the end of sublayer 2. Both ends
  bound-check the carry capacity.
- Router weights: classifier ships F32 (_keep_in_fp32_modules) → BF16 for
  the gate GEMV, e_score_correction_bias stays F32. No shared expert (the
  identity experts play that role) — zero-filled dummy.
- kernels/gb10/longcat-flash-lite/MODEL.toml target (bf16 KV like the
  other MLA targets) + factory registration.

643 spark-model + 111 atlas-core tests green.
Validating the backbone needs ONE real checkpoint layer, not the 129 GB
model: the committed golden records every layer's output, so a 1-layer
slice exercises every new path (MLA + both weight folds, dual-sublayer
split, softmax+bias router, zero-expert fold, shortcut carry) at ~7 GB
and isolates a mismatch to one layer instead of smearing it over 14.

The trick that needs no engine change: the 16 fixture tokens are
DISTINCT, so a synthetic embed_tokens whose row tokens[i] holds the
golden fused n-gram embedding for position i makes an ORDINARY embedding
lookup reproduce the golden input exactly (the n-gram config keys are
dropped so the plain path runs). The completions API takes raw token
ids, so the exact fixture is replayable.

make_slice_ckpt.py builds the slice; slice_expected.py computes the
target logits = lm_head(norm(layer{N-1}_out)) from the golden (1 layer:
argmax 776 at 9.058, margin 1.558 over the runner-up — far above NVFP4
noise); slice_compare.py drives the live serve and checks the argmax.
…fixes

Everything between "the loader compiles" and "the model answers a request"
on the 1-layer validation slice. Each of these would also have blocked the
REAL 129 GB checkpoint, not just the slice:

- config dispatch: LongCat-Flash-Lite ships NO `model_type`, only
  `architectures: ["LongcatFlashNgramForCausalLM"]`, so it could never
  reach parse_longcat_ngram. Dispatch now falls back to an architecture->
  model_type map when model_type is absent/empty (consulted ONLY then, so
  no existing checkpoint changes behaviour). Test added on a config with
  model_type removed — the real shape.
- preflight, dual-sublayer: the layer-count check compared checkpoint
  `layers.N` indices against num_hidden_layers, which is 2x by design —
  it rejected the real 14-layer checkpoint as "has 14 but config says 28".
- preflight, zero-experts: the correction-bias check compared the bias
  length against num_experts; the bias is per ROUTER LOGIT, so a
  zero-expert model legitimately ships num_experts + zero_expert_num
  (384 = 256 + 128).
- experts are PLAIN BF16 in this checkpoint (no NVFP4/FP8 metadata), so
  they load through detect_nvfp4_variant + quantized_any (runtime
  BF16->NVFP4) instead of the pre-quantized path.
- PLAIN rope, explicitly: the shared MLA loader always builds a YaRN
  inv_freq table and defaults to factor=128 when a config declares no
  scaling — silently YaRN-scaling LongCat's plain rope. Pinning
  yarn_factor=1.0 makes interpolation and extrapolation identical (the
  table reduces to 1/theta^(2j/dim)) and short-circuits yarn_rope_mscale.
- kernel target: `kernel_source = "mistral-small-4"` (SSOT rather than
  vendoring a second MLA .cu tree — valid because LongCat's interleaved
  rope is folded into the weights at load, so the rotate_half arm is the
  one that must run), plus the 46 [expected_absent] declarations the
  startup audit requires, each with its real reason.

The slice serves and answers requests. Numerical parity is NOT yet
reached — see the next commit's harness for exactly where it diverges.
The slice serves, but its logits do not match the golden. These three
scripts localise WHERE, so the next session debugs one stage instead of a
whole backbone.

slice_stage_ref.py replays layer 0 in numpy and emits the four stage
vectors of each sublayer for the fixture's LAST token — the row Atlas's
ATLAS_OP_DUMP hooks record — and asserts the replay still reproduces the
committed golden layer0_out before writing anything.

slice_stage_cmp.py drives the live serve and compares stage by stage.
slice_l1_probe.py isolates further: at sequence length 1 the attention
softmax is over ONE key, so the output reduces to `v0 @ o_proj` —
INDEPENDENT of rope and of the q-side LoRA scale. Match at L=1 would
acquit the rope/q path; mismatch indicts the kv/v/o path.

TRAP worth knowing (it cost a full misdiagnosis): `dump_bf16` writes RAW
BYTES, and this model runs an FP32 residual stream, so each record is
1536 f32 — NOT 3072 bf16. Read as bf16 it looks like alternating zeros
and plausible values, which reads as "the engine half-wrote the row".
The scripts read f32.

Findings at the time of writing:
  sub0_input_norm_in        cos 1.0000  — embedding lookup EXACT
  sub0_input_norm_out       cos 1.0000  — input RMSNorm EXACT
  sub0_post_attn_norm_out   cos 0.8396  — FIRST DIVERGENCE (MLA attention)
and at L=1, post_attn_norm_out cos 0.1439 — so the divergence survives
with rope and q-scaling removed from the picture, pointing at the kv/v/o
path or at how Atlas's MLA prefill consumes the absorbed/block-diagonal
precompute. Inverting the dumped norm (RMSNorm is invertible up to one
positive scalar) and scoring candidate conventions rejected all of:
per-head vs split [all-nope|all-v] v layout, kv-scale present/absent,
and a transposed o_proj — so it is not a simple tensor-convention swap.
The n-gram tables are the model's largest tensors (31.4 B params on
LongCat-Flash-Lite, ~51 B announced for Flash-Next) and its LEAST
bandwidth-hungry: a token touches exactly one row per table — 12 rows,
~3 KB — regardless of sequence length. Pure capacity, negligible
bandwidth, which makes them the best demotion candidate in the model.
Demoting them converts tens of GB of dead capacity into KV.

Sizing, measured from the real checkpoint (69.07 B params, 138 GB BF16):
tables 31.41 B (NVFP4 17.7 GB), everything else 37.66 B (NVFP4 21.2 GB).
The proxy fits all-resident at NVFP4. Flash-Next does NOT, if its
announced "+51 B" is additive: 70.3 GB backbone + 28.7 GB tables = 99 GB
against a 97 GB pledge, before any KV. Hence this.

Design, and why it needs no CUDA kernel change:
- The cache is a flat PINNED arena. On GB10 pinned host memory is
  GPU-addressable at the SAME virtual address (ExpertArena asserts it),
  so the arena IS a [slots, dim] device-side table.
- n-gram row ids are a pure function of TOKEN IDS and are already
  computed host-side, so a lookup resolves row_id -> slot on the host and
  hands the gather kernel the SLOT INDEX in place of the row id.
  batched_embed / batched_embed_fp8 then run verbatim. No new kernel, and
  no cuMemcpyHtoD anywhere on the fault path — a miss reads NVMe straight
  into the pinned slot.
- Reads come STRAIGHT OUT OF THE SAFETENSORS SHARD (open_at with the
  tensor's base offset): a table is already a contiguous row-major blob
  there, so serving needs no repack or re-save of the checkpoint. That
  offset is only 8-byte aligned, so a row can straddle a 4 KiB O_DIRECT
  block — the fetch reads the covering one-or-two-block span and copies
  across the seam (unit-tested over every phase/stride combination).
- Eviction is CLOCK (second-chance): O(1), no per-hit bookkeeping, and a
  good LRU approximation for these power-law accesses. Rows resolved for
  the batch IN FLIGHT are pinned, so a prefill can never evict a row its
  own gather is about to read; exhausting the pins is a NAMED refusal
  naming the fix, not a silent corruption. The serving constraint that
  falls out: slots >= max tokens per forward, per table.

Validated: `cached_table_matches_resident_table` (GPU) gathers the same
real-checkpoint rows through the cache and through a fully-resident table
and asserts BYTE-IDENTICAL output under genuine pressure — 5 slots for 16
rows, 27 evictions, re-faulting mid-run. 645 spark-model tests green.

Sizing note from the measured access pattern (12 M real tokens through
the real hash): a 100 K-row/table cache (~0.3 GB for 12 tables) hits
70-78%, and 10x the cache buys only 2-6 points because the miss floor is
compulsory, not capacity — so build small caches, not big ones.
Without this, the first real LongCat / Flash-Next load pushes every
`*.ngram_embeddings.embedders.{i}.weight` through the generic upload
path: 63 GB (LongCat-Lite) to ~102 GB (Flash-Next) of BF16, before any
quantization can run. On a 121 GB unified box that fails — and the
failure mode is not a clean OOM: `load_fns.rs` falls back to
`alloc_managed`, which on GB10 means Linux swap, which the backend's own
comment calls out as "GPU OOM = system OOM = kernel freeze".

The tables are now SKIPPED at load and recorded with where they live:

- `is_ngram_table` — the shared predicate, matching only the huge
  `embedders.{i}.weight` blobs. The small `post_projs` are ordinary
  tensors and still load normally.
- `WeightStore::defer` / `deferred` / `deferred_sorted` — a registry of
  (path, ABSOLUTE offset, shape, dtype) for skipped tensors, which is
  everything a consumer needs to read them IN PLACE: streaming per-table
  quantize-on-load, or `NgramRowCache::open_at` straight off NVMe. No
  repack and no re-save of the checkpoint either way.
- Both loaders participate: the fast O_DIRECT loader already carries
  `TensorMeta::abs_offset`, and the mmap loader derives the same offset
  from the pointer delta into its mapping (exact, no header re-parse).

`deferred_sorted` sorts NUMERICALLY on the trailing index —
`embedders.2` must precede `embedders.10`. A lexicographic sort silently
mis-maps every table past the ninth, which cost a real debugging session
the first time it happened (the golden-dump script had the same bug), so
it is pinned by a unit test alongside the predicate test.
The MLA attention divergence the stage bisection localised is NOT in the
loader math. Atlas's MLA kernels bake their dimensions in as COMPILE-TIME
constants, and this target was borrowing another model's tree:

- `mla_prefill_attn.cu` is `#define MLA_HDIM <kv_lora + rope>`.
  LongCat is 512 + 64 = 576. Mistral-Small-4's tree is 320 (256 + 64), so
  `kernel_source = "mistral-small-4"` silently truncated the latent by 44%.
  The weights were right and the KERNEL read the wrong geometry — which is
  exactly why every tensor-layout hypothesis (per-head vs split v layout,
  kv-scale on/off, transposed o_proj) was rejected numerically.
  DeepSeek-V4-Flash uses 576 as well, so its MLA kernels are copied here.

- Borrowing a whole foreign tree also drags in that target's shadows of the
  GENERIC kernels plus its module-name table. Switching wholesale to
  DeepSeek's tree made the RMSNorm output ~8x too large — a stage that was
  previously EXACT. So only the MLA kernels (and the w4a16 / moe files the
  MLA path needs) are vendored; everything else comes from common/.

OPEN ITEM, stated plainly: this target is still not numerically correct.
LongCat's qk head dim is 192 (nope 128 + rope 64). `-DHDIM=192` DOES NOT
BUILD — common's paged-decode kernels `#error` because 192 does not
vectorize (they need 4 or 8 BF16 per lane; 192/32 = 6). Unset, common
defaults to 256, which is also wrong for the unabsorbed lane. The fix is
one of: instantiate those kernels at 192, pad q/k to 256, or keep the model
on the ABSORBED lane — which never materialises 192-dim heads (it works in
the 576-wide latent) and is how DeepSeek-V4 sidesteps the same problem with
its 448-dim nope. That is the next step, and `slice_stage_cmp.py` measures
it in one command.

Also carried: the `moe_silu_mul` shadow-drop declaration the vendored
swiglu_limit copy needs (the launch site handle-checks and falls back to the
unfused pair; LongCat's experts are runtime-quantized NVFP4 anyway).
Groundwork for the LongCat / Qwen3.8-Flash-Next family, where the embedding
tables outweigh the backbone and the interesting engineering is capacity rather
than compute. Row ids are a polynomial rolling hash over TOKEN IDS ONLY, with
resets at document boundaries — which is what makes the lookups deterministic,
prefetchable, and safe under speculative decoding, and why a decode step needs
no more than the last N-1 tokens of history.

Placed in atlas-core rather than spark-model on purpose: the arithmetic envelope
has to be checked when a config is parsed, long before a GPU layer exists, and
the hash should not be written twice to make that possible.

Validated, not assumed. A config declaring the trio is refused when
  - a table would hold more rows than the u32 the gather kernels index with
    (a truncated id reads the WRONG row rather than failing),
  - hidden_size does not divide evenly by the table count,
  - the rolling-hash accumulator would wrap u64,
  - or only part of the trio is declared, leaving the rest to be invented.
The first and third matter because the stated target has far larger tables than
the checkpoint this was developed against, and both would surface as subtly
wrong logits rather than as a crash.

bench/ngram_embed/ carries a dependency-free reference and the fixtures it
generates. No numpy on purpose: a reference that cannot be re-run on the machine
reviewing it is not much of a reference.

Tests: ids bit-exact against the reference at real LongCat-Flash-Lite dimensions
and on synthetic (N, K) shapes; prefill/decode/chunked-prefill equivalence;
an all-EOS stream contributing no shifted terms; and the rejection paths.
Oracles verified by mutation — pairing each shift with the wrong power, using
even table offsets, and disabling the boundary reset are each caught.

Co-Authored-By: Claude Opus 5 <[email protected]>
Every existing shape uses a power-of-two vocab, where V^d mod T shares
structure across tables that a prime V does not -- so a wrong power or a wrong
table modulus has a better chance of coinciding with the right answer. Found by
cross-checking this implementation against an independent one, whose fixtures
covered this shape and whose ids agree exactly with these across all 228
positions.

Co-Authored-By: Claude Opus 5 <[email protected]>
Two more root causes found by the stage bisection, both structural rather
than arithmetic, and both landmines for ANY future model port.

1. common/rms_norm.cu applies `(1.0f + w)` — the GEMMA convention — while
   Mistral-Small-4's shadow applies plain `w`, which is what every
   HF/DeepSeek-lineage model (LongCat included) needs. Dropping the borrowed
   Mistral tree therefore silently switched norm conventions: `input_norm_out`
   went from EXACT to 8x too large, and the ratio gave it away — ~128 ≈ 1/rms
   with only +-1.5% spread, i.e. tracking `(1+w)` with w~0.05, NOT `w` which
   varies 2x across the tensor. This target now vendors the plain-weight
   rms_norm.cu. Anyone shadowing common/ for a non-Gemma model must do the
   same, or get a norm that looks plausible and is wrong.

2. HEAD-WIDTH PADDING. Atlas's MLA prefill assembles K at stride
   `qk_nope + qk_rope` and V at stride `v_head_dim`, then runs ONE
   FlashAttention whose head width is a compile-time constant. Every MLA
   model shipped so far has those equal (Mistral 64+64 = 128 = v_head_dim;
   DeepSeek-V4 448+64 = 512 = v_head_dim). LongCat is the FIRST where they
   differ — 192 vs 128 — and 192 cannot be compiled at all (common's kernels
   #error: 4 or 8 BF16 per lane, 192/32 = 6).

   Both are now padded to the stock 256 purely in the WEIGHTS, no kernel
   change: q_b_proj per head becomes [nope | zeros | rope] with the rope
   block moved to the tail so it lands where the assemble kernel writes K's
   rope; kv_b_proj becomes [nope | zeros | v | zeros]; o_proj widens with
   ZERO columns in each head's pad lanes. Those o_proj zeros are what make it
   exact — whatever the attention leaves in a padded V lane is multiplied by
   zero — and the zeroed Q lanes mean the padded K lanes cannot move any
   score either. The softmax scale is pinned to 1/sqrt(192), the TRUE qk
   width, via set_attn_scale_override.

Measured effect on the L=1 probe (rope- and q-scale-independent, so it
isolates the kv/v/o path): post_attn_norm_out cos 0.14 -> 0.55 and the
magnitude went 4.535 -> 4.116 against a 4.054 reference. STILL NOT CORRECT —
the remaining error is in the same stage — but two confirmed causes are gone
and the harness measures the next one in a single command. 643 spark-model +
112 atlas-core tests green.
The head-width padding landed in the WEIGHTS (q_b/kv_b/o_proj rewritten to a
256-wide head) but nothing told the layer, so the whole MLA chain kept taking
its stride from `head_dim_override.unwrap_or(config.head_dim)` — and the
LongCat parser sets head_dim to 192, the TRUE qk width. Q, K, V and the
o_proj input were every one of them sliced 64 lanes short of where the
weights actually put each head.

The op-dump file SIZE is what exposed it: 6144 floats where 32 heads x 256
should give 8192, and 6144 = 32 x 192 exactly. A stride error of that shape
is nasty precisely because it doesn't look like one — every tensor is
populated and finite, the cosine just sits at 0.55 instead of 1.0 or 0.

Two fixes:

  * the loader now calls `set_dimension_overrides(padded_hd, n_heads,
    n_heads)`, so `hd` is 256 everywhere downstream. `kv_dim = nkv * hd`
    tracks it for free, which is what keeps K and V contiguous.

  * `cache_skip_mla` now asks `effective_attn_scale(hd)` instead of
    hardcoding `1/sqrt(hd)`. The loader pins 1/sqrt(192) via
    `set_attn_scale_override` and the hardcoded form silently used
    1/sqrt(256). Invisible at L=1 (softmax over one key is 1.0 whatever the
    scale) and wrong for every longer sequence — so the L=1 probe could
    never have caught it.

Measured on the 1-layer slice against the numpy reference:

    L=1  post_attn_norm_out    cos 0.5439 -> 0.9990
    L=16 sub0_post_attn_norm_out   cos 0.8117 -> 0.9995
    L=1  per-head V         0/32 -> 32/32 at cos 1.0000

and the padded V lanes now hold exactly zero, which is the property the
zero-column o_proj scheme depends on for exactness.

Also fixes two defects in the MEASUREMENT that had been making the stage
table read far worse than reality:

  * the comparator paired the engine's "moe_out" (the DENSE FFN delta)
    against the reference's `sub0_moe_out` (the SHORTCUT MoE). Different
    tensors. That mispairing was reporting cos 0.1976 and 0.5235 and reading
    as a broken MoE; with each stage paired against the stage of the same
    meaning both come out at 0.9990 and 0.9880. The MoE was never wrong.
    The engine now dumps `shortcut_moe_out` separately so the two can never
    be conflated again, and the reference emits matching
    `sub{s}_dense_ffn` / `sub0_shortcut_moe` stages.

  * every vector was truncated to 1536 of its 3072 elements, a leftover from
    the earlier "records are raw bytes" misdiagnosis. `dump_bf16` widens to
    f32, so a record is `n_elements` f32 — the whole row. Comparisons now
    read full rows.

Layer 0 now matches the HF reference end-to-end at every stage (>=0.988),
with relerr accumulating 0.03 -> 0.15 down the stack, consistent with the
runtime BF16->NVFP4 weight quantization this uncalibrated slice falls back
to. 643 spark-model tests green; the regenerated stage reference still
matches the committed golden layer0_out.
…atches

LongCat-Flash-Lite now serves end-to-end and matches the committed golden at
every stage of all 28 engine sublayers. Two independent gaps closed.

1. THE OOM PRE-FLIGHT COUNTED TENSORS IT NEVER UPLOADS. The n-gram tables are
   62.8 of the checkpoint's 138 GB and the loaders DEFER them, but the
   pre-flight estimated peak from total on-disk bytes and refused the model:
   "peak 167.30 GB + 4.00 GB reserve exceeds 112.02 GB free". Excluding the
   deferred tables gives 91.25 GB against 111.37 GB free, which fits with room
   to spare. Fixed in all three pre-flight sites (fast loader + the two mmap
   paths) so the two loaders agree.

2. THE FUSED EMBEDDING WAS BUILT AND NEVER CALLED. `ngram_embed.rs` was
   validated in isolation months ago, and the tables were deferred correctly,
   but nothing in the model build or forward path invoked it — so every prompt
   entered the stack on a plain `embed_tokens` gather, missing 12 of its 13
   contributions. That does not crash. It produces fluent, confident,
   degenerate text ("the capital of the nation of the hot hot hot..."), which
   is exactly why it survived this long.

   Wiring: a `load_ngram_embedding` trait hook (default None, so no other
   architecture changes), a `longcat/ngram.rs` that turns the deferred
   (shard, offset, shape) records into `NgramTable::Cached` row caches, and one
   `embed_tokens_fused` that every embedding site routes through.

   The tables cost 403 MB as row caches — 65536 slots x 512 B x 12 — against
   62.8 GB BF16-resident or 31.4 GB FP8. A row is 512 bytes and a token touches
   exactly 12 of them, so these are simultaneously the model's biggest tensors
   and its least bandwidth-hungry. That memory goes to KV instead.
   ATLAS_NGRAM_CACHE_SLOTS tunes it.

   NINE embedding sites, not the eight I first found. The one I missed —
   `prefill_b/embed_chunk.rs` — is THE chunked-prefill embed, i.e. the path
   every prompt actually takes when chunked_prefill is on. Decode was correct
   while prefill was not, so the model looked wired and behaved unwired. What
   settled it was instrumentation, not reading: `set_ngram_embedding:
   installed` proved the model had it, `embed_tokens_fused: ngram=true
   ctx_len=4 seq_len=1` proved only DECODE was calling it, and the layer-0 dump
   was cos 1.0000 against the raw embed_tokens row — the plain gather, not even
   divided by 13. Two different causes wear that same symptom; only the log
   separates them.

   `embed()` now REFUSES a bare token id when an n-gram model is loaded rather
   than returning a row missing most of its signal, and every site keeps its
   original path byte-identical when there is no n-gram embedding.

Validated on the real 129 GB checkpoint against bench/ngram_ref/
longcat_forward_golden.npz. `full_forward_cmp.py` exploits the dual-sublayer
mapping — checkpoint layer K's output is engine sublayer 2K+2's input:

    input        (the FUSED embedding)  cos 0.4557 -> 1.0000
    layer0_out .. layer12_out                 all >= 0.9952
    worst stage: layer2_out at cos 0.9952

and the served answer is coherent and self-terminating:

    "The capital of France is:
     A. Lyon    B. Marseille    C. Paris    D. Bordeaux
     C. Paris"

Note for anyone reading the 1-layer slice results: the slice CANNOT test this.
`make_slice_ckpt.py` bakes the golden fused embedding into a synthetic
`embed_tokens` and strips the n-gram config keys so a plain gather reproduces
the golden input. That isolates the backbone cleanly — and it means the slice
stayed green through this entire bug.

647 spark-model tests green.
Model load was dominated by MLA weight precompute, not by the runtime
BF16->NVFP4 quantization everyone (me included) assumed. The first profile
settled it: across 7808 calls the ENTIRE quantize path is 1.96 s
(per_call=0.251 ms) while layers took a rock-steady 10.55 s each. Quantization
was ~1.3% of load. Even the ranking inside it was wrong — allocation
(alloc_out 1073 ms + free 1095 ms) costs ~3x the stream syncs (629 ms).

Phase timers then located the real 94%:

  MLA phase C (W_QK_absorbed)   4.45 s per SUBLAYER
  MLA phase B (per-head views)  ~0.9 s per SUBLAYER
  everything else (768 expert quantizes included)  ~0.6 s

Phase C was a single-threaded scalar CPU GEMM — n_kv*kv_lora*q_lora*nope =
32*512*1536*192 = 4.83e9 FP32 MACs per sublayer — with both BF16 operands
re-decoded from a bounds-checked byte slice INSIDE the innermost loop and the
`wq_b` operand walked at a 3072-byte stride. Now: widen both operands to FP32
once up front, make `l` innermost so the row walk is contiguous and
vectorizable, and split disjoint output-row spans across threads.
ATLAS_MLA_ABSORB_THREADS overrides the count (1 = sequential).

  absorb_qk @ LongCat shape (4.83e9 MACs, 20 threads):
    reference (scalar, bf16-decode-in-loop): 4.4477 s
    new (row-parallel, l-inner): 51.76 ms   (+25.81 ms widen)
    speedup 85.9x gemm-only, 57.3x including the widen
    bit-mismatched elements: 0 of 25.2M

Phase B issued 10,240 row-at-a-time `copy_d2d` per sublayer — and
`copy_d2d_impl` ends in a full `cuStreamSynchronize`, so that is ~10k stream
stalls to move 14 MB. Within a head both source and destination rows are
contiguous, so each head is one linear run: 64 `copy_d2d_async` + one sync.

BIT-EXACTNESS IS ASSERTED, NOT ASSUMED. Accumulation order is preserved
exactly — each output accumulator still visits the same products in the same
ascending order from 0.0, per-`l` accumulators are independent so vectorizing
across `l` cannot reassociate a sum, and Rust does no FP contraction by
default. New tests: `absorb_rows_is_bit_exact_vs_reference` keeps the
pre-change triple loop verbatim as an oracle and asserts `to_bits()` equality
over 4 shapes x 5 thread counts (including 1, a prime, and a count that does
not divide the rows); `absorb_qk_matches_reference` does the same through the
function the loader calls; `per_head_runs_cover_the_same_bytes` asserts the
per-head runs cover the identical (src, dst, len) ranges the per-row loop did,
across LongCat, Mistral-ish, and deliberately ragged shapes.

Measured on the real 129 GB LongCat load: 10.55 s/layer -> ~1.7 s/layer, so
layer build goes ~148 s -> ~24 s. Phase C is now 278.7 ms and phase B 5.4 ms
per sublayer. These phases are shared with Mistral-Small-4 and
DeepSeek-V4-Flash, so both get the same win.

The phase timers are kept as permanent tracing::info!, so the next "where does
load time go" is answered from the log instead of by guessing. `quantize_to_nvfp4`
and `quantized_any` keep theirs too — they are what refuted the original premise.

Left alone: phase_block_diag (187 ms/sublayer of host scatters over ~470 MB),
instrumented but not optimized.

647 spark-model tests green (643 + 4 new).
Mirrors the Qwen DFlash launcher. Defaults to port 8888 because that is what
bench/agentic/* expects (ATLAS_URL defaults to
http://localhost:8888/v1/chat/completions), so the agentic harnesses and the
TUI's own benchmark suite point at it with no extra flags.

Pins the two things that are easy to get wrong and silent when you do: NCCL is
outside the loader path on this box, and ATLAS_NGRAM_CACHE_SLOTS sizes the
NVMe row cache that serves the 62.8 GB of n-gram tables out of 403 MB of
pinned arena.

Everything is env-overridable (PORT, MAX_SEQ_LEN, MAX_NUM_SEQS, GPU_UTIL,
LONGCAT_PATH, MODEL_NAME, BIND) and extra args pass through. Does not pipe its
own output — the TUI disables itself when stdout is not a terminal.
Four things, found while chasing "C=1 is fine, C>1 is not".

1. BATCHED DECODE 500'd on n-gram models. `decode_a2`'s batched decode and
   `impl_b1` still called the bare `embed(token, ..)`, which refuses a token
   without its preceding context on an n-gram model. Both now use `embed_ctx`
   with THAT sequence's own history — each batch slot is a different sequence,
   so the n-gram context must never come from the batch. The guard worked as
   intended: a hard 500 instead of quietly serving embeddings missing 12/13 of
   their signal under load, which is the failure mode that hides for weeks.

2. ATLAS_NGRAM_DISABLE=1 — a bisection lever that serves the plain
   `embed_tokens` gather. Output is WRONG but deterministic, which is what
   lets you ask "is this concurrency bug mine, or older than the n-gram path?"
   It is how I established that batched decode diverges with the fused
   embedding OFF as well.

3. THE MODEL CARD'S SAMPLING IS NOW THE DEFAULT. The checkpoint's
   generation_config.json asks for repetition_penalty 1.06 / temperature 0.7 /
   top_p 0.95 / top_k 4, and we were serving Atlas's generic defaults. All
   four [sampling.*] presets now carry it, plus
   `use_sampling_presets_for_core = true` — WITHOUT that flag the presets
   apply only to non-core paths and a plain /v1/completions still gets the
   generic values, so they look wired and are not. (Same trap that left every
   qwen target on generic sampling.)

   top_k = 4 is unusually tight and deliberate; this is a 256-expert MoE with
   zero-computation experts and it degenerates given a wide tail.

   This also matters for TESTING: at temperature 0 two near-tied logits flip
   the argmax on any batched-vs-single kernel difference, so temp-0
   exact-match exaggerates "divergence". Judge concurrency on whether answers
   are CORRECT at the model's real settings, not on string equality.

4. TUI tok/s WAS A BURST BECAUSE THE COUNTER WAS. `GENERATION_TOKENS_TOTAL` is
   incremented once per request from the final usage block; the dashboard
   differentiates it at 1 Hz, so it reads 0 tok/s for the whole generation and
   then one spike. The server was streaming correctly the entire time — 139
   SSE chunks over 5.8 s, median gap 41.8 ms, only 5% in the last 5% of wall
   time. New `DECODED_TOKENS_TOTAL` advances per token in `handle_token`, and
   the TUI's gen_tps prefers it, falling back to the old counter for blocking
   requests that never stream. It counts tokens DECODED (a token the tool-call
   sanitizer suppresses still cost a decode step), so it can run slightly
   ahead of the completion-token total; the two are not interchangeable.

Also folds in the last of the load-time work: the BF16 pack in phase C was
`flat_map(|v| v.to_le_bytes().to_vec())`, heap-allocating a two-byte Vec per
element — 25.2M mallocs per sublayer. One preallocated buffer instead:
202.28ms -> 19.23ms (10.5x), bytes equal. `bf16_truncate_matches_old_flat_map`
covers signed zeros, denormals, infinities, NaN, exact-halfway patterns (where
a ROUNDING implementation would diverge from this TRUNCATING one) and 4096
random bit patterns.

Load time end to end: 10.55 s/layer -> 1.27 s/layer, 148 s -> 17.9 s (8.3x).
Phase D is now the largest remaining item (~185 ms/sublayer) and is untouched.

STILL OPEN: batched decode does not match single-sequence decode. At the
model's own sampling, serial scores 7/8 on checkable factual questions and
C=4 scores 4/8, with template control tokens ("/think_off") leaking into
output and one answer echoing its own prompt. Not decode graphs
(ATLAS_NO_DECODE_GRAPHS=1 is unchanged at 3/8) and not batched prefill (at
max_tokens=1 the batched first token matches serial exactly). The divergence
starts at the FIRST decode step.

648 spark-model tests green.
C=1 was correct and C>1 degraded. The cause is structural, not numeric:
`multi_seq/ffn.rs` — the BATCHED decode FFN — never implemented LongCat's
shortcut MoE. `decode_inner` (single-sequence) runs the producer/consumer
pair; the batched ladder does residual-norm, dense FFN, residual-add, and
stops. So at any batch size above one, every sequence lost the block's entire
256-expert shortcut contribution, on every layer, silently.

The symptom is worth recording because it does not look like a missing
component. Attention still reads the right KV, so each stream stays perfectly
on topic — what breaks is the distribution, and the model answers in
fragments:

  serial  C=1   Red/Blue/Yellow · Brazil/Argentina/Chile ·
                Piano/Flute/Drum · Jupiter/Saturn/Uranus
  batched C=4   'Ven'  'Prap'  'Pow'  'J'  'JHRPD\nJHRPD'  'Brazil\nBrazil'

Right topic, truncated words. Nothing errors; nothing crashes.

The per-token branch now runs the producer on each row's normed input BEFORE
the dense FFN reuses `moe_output`, stashes it at that row's slot in the carry
(`carry.offset(i * h * bf16)`), and the consumer adds that row back at the end
of the paired sublayer — the batched mirror of the single-token path.

Every OTHER arm of that ladder (forward_k2/k3/km, grouped, pairwise, dense
forward_prefill) still has no shortcut, so a shortcut-MoE model reaching one
would compute a structurally incomplete block and return Ok. Added an
`ensure!` at the top of `ms_phase_ffn` that refuses instead. In practice
`force_seq_ffn = mla.is_some()` routes LongCat to the per-token branch, but
that coupling is incidental — assert it rather than depend on it.

Measured at the model's own sampling (repetition_penalty 1.06 / temperature
0.7 / top_p 0.95 / top_k 4), checkable factual questions:

  before   serial 7/8   batched(C=4) 4/8
  after    serial 7/8   batched(C=4) 7/8

The one remaining miss is the same in both arms — the model doing 17x23
longhand and running out at max_tokens=250 — so it is not a concurrency
defect. Four-stream probe with unique nonces: complete correct lists in every
stream, zero nonces crossing between them.

How the search went, since two of the intermediate conclusions were wrong and
the record is worth having. Batched PREFILL was ruled out (at max_tokens=1 the
batched first token matches serial exactly). Decode graphs were ruled out
(ATLAS_NO_DECODE_GRAPHS=1 unchanged). ATLAS_NGRAM_DISABLE=1 showed batched
decode diverging with the fused embedding off too, which correctly pointed
away from the n-gram wiring. But I also concluded "no cross-request
contamination" from N IDENTICAL concurrent prompts returning identical text —
that test cannot detect contamination between identical sequences, because
bleeding the same data proves nothing. The nonce probe is what actually
settles that question, and it had to be run with DIFFERENT prompts.

648 spark-model tests green.
Three probes written while chasing "C=1 is fine, C>1 is not", kept because
each answers a question the existing harnesses do not, and because two of them
caught bugs that produced no error.

conc_quality_probe.py — scores CORRECTNESS serial vs batched at the model's
own sampling. Exact-match at temperature 0 is the wrong instrument: two
near-tied logits flip the argmax on any batched-vs-single kernel difference,
so string equality reports "divergence" that is not a defect. Send no sampler
params and score whether the answer is right.

conc_bleed_probe.py — cross-sequence contamination, with DIFFERENT prompts
each carrying a unique nonce. The obvious version of this test (N identical
concurrent prompts, assert identical output) CANNOT detect contamination: if
every sequence carries the same data, bleeding between them proves nothing. I
drew the wrong conclusion from exactly that test before writing this one.

prefix_cache_probe.py — agentic-shaped: long shared system prompt, short
differing user turn, cold vs warm vs concurrent. Checks correctness FIRST and
TTFT second, because a cache that returns the wrong continuation is worse than
no cache. Looks for the prefix being regurgitated into the answer and for
empty replies, which is how a bad restore actually presents.

All three take PROBE_MODEL and a port, so they point at any model.
Three gates on #746, all mine.

KERNEL SHADOW STRUCTURE (13 violations). Building the LongCat kernel tree I
COPIED the MLA .cu files out of deepseek-v4-flash (and rms_norm.cu out of the
Mistral lineage, which minimax also carries). `scripts/check_kernel_shadows.py`
RULE2 requires identical shadows to be symlinks to one canonical file, so
build.rs's common/shadow merge cannot silently diverge two copies of the same
kernel. All 13 are now relative symlinks.

Verified rather than assumed, because this is the kind of change that can
quietly alter what a target compiles:

  - the converter only touched files BYTE-IDENTICAL to their canonical
    counterpart, checked before and after the swap
  - every LongCat .cu resolves to the same sha256 as the copy git has at HEAD
    (0 changed)
  - deepseek-v4-flash's own .cu are untouched (0 changed) — LongCat points AT
    that tree, it does not modify it
  - `find_cu_files` filters on extension only, with no `is_file()` test, so
    symlinks are collected and read through; a forced full kernel rebuild
    (ATLAS_TARGET_MODEL='*') is green and the model still initialises
    **177 PTX modules**, the same count as before
  - end to end: LongCat serves byte-identical output to the pre-conversion
    run ("C. Paris")

Note the coupling this creates by design: LongCat's rms_norm.cu is now a
symlink into minimax-m2-229b. That file is load-bearing — it applies plain `w`
where common/rms_norm.cu applies Gemma's `(1.0f + w)`, and picking up the
wrong one made LongCat's norms 8x too large. Editing it for either model now
changes both. That is what the gate asks for; it is worth knowing.

CLIPPY (10 errors, workspace, --all-targets):
  - two redundant `*mut u8 -> *mut u8` casts in the n-gram row cache
  - a duplicated `#[allow(too_many_arguments)]` in moe_gate.rs — my doc
    comment for the LongCat router landed between the PREVIOUS fn's attribute
    and its own, leaving two
  - two manual slice copies in the n-gram EOS-reset shift -> copy_from_slice
  - three overindented doc list items in longcat/prep.rs -> a ```text block,
    which is what that head-padding diagram wanted anyway
  - four manual `% n == 0` -> `is_multiple_of`, two of them in the load-time
    phase timers and two in pre-existing examples

FMT: `cargo fmt --all`, clean under `--check`.

648 spark-model + 105 spark-storage tests green.
All five are this branch's own growth, so no allow-list entries were added —
the cap's allow-list wants a rationale AND a tracking issue, and "I just wrote
this" is neither.

  layers/ngram_embed.rs         864 -> 109  + ids/table/embed/tests
  weight_loader/longcat/mod.rs  564 -> 436  + ffn.rs
  spark-runtime/weights.rs      536 -> 420  + weights/name_utils.rs
  model/impl_a3.rs              518 -> 472  + impl_a3_embed.rs
  layers/moe/forward_prefill.rs 506 -> 491  + forward_prefill_router.rs

Split along real seams rather than by line count:

  ngram_embed/ids.rs     the hash id core — pure token-id arithmetic, no
                         device, no weights, which is exactly why it can be
                         tested bit-exactly against the Python reference
  ngram_embed/table.rs   the per-table storage enum (BF16 / FP8 / NVMe-cached)
  ngram_embed/embed.rs   the fused GPU embedding itself
  longcat/ffn.rs         the two per-sublayer FFN builders — the dense SwiGLU
                         every sublayer has, and the shortcut MoE sublayer 0
                         computes for sublayer 1 to add
  weights/name_utils.rs  tensor-NAME parsing: numeric trailing-index sort, the
                         n-gram predicate, expert-index extraction
  impl_a3_embed.rs       single-token embedding, including the guard that
                         REFUSES a bare token id on an n-gram model
  forward_prefill_router LongCat's softmax+bias router with the zero-expert
                         fold, batched-prefill side

Mechanical fallout worth knowing for the next split of this kind: moving a
`#[cfg(test)] mod tests { use super::*; }` into its own FILE silently changes
what `super` means — it becomes the tests module itself — so the imports must
be re-anchored at the real parent, and the now-redundant inner `mod tests`
wrapper trips clippy's `module_inception`. Fields the old single file shared
freely became private across the new boundary and are now `pub(super)`, which
keeps them invisible outside the module.

Verified beyond compiling: workspace clippy --all-targets is clean (that also
picked up an unrelated empty-format-string in a microtest example), fmt is
clean under --check, 648 spark-model + 276 spark-runtime tests pass, and the
full model still serves byte-identical output to the pre-split run
("C. Paris").
Mac CI could not compile spark-model: `NgramRowCache` is behind
`#[cfg(feature = "cuda")]` in spark-storage (it serves rows out of a pinned,
GPU-addressable arena), but spark-model named it unconditionally in three
places — the `NgramTable::Cached` variant, the gather arm in `embed`, and the
loader that opens the caches.

All three are now gated, plus the knock-on `E0282` where `slots`' element type
was only inferable through a method that had been configured out (named
`Vec<u32>` explicitly rather than leaving it to inference across a cfg).

The non-CUDA `build()` REFUSES rather than returning `None`. `None` is the
answer for "this architecture has no n-gram embedding" — returning it for a
checkpoint that HAS one would serve a plain `embed_tokens` gather, which is
the exact failure this branch already spent a long time chasing: fluent,
confident, degenerate text and nothing in the log. It still returns `None`
when the config genuinely has no n-gram trio, so every other model is
unaffected.

Verified both ways: `cargo check -p spark-model --no-default-features` is
clean (the Mac configuration), workspace clippy --all-targets and fmt --check
are clean under CUDA, and 648 spark-model tests pass.
Investigating the prefix-cache correctness regression on LongCat. This lands
the one durable artifact (a bisection lever) and records the eliminations, so
the next person does not re-run them.

ATLAS_PREFIX_SUBBLOCK=0 restricts the radix walk to WHOLE blocks. The
sub-block arms return a `matched_tokens` that is NOT block-aligned, and they
do it by reusing a block whose KV was computed for a LONGER key — a different
continuation past our suffix. That is a reasonable suspect for foreign
context, so it deserved a switch. It is NOT the cause here (corruption
persists with it off), but the lever is worth keeping.

WHAT THE CORRUPTION IS NOT — each measured, not argued:

  * NOT a bad KV restore. Same prompt cold vs warm, ATLAS_OP_DUMP at layer 0:
    input_norm_in / input_norm_out / mla_v / mla_attn_out / post_attn_norm_out
    / shortcut_moe_out / moe_out all cos=+1.000000, identical text. A warm
    request recomputes the same hidden state the cold one did.

  * NOT over-matching. A prompt differing from a cached one at token ~3
    correctly got kv_write_start=0 / marconi_skip=false; a prompt sharing the
    system turn matched 336 of 359. The tree refuses when it should.

  * NOT the full-prompt-hit fast path. `prefill_full_cache_hit` runs
    lm_head(final_norm(embed(last))) with NO layers, which looked like a
    smoking gun — but tracing shows it never executes here (chunked prefill
    routes through proc_range instead). Worth knowing it exists.

  * NOT repetition_penalty over a wrong history: 1.06 vs 1.0 with the cache on
    scored 15/16 and 13/16, zero prompt-echo either way.

  * NOT the n-gram wiring: at temperature 0 the cache is deterministic AND
    correct through both /v1/completions and /v1/chat/completions.

WHAT IT NEEDS, measured on matched prompts:

  cache OFF + server preset ........ 16/16 correct
  cache ON  + explicit temp 0.7 .... 15/16 correct
  cache ON  + temperature 0 ........ exact, deterministic
  cache ON  + server preset ........ ~50%, regurgitates the system prompt,
                                     returns empty, answers other questions

So it takes the cache AND the preset path together; either alone is clean.
That is odd, because for this target the preset resolves to exactly the values
the explicit arm sends (all four [sampling.*] entries carry the model card's
1.06 / 0.7 / 0.95 / 4), and min_p / top_n_sigma come from state defaults in
BOTH arms. The two arms should be identical and are not, which means the real
variable is something else that co-varies with them — prompt LENGTH and block
alignment are the untested suspects (the corrupting prompts are 554/556 tokens
and settle at kv_write_start=544, one block-ish from the divergence).

Reproducer: bench/agentic/prefix_cache_probe.py against a server booted with
--enable-prefix-caching true. Prefix caching stays OFF by default and should
not be enabled for agentic work until this is closed.
Atlas ships `--default-min-p 0.08` and `--default-top-n-sigma 1.0`, and every
request that does not name them takes those values. LongCat's card asks for
NEITHER filter, and they were being applied anyway — stacked on top of an
already-tight top_k = 4, which is a real distribution change nobody asked for.

`SamplingCategory::min_p` already existed as `Option<f32>` with a doc comment
describing exactly this precedence — and `sampling_setup` never read it. The
field was declared, parsed out of MODEL.toml, threaded through codegen, and
then dropped on the floor: `req.sampling.min_p.unwrap_or(state.default_min_p)`
skips the preset entirely. `top_n_sigma` had no preset field at all.

So:
  * `top_n_sigma: Option<f32>` added to `SamplingCategory`, parsed from
    `[sampling.*]`, emitted by codegen — same absence-vs-zero rule as min_p,
    because `None` (CLI owns it) and `Some(0.0)` (no filter) mean opposite
    things and a bare f32 cannot express both.
  * both now resolve request > MODEL.toml preset > CLI default, matching what
    temperature / top_k / top_p already do. Models with no `[sampling.*]`
    entry are untouched: `None` keeps the CLI default owning the field.
  * LongCat's four presets pin `min_p = 0.0` and `top_n_sigma = 0.0`.

Verified rather than assumed — a one-shot line now reports what the sampler
ACTUALLY runs after resolution, because these values live in three places and
only their resolution matters:

  sampling resolved (first request): temp=0.700 top_p=0.950 top_k=4
    min_p=0.0000 top_n_sigma=0.0000 rep_pen=1.060 (core_preset=true)

Note `[behavior].min_p_floor` still RAISES min_p afterwards if a target sets
one (LongCat does not); that floor exists for the FP8/NVFP4 degenerate-tail
loop and is deliberately left able to override a card.

This does NOT fix the prefix-cache corruption — the probe still scores 2/4 on
warm rounds with the cache on, so min_p/sigma were not that mechanism. It is a
correctness fix on its own terms: the model was not being served as its card
specifies.

104 spark-server tests green.
… path

The prefix cache never corrupted anything. It ROUTES differently, and the
route it selects is wrong for LongCat's padded-head geometry.

The tell was a missing file, not a wrong number. Dumping layer 0 for the same
question with the cache off and then with a foreign prefix cached, the
cache-ON run had no `mla_v` and no `mla_attn_out` at all — those two dumps
live in `cache_skip_mla.rs`. A prefix hit does not take that path. It takes
`paged_mla`. Everything the two paths share then disagrees, while the input is
identical:

    input_norm_in        cos +1.000000   (identical embedding)
    input_norm_out       cos +1.000000
    moe_out              cos +0.996548
    post_attn_norm_out   cos +0.989139
    shortcut_moe_out     cos +0.970425

Attention diverges; nothing upstream of it does.

Why this model and not the others: LongCat is the first MLA checkpoint whose
qk head (192) and v head (128) differ, so its weights are padded to a 256-wide
head with the softmax scale pinned to 1/sqrt(192). `cache_skip_mla` was fixed
for that and validated against the golden (all 14 layers >= 0.9952).
`paged_mla` was never touched — it has the right scale via
`effective_attn_scale`, but its K/V assembly has not been checked at a padded
head, and it measurably disagrees.

`paged_mla` now REFUSES a layer with `attn_scale_override` set rather than
serving subtly wrong attention. Prefix caching is off by default, so this only
reaches someone who opts in — and they get a clear error naming the cause
instead of a model that quietly answers a different question. Cache-off is
untouched: 60/60 across five prompt lengths, unchanged.

Eliminated along the way, each measured rather than argued: KV restore
(same-prompt cold vs warm is cos 1.000000 on every layer-0 tensor); radix
over-matching (a prompt differing at token ~3 correctly gets
kv_write_start=0); the sub-block match arms (ATLAS_PREFIX_SUBBLOCK=0 is
WORSE, not better); the full-prompt-hit fast path (traced, never executes);
repetition_penalty; min_p/top_n_sigma; the n-gram wiring (temp 0 is exact);
prompt length (fails at 107 tokens as readily as 554); and the prefill kernel
choice (swapping paged_mla onto the validated BR64 arm changed nothing, so the
defect is in the K/V assembly, not the flash kernel).

The real fix is to make `paged_mla` correct at a padded head, which also
restores the 6x TTFT win the cache offers (1513 ms -> 32 ms measured). Until
then the guard keeps the failure loud and the default path is unaffected.

648 spark-model tests green.
Supersedes the padded-head guess in a52b6bf. That commit had the right
LOCATION (a prefix hit routes MLA prefill from `cache_skip_mla` to
`paged_mla`) and the wrong REASON.

The reason is one line of that path's own comment:

    // Direct flash attention with expanded Q/K/V (not from paged cache).

It attends over the K/V it just assembled — i.e. ONLY the tokens this call is
processing. With no prefix hit that IS the whole prompt, which is how every
MLA model has been exercised and why this never showed up. On a hit it is not:
only the uncached tail runs (measured 12 of 556 tokens), so those tokens
attend to each other and NEVER to the 544 cached ones. The model answers from
a truncated context — fluent, confident, and about something else.

Proven by dumping both paths for the same request, rather than reasoned:

    Q          cos 1.000000   all 32 heads
    K          cos 1.000000   all 32 heads
    V          cos 1.000000   all 32 heads, pad lanes exactly 0
    attn_out   cos 0.932265   27 of 32 heads differ

Identical Q, K and V with a different attention output is only possible if the
KEY SET differs. Nothing upstream of attention diverges at all.

That also explains the two results that kept the earlier hypotheses alive. A
FULL match leaves 1 token and `prefill_dispatch` routes n<=1 to `decode`,
which DOES read the paged cache — so exact repeats came back bit-exact and
correct, and only PARTIAL hits corrupted. And it is why length made no
difference (fails at 107 tokens as readily as 554): what matters is whether
any prefix was skipped, not how much.

`paged_mla` now refuses when `seq_len_start > 0` — the honest condition, in
place of a52b6bf's `attn_scale_override` proxy, which would have refused
LongCat even where this path is correct and would NOT have caught any other
MLA model hitting the same hole. `seq_len_start` is threaded through
`MlaPrefillArgs` for it.

The real fix is to attend over the paged cache here; the
`prefill_attention_paged_*` family already exists for exactly that. It is
worth doing: the cache is otherwise sound (KV restore is bit-exact, the radix
walk does not over-match) and measured 1513 ms -> 32 ms TTFT.

Also ruled out and not worth re-testing: the sub-block match arms
(ATLAS_PREFIX_SUBBLOCK=0 is worse), the flash kernel (BR32 vs BR64 give
identical output), cache-assemble ordering (moving it before K/V assembly
changes nothing), repetition_penalty, min_p/top_n_sigma, and the n-gram
wiring.

Default path unaffected: prefix caching is off by default and the cache-off
sweep is 60/60 across five prompt lengths, unchanged. 648 tests green.
AzeezIsh and others added 23 commits August 29, 2026 02:10
`hc_pre_finish` was the largest single kernel in the decode profile — 23% of
all GPU time (11.86 s of 51.47 s), a flat ~173 us regardless of T, ~38 GB/s
against the part's ~273. It is the direct descendant of rsafier's 63bf51d,
which split the collapse across the GPU and whose closing note was "the warp
rewrite bought coalescing; it could not buy cross-SM parallelism". This one
ends the same way: the layout bought coalescing and could not buy
memory-level parallelism.

WHY IT WAS SLOW. One thread owns one output dim `d` and contracts over `rank`
sequentially. In the checkpoint's `[hc*H, rank]` layout that thread walks a
contiguous rank-320 row, so consecutive threads touch rows 640 B apart and
every lane of a warp lands on its own sector.

The constraint that shaped every attempt: the output must be BITWISE
unchanged. This is a speculative-decoding model, and decode-path FP32
reassociation on this checkpoint has been measured flipping tool-calling
behaviour on BFCL, not just last-bit noise. Two kernel-side fixes were built
and each got exactly one of the two properties:

  * warp-per-dim with a shfl reduction: +17.8%, but it reassociates. Shipped
    opt-in in 71678b3; this commit deletes it.
  * shared-memory staging of `up_w`, which keeps each thread's sequential
    accumulation and IS bit-exact: 44% SLOWER (9.06 vs 16.10 tok/s). Staging
    the whole rank in one pass (8 syncs, not 40) measured 9.06 vs 9.40, so
    the barriers were not the cost — a useful tile is ~42 KB, which caps
    occupancy near one block per SM.

THE LAYOUT GETS BOTH. `input_mix_weight_up` is now stored transposed as
`[rank, hc*H]`, so thread `d` reads `up_w[r*hc_dim + i]`: consecutive threads
read consecutive bf16, and the per-thread `for r` order is untouched.
Transposed in place at load through one 6.55 MB staging buffer — a second
resident copy would be 6.55 MB x 97 sites = 635 MB on a box that loads at
113 of 119.6 GB and hard-freezes on OOM. The prefill GEMM, whose NT
tensor-core kernel wants the checkpoint layout, stages a transposed copy back
per call (~50 us against a ~45 ms collapse, T > 64 only).

AND THE LAYOUT ALONE WAS WORTH NOTHING: 19.79 vs 20.01 tok/s. This kernel was
never bandwidth-limited. Thread-per-`d` caps it at H = 2560 threads with one
dependent 320-step FP32 chain each — nowhere near enough loads in flight to
cover DRAM latency. What paid was giving each thread the `hc` streams as
INTERLEAVED accumulators instead of one after another: four independent
load+FMA chains, every one still summing r = 0..319 in order, and the fold
over s still in s = 0,1,2,3 order. Spelled out for hc == 4 because `hc` is a
runtime argument, so a loop over an `acc[]` array cannot be unrolled and nvcc
puts the accumulators in local memory.

MEASURED, one GB10, 256-token completions, agg tok/s:

                              C=1     C=2
  parent (row-major)        20.01   22.98
  transposed only           19.79   22.98
  + interleaved streams     21.68   25.24

Block width swept 32/64/128/256 (`ATLAS_HC_FIN_BLOCK`): 21.68 / 20.57 /
21.68 / 21.65 at C=1. NARROWER IS WORSE, the opposite of the guess — every
extra block re-stages the whole rank-320 vector, and the extra SMs do not pay
for it. rsafier's original `clamp(48/T, 1, 10)` was already at the good end
of that curve; 128 is a hair better and is the new default.

EXACTNESS, verified rather than argued: the served logits are bitwise
identical to the pre-change build over a full FP32 row (992308 bytes, zero
differing bytes) and the 80-token greedy completion hashes the same
(3fff60b1034842c6). Every block-width arm reproduces it too, as pure launch
geometry must.

Both GPU probes upload `input_mix_weight_up` in the checkpoint layout, so
each now transposes on the host — keeping them tests of the kernels rather
than of the loader.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…4e5d)

Ported from rsafier's 2a9b4e5d on the upstream qwen4_exp branch. His profile
of the verify disproved the published "GDN floor" story: the dominant term was
never the GDN, it was the MoE. `forward_prefill` routes through the grouped
GEMM, which streams all 512 experts' weights regardless of row count, so a
one-row verify paid nearly what a 28-row chunk paid.

               before    after
  moe         2700 us    191 us   (14x)
  gdn_block    860 us    862 us   (unchanged)

Both hc bodies — the GDN one and the full-attention one — now dispatch the
K=1/2/3 row counts to the fused MoE kernels that already existed for exactly
this shape. `ATLAS_QWEN4EXP_HC_SMALL_M_FFN=0` restores the grouped path.

Our branch did not have this: every 1-3 row verify was still going through
`forward_prefill`. It is a kernel-shape substitution into the same
`moe_output()`, not a math change, and the 80-token greedy completion is
unchanged (3fff60b10348, matching plain decode).

Worth it here for a reason his branch could not measure: on this branch MTP
actually pays, so cutting the verify's dominant term feeds straight through.
The MTP fraction the runtime gate selects rose from 0.17-0.23 to 0.41 of
emitted tokens on the same workload — the gate picking speculation more often
because it genuinely got cheaper.

Credit: Richard Safier <[email protected]>, upstream 2a9b4e5d.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…t-exact

477a4c9 clamped this model's verify width to what it could serve at all
(K=4 has no batched MoE arm under the mHC highway). Measuring the remaining
ladder properly says the ceiling belongs one row lower.

One GB10, 256-token completions, agg tok/s, with the small-M MoE verify in:

  arm        C=1     C=2   mtp frac    p1    tok/step   greedy vs plain
  base      17.74   26.93         —      —      1.000   (reference)
  K=2       21.73   25.39      0.41   0.774     1.774   IDENTICAL
  K=3       20.16   24.92      0.41   0.782     2.420   DIFFERS

1. K=3 IS SLOWER. Its acceptance is genuinely better — 1.774 -> 2.420 tokens
   per step, 2.504 with the gate forced — but the third verify row costs more
   than the extra 0.65 tokens buys. That holds AFTER the 14x cut to the
   verify's MoE term, so it is not the MoE.

2. K=3 IS NOT OUTPUT-EXACT, which settles it regardless of speed. At
   temperature 0 speculation must be indistinguishable from serial decode.
   K=2 reproduces plain decode byte for byte on both probe prompts; K=3
   diverges on one. Bisected by lever, two prompts, sha of the completion:

     arm                          prompt 0        prompt 1
     serial reference             35eb56891bb5    17e672c5b674
     K=2 default                  match           match
     K=3 default                  b47ec495171c    match
     K=3 ATLAS_MTP_STREAM_ROW_FIX=0   match       match
     K=3 ATLAS_QWEN4EXP_HC_SMALL_M_FFN=0  b47ec495171c  match

   So it is d1753d0's stream-row selection, and NOT the small-M MoE port,
   which the fourth arm exonerates. That selection is what lifted K=2
   acceptance 0.69 -> 0.83; it is right for the row it was validated on and
   wrong for row 2. A width clamp is the right place to hold that line until
   row 2 is fixed.

`default_num_drafts = 1` in MODEL.toml already asked for K=2; this makes the
model refuse to be talked out of it by a CLI flag, the same way 477a4c9 does
for K=4.

Raising this needs the row-2 divergence fixed first, not a benchmark that
happens to look acceptable.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
15% of a BFCL draw was returning HTTP 500 for a reason that had nothing to do
with the model.

Every scratch region in the engine is sized by `max_batch_tokens` — the widest
token count a single forward can present, 8196 at the default serve config.
One was not: qwen4_exp's PLE arena used a standalone 2048, and the layer
REFUSES a wider chunk rather than overrunning it. Nothing told the scheduler
about that bound, so anything past 2048 tokens died in prefill:

  Prefill chunk layer 1 failed: PLE: 3024 tokens exceeds the 2048 this layer
  was sized for

The old comment claimed "2048 covers the chunk sizes this model runs at". It
did not.

WHAT IT COST, measured on a 334-sample BFCL subset draw, same draw both sides:

                        broken    fixed
  overall                70.96    76.05
  normalized             68.54    74.00
  live_multiple          30.16    73.02
  live (category)        51.58    80.00
  hallucination          79.65    67.59
  PLE prefill failures   51 / 334   0

`live_multiple` more than doubled. It was the worst-hit subset because it
carries the largest tool schemas — a median 3.2 KB of tool JSON, up to 22 KB —
so its prompts are the longest, and it had been scoring 30% against
`live_simple`'s 93% on the same model.

READ THE HALLUCINATION ROW CAREFULLY: it went DOWN, and that is also the bug.
`score.py` awards a point when the ground truth is `[]` and the model made no
call — and a request that 500s makes no call, so every failure was scoring as
a CORRECT decline on the irrelevance subsets. The benchmark was losing real
points on one category and collecting fake ones on another, from the same
defect. 67.59 is the honest number.

CAPPING THE PREFILL CHUNK INSTEAD WAS TRIED AND DOES NOTHING. Chunked prefill
is already on, so clamping `max_prefill_tokens` to 2048 looked free. Measured:
51 failures before, 51 after, and the same score to two decimals. The failing
widths (2064, 2288, 3024, 4240, 5200 …) are batched-forward totals — a fused
mixed step sums a padded decode batch with a prefill slice and is bounded only
by `max_batch_tokens`, never by the per-chunk cap.

The cost is real: tokens*10240*14 bytes, so 293 MB at 2048 becomes 1.18 GB at
8196, out of the KV budget. Verified the box still loads (113 of 119.6 GB,
where an OOM hard-freezes it) with zero allocation errors and decode unchanged
at 22-25 tok/s. `ATLAS_PLE_MAX_TOKENS` still overrides for anyone who would
rather have the KV depth — and now WARNS when the override is set below the
forward width, which is the configuration that produced this bug.

`max_batch_tokens` rides on ModelConfig as `#[serde(skip)]`, following the
convention the comment beside `init_nccl_comm` already sets out: serve-time
values are carried on the config, not written into the environment, because
the process is multi-threaded by then and a concurrent getenv during setenv is
UB. `skip` rather than `default` so a checkpoint's config.json can neither
supply nor clobber it.

Reviewed by Qwen3.8-Max, which caught the serde exposure and that an override
below the forward width silently reintroduces the bug.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
6d978e7 clamped the verify to K=2 on two grounds — K=3 was slower AND not
output-exact — and said raising it needed the row-2 divergence fixed first.
This finishes that investigation. Both grounds hold, and the second one is now
localized rather than merely bisected.

`ATLAS_MTP_STREAM_ROW_MAX` bounds which verify rows `select_mtp_stream_row`
applies to. Two prompts, sha of the greedy completion against plain decode:

  arm                          exact   p1      tok/step
  rows 0,1,2 (6d978e7)         NO     0.795     2.402
  row 1 only                    yes    0.603     2.069
  no selection at all           yes    0.576     2.017
  K=2                           yes    0.843     1.843

Dropping ONLY row 2 restores exactness. So this is NOT a general
draft-invariance problem in the K=3 verify — which was the leading alternative
explanation, since changing the drafts is the one thing the selection
observably does. Row 2's copy specifically is wrong. (`d1753d0b` introduced
it; it is what lifted K=2 acceptance 0.69 -> 0.83, so it is correct for the
row it was validated on.)

AND FIXING ROW 2 WOULD NOT CHANGE THE CLAMP. The exact K=3 was benched, one
GB10, 256-token completions, agg tok/s:

  arm                          C=1     C=2
  K=3 exact (row 1 only)      16.91   22.88
  K=3 as shipped (inexact)    20.16   24.92
  K=2                         21.67   25.41

K=2 beats BOTH — including a K=3 with strictly better tokens per step. The
third verify row costs more than the extra tokens return on this model, so
K=3's acceptance advantage is real and irrelevant. A future K=3 needs the row-2
defect fixed AND a verify row that pays for itself; the second is the harder
problem and is not a numerics bug.

The lever ships as a diagnostic, default unbounded, so the next person can
reproduce the table above in one run instead of re-deriving it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…r's 2a9b4e5d)"

This reverts 87e279b. The port is inert on this branch, and its commit
message claimed a benefit I could not substantiate.

rsafier's 2a9b4e5d fixes a real problem on HIS branch, where — as his message
says — "decode_verify_hc splits a verify into row-0-then-drafts", i.e. the
verify runs through the PREFILL body, whose MoE goes to the grouped GEMM and
streams all 512 experts regardless of row count. I ported it into the same two
files, `qwen3_ssm/trait_prefill_hc.rs` and
`qwen3_attention/trait_impl/prefill_inner.rs`.

This branch's verify does not go through either. `decode_verify_dispatch` runs
attention layers with a per-row `layer.decode()` and SSM layers with
`layer.decode_batched()`. Confirmed two ways:

  * `ATLAS_QWEN4EXP_PREFILL_PROF=1` over a speculative completion emits
    hc-prefill stage lines for T=21 (the prompt) and for NO other row count —
    the 2-row verify never enters that body.
  * `trait_decode_batched_hc.rs:255-275`, which is where the verify's MoE
    actually lands, ALREADY dispatches `forward_k3` / `forward_k2` / the
    batched GEMV by row count. The GDN side likewise already runs the fused
    `gdn_verify_fused_conv_kn` kernels. Both of the levers 2a9b4e5d adds were
    in place here before I touched anything.

So the port only ever affected genuine 1-3 token prefills, and I attributed a
change to it that it cannot have caused: I wrote that the gate's MTP fraction
rose 0.17-0.23 -> 0.41 because the verify got cheaper. That measurement is
real but confounded — the two arms also differed by the stage-3 kernel work in
ebb6005, and 8 completions per arm is not enough to separate them. The
k3_bisect independently showed `ATLAS_QWEN4EXP_HC_SMALL_M_FFN=0` changing
nothing about K=3, which is what an inert lever looks like.

Reverting rather than re-describing: it is a numerics-affecting substitution
(different MoE kernel, same math) on a path with no measured benefit here, and
an unmeasured numerics change should not ship. If a future change routes this
model's verify through the prefill body the way upstream does, 2a9b4e5d
becomes the right fix again and this revert is the pointer to it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…loads

Measured on BFCL, one binary, the same n=334 draw, thinking the only
difference:

                      --disable-thinking    recipe default
    overall                   76.95              81.74
    normalized                75.78              82.95
    hallucination             72.10              92.45
    irrelevance               85.71             100.00
    live_irrelevance          58.49              84.91
    parallel                  63.33              83.33

+20.4 on hallucination against a reference that scores 97.16 there. The
failure it fixes is specific: with one tool offered and a question that tool
cannot answer, the model calls it anyway — "area of a rectangle" ->
`draw_circle({radius: 50.265})`, "last year's TSX stock prices" ->
`requests_get(PublicHolidays/2024/CA)`. Deliberation is what stops that.

The recipe was already right — it ships `reasoning_effort: low`, not
`disable_thinking`. What was wrong was the BENCHMARK HARNESS: every serving
script in this investigation passed `--disable-thinking`, so the whole
accuracy series measured a configuration we do not serve, and I spent a long
time attributing the resulting gap to the model. This note exists so the next
person reads it before writing the serve line.

Both of the settings I got wrong here came from the same mistake: inheriting a
finding from MLPerf's qwen3.6 submission instead of measuring this checkpoint.
That recipe disables reasoning and documents why (86.23 -> 78.19 with it on),
and it sets `disable_tool_grammar = true` calling it "mandatory for parallel
tool calls". Re-measured on qwen4_exp, BOTH come out the other way: thinking
is worth +4.8 overall, and leaving the grammar ON is worth +0.9 overall /
+4.5 hallucination. Neither finding transfers across checkpoints, and the
recipe now says so.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… rejects

BFCL's Java and JavaScript categories are not ordinary JSON-schema tool tasks.
Their ground truths are SOURCE LITERALS, so `bfcl_eval` rewrites the function
doc before the model ever sees it -- every parameter type becomes `string` and
the description says so ("This is Java integer type parameter in string
representation.") -- and `ast_checker` enforces the same contract from the
other side, rejecting a non-string argument outright.

`provision.py` never ran that rewrite. So we told the model `pageNo: integer`,
it correctly emitted `3`, and the checker demanded `"3"`:

  simple_java_18: Incorrect type for parameter 'pageNo'.
                  Expected type String, got int. Parameter value: 3.

24 of 36 simple_java failures on the pinned n=995 draw were that error. The
prompt was not merely suboptimal, it was unwinnable, which is why these two
subsets sat so far under their sibling:

  simple_python      89.92
  simple_java        41.94
  simple_javascript  25.81

A/B on those 93 samples, one server, one binary, only the tool schema differs
(arm A reproduces the golden run's per-subset scores exactly, 41.94/25.81,
which is what makes the replay trustworthy):

  subset             old      fixed
  simple_java       41.94    58.06    +16.12
  simple_javascript 25.81    67.74    +41.93

ONLY THE MODEL-VISIBLE `tools` GET THE REWRITE. `func_description` stays raw,
and that split is load-bearing rather than stylistic: `ast_checker` looks the
expected type up in `JAVA_TYPE_CONVERSION`/`JS_TYPE_CONVERSION` UNGUARDED, and
neither table has a `string` key. Handing it a preprocessed doc raises
KeyError inside the checker, `score.py` catches it as a zero, and the entire
subset silently scores 0.0 -- measured, not theorised. Confirmed the checker
does no preprocessing of its own, so this is exactly one pass.

Delegates to `bfcl_eval`'s own `add_language_specific_hint_to_function_doc`
rather than restating the rule, so their preprocessing cannot desync from
ours. It raises instead of falling back to the raw doc: a harness that quietly
provisions the wrong prompt reports a wrong number, which is worse than not
running. The Java/JS postcondition is asserted rather than assumed.

Applied to every subset because that is what BFCL does -- on Python ones the
rewrite only appends " Note that the provided function is in Python 3 syntax."
That does change the Python prompts, so the pinned draw is being re-run whole
rather than spliced.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
9704cf5 settled K=3 on two measurements and left the reason at "the third
verify row costs more than the extra tokens return". That is true but it does
not tell the next person how far off it is, so they cannot judge whether a
row-2 fix is worth attempting. It is not, and here is the margin.

At K=3's measured step cost (119.1 ms against K=2's 85.0 ms) it needs 2.582
tokens/step to TIE K=2. Under 1 + p + p^2 that is per-draft acceptance
p = 0.853 — and K=2's own measured first-draft acceptance is p1 = 0.843. So
even a PERFECT row-2 fix, one that lifts K=3's drafting all the way to K=2's
quality, lands at 2.554 tok/step / 21.43 tok/s, still short of K=2's 21.67.
K=3 has to draft better than K=2 does merely to draw. The model is optimistic
besides: it assumes the second draft position accepts at the first's rate,
when later positions always accept less.

That reframes the row-2 defect. It is worth fixing for CORRECTNESS — a
temperature-0 speculative path must be indistinguishable from serial decode —
but it is not a throughput lever, and 9704cf5's "fixing row 2 would not
change the clamp" now has an arithmetic reason rather than only an A/B.

Also records WHY the third row costs 1.40x, since that is the part that
generalises. The verify FFN streams each ACTIVATED expert once, so cost tracks
the UNION of experts across verify rows, and this model routes top-10 of 512:
19.8 distinct experts at R=2, 29.4 at R=3, ratio 1.485. The measured 1.401
sits between the token ratio 1.303 and that 1.485, which is where modest
routing correlation puts it.

Scoped deliberately. Independent routing is a pessimistic estimate, not a
strict upper bound, so none of this proves no K=3 can ever win — upstream ran
the same experiment on a 27B, where fewer experts mean more natural overlap,
and got a wash (-0.2%) rather than a loss. The claim is about this geometry,
this kernel, C=1, and the acceptance we measure.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… hit that fires once

Measured leg on one GB10, thinking ON, 128-token completions, unique prompts
so the cold numbers are actually cold. Three findings, one of them a defect.

TPOT IS FLAT IN CONTEXT. 52.24 ms at 268 prompt tokens, 53.63 ms at 8060 —
+2.7% across a 30x range. The 3:1 GDN ratio means decode never re-reads a
context-length KV tensor, so per-token latency is a constant an operator can
plan against. TTFT is where the wall time goes: marginal prefill is
1.91 ms/token (~524 tok/s), so on a long single-turn prompt TTFT is nearly all
of it.

C=2 HAS A CLIFF between 1122 and 2347 prompt tokens. Below it C=2 TPOT is
65 ms and aggregate is ~1.60x C=1; above it TPOT doubles to ~109 ms and
aggregate is ~1.00x — the second stream buys nothing. Any concurrency sizing
taken from a short-prompt benchmark will not survive the prompts we serve.

SSM SNAPSHOTS ARE THE ENTIRE WARM WIN. Cold vs warm on a repeated prefix,
--ssm-cache-slots 16 against 0 with KV prefix caching ON in both, so the
delta is the SSM state restore alone: at 8070 tokens 24.18x with snapshots
against 1.07x without. Warm TTFT with snapshots is FLAT at ~680-700 ms at
every prompt length. Without them the KV prefix cache decays to nothing by 8K,
because recomputing the GDN recurrence IS what prefill costs here. The
recipe's existing "3.9x warm TTFT" claim reproduces (3.95x at 1124 tokens) —
it was just measured at the one length where the win is smallest.

★ AND THE HIT DOES NOT REPEAT — this is the defect. Eight identical
back-to-back requests at 4545 prompt tokens: 9754 ms cold, 587 ms on the
second (16.6x), then ~7950 ms for each of the remaining six. At 7984 tokens
there is no warm hit at all; all eight land at ~15.7 s. The server names it:

  Prefix cache hit: 4545 tokens (285 blocks) but no SSM snapshot
    -- recomputing all KV

KV matches the entire prompt, the SSM snapshot lookup misses, the GDN state is
rebuilt from scratch, TTFT reverts to cold. Snapshots ARE written every
request (slots cycling 1,3,0,2) and the single hit that landed came from an
INTERMEDIATE checkpoint at token 4528, not the leaf.

Ruled out rather than assumed: this is NOT the default-off `ATLAS_MARCONI_EXACT`
exact-leaf bypass. That branch logs whenever it fires and it logged zero times
in this run, so `skip` was already false — the lookup found nothing, it did not
find something and discard it. The leading hypothesis is that the snapshot is
released when its producing sequence completes, so it is gone before the next
request looks; recorded as a hypothesis, with the log line as the measurement.

Multi-turn agentic serving — the workload the edge-agentic gate is built on —
is exactly what should be collecting this win, and it collects it once.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…erall, 83.20 -> 81.00 normalized

b0e22d9 predicted +16.1 and +41.9 on simple_java/simple_javascript from a
93-sample A/B. The full pinned draw confirms both almost exactly (41.94 ->
58.06, 25.81 -> 67.74) and adds the part the A/B could not see, because it only
replayed those two subsets.

  category        before   after
  non_live         76.44   82.02
  live             78.82   77.65
  hallucination    94.32   83.33
  OVERALL          81.11   83.32
  NORMALIZED       83.20   81.00

Overall rose and normalized FELL. Both are correct. `overall` is a plain mean
over samples so it follows non_live, which is 62% of this draw; `normalized` is
the unweighted mean of three CATEGORY scores, so a hallucination regression
costs it a third of the damage no matter how few samples carry it.

The regression is the price of being faithful to BFCL rather than a bug in the
fix. Their preprocessing appends " Note that the provided function is in
Python 3 syntax." to every function description on non-Java/JS subsets, and
that sentence alone moves irrelevance 100.00 -> 79.17. Temperature is 0 and
nothing else about those samples changed, so this is causal, not variance: it
is 5 of 24 samples, and the sentence reads as an endorsement of the offered
tool on a category scored by DECLINING to call it. live_irrelevance (88
samples) moves only 88.64 -> 87.50, consistent with a nudge that matters most
where the tool is most plausibly relevant.

Recorded rather than tuned away. Dropping the hint on Python subsets would buy
back ~11 points of hallucination and put normalized above where it started,
and it would be exactly the kind of harness edit that reports a number the
official scorer would not — the same class of mistake as the pre-fix Java
prompts, in the other direction. The Java/JS half of that same BFCL call is
what bought the +16.1 and +41.9.

Standing against the MLPerf qwen3.6 reference (86.23 / 87.96) and this draw's
own pinned floor (83.64 / 85.32): overall 83.32 is now within 0.3 of the floor;
normalized 81.00 is 4.3 under it, and hallucination is the whole gap.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The PLE n-gram table is 320,001,536 rows x 160 dims FP8 = 51.2 GB and cannot be
resident beside the ~111 GB the model already holds in this box's 119.6 GB, so
it is served off NVMe through a pinned row cache. One prefill of 4720 tokens
issues 75,008 row lookups (tokens x 16 n-gram heads); 22,072 of them MISS.

Every miss was a blocking pread issued one at a time. The file is opened
O_DIRECT, so there is no page cache and no kernel readahead to hide them:
22,072 x ~74us = 1631 ms, which was 16% of that request's cold TTFT. The code
already said so ("the misses are SERIAL blocking preads today (QD=1 under this
mutex), so miss-count x latency IS the prefill stall") -- this makes it false.

NOT A CACHE-SIZING PROBLEM, measured before touching anything. Sweeping
ATLAS_PLE_CACHE_SLOTS 65536 -> 262144 -> 1048576 (21 MB -> 336 MB) changed the
miss count by ZERO -- 22,688 in all three arms, byte for byte. The misses are
compulsory first-touch, not evictions, so capacity cannot help and only the
queue depth can.

`resolve` splits into two passes. PASS 1 decides, serially and unchanged: the
CLOCK hand, the eviction order, and the slot each id gets are exactly what the
old single loop produced, in the same order. The residency bookkeeping that
`fetch_into` did at its END moves to decision time, which is what keeps a
repeated id inside one batch resolving as a hit to the slot already scheduled
for it rather than faulting twice. Oversubscription still REFUSES here, before
any I/O. PASS 2 does only the reads, across `ATLAS_PLE_FAULT_THREADS` workers.

Sound because the faults are independent: `victim` skips pinned slots and every
slot it hands out is pinned immediately, so the slots in one batch are distinct
and the arena writes are disjoint; `read_exact_at` is positional, so a shared
`&File` has no cursor to race on; and each worker carries its OWN bounce buffer,
which the single `self.bounce` had made a second serialisation point
independent of the I/O.

  QD    resolve    vs serial      TTFT 4720 tok    TTFT 8024 tok
   1    1631 ms      1.00x          10137 ms         16980 ms
   8     424 ms      3.85x           8906 ms         15991 ms
  16     257 ms      6.35x           8752 ms         15975 ms
  32     171 ms      9.55x           8631 ms         15791 ms

-14.9% cold TTFT at 4720 tokens, -7.0% at 8024. Monotone through 32, so that is
the default; `=1` restores the old serial path for a bisect.

OUTPUT IS BYTE-IDENTICAL. Greedy temp-0 completions hash the same in every arm
(sha 71615d90.. at 4720, 00221bef.. at 8024), and the miss counts match to the
row across arms, which is what says pass 1's decisions did not move.

On the error path the batch's claims are dropped from `map`/`slot_row` before
returning: a partially-written slot left claimed as resident would serve a wrong
n-gram row, which reads as fluent output with wrong logits -- the exact failure
this cache's checks exist to prevent.

Context for whoever asks why this is our problem at all: the checkpoint's own
SGLang reference serves --tp 2 with an fp8-RESIDENT PLE loader, so it never
faults. This cost is the price of fitting on one node.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
4727510 publishes residency at DECISION time — that is what makes a repeated
n-gram id inside one batch resolve as a hit to the slot already scheduled for
it, instead of faulting twice into two slots. The cost of that choice is that a
mid-batch bail leaves claims behind, and I shipped one path that does exactly
that: `victim()` refuses when the batch has pinned every slot, and the `?`
returned straight out of the decision loop with every EARLIER reservation still
in `map`/`slot_row`, claiming rows whose bytes were never read.

The next request asking for one of those ids would have hit the cache and been
served whatever the slot happened to hold. That is the failure this cache's
checks exist to prevent — a wrong n-gram row is fluent output with wrong
logits, not a crash.

Both abort paths now go through `drop_reservations`, which is conditional on
both sides: a claim is withdrawn only if it is still the one this batch made.
Nothing in the current code can have replaced it, since the slots stay pinned
for the batch, but an unconditional `remove` would delete a LIVE mapping the
moment that stops being true — and, again, the symptom would be a wrong row
rather than a crash.

The fetch-failure path drops the whole batch rather than the failing worker's
share: the workers keep no shared progress record, so which rows landed is not
knowable at the join, and over-dropping only costs a refetch.

Found by Qwen's adversarial review of the design. Its other load-bearing
question — whether `read_exact_at` is really positional, since the whole
thread-safety argument rests on a shared `&File` having no cursor to race on —
checks out: `atlas_tier::pio::read_at` is `std::os::unix::fs::FileExt::read_at`,
i.e. `pread(2)`. Verified rather than assumed.

Rebuilt and re-measured, unchanged on the happy path: 4720 tokens 8686 ms,
8024 tokens 15841 ms, resolve 199 ms, and the greedy completions still hash
71615d90.. and 00221bef.. exactly as the serial arm produced them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ange for the PLE fix

Three corrections to the record, two of them to my own earlier claims.

WHERE COLD TTFT GOES. Per-stage over one 4656-token prefill:

  moe        2830 ms  48.8%
  ple        1683 ms  29.0%   <- ALL of it in ONE layer (L1: 1681.9 ms;
  gdn_block   686 ms  11.8%      every other SSM layer is 0.0)
  hc_pre_*    455 ms   7.9%
  hc_post_*   144 ms   2.5%

7450eb8 inferred from the warm-hit A/B that the GDN recurrence was ~94% of
cold TTFT. That was wrong, and wrong in a way worth naming: a warm SSM snapshot
hit skips the ENTIRE forward, so it cannot separate GDN from MoE. What that A/B
actually proves is that the GDN state is what makes the forward UNSKIPPABLE --
not what the forward spends its time on. GDN is 11.8%.

THE PLE FIX'S RANGE, not just its best number. 4727510's headline (-14.9% at
4720 tokens) is a controlled same-prompt A/B taken on a COLD row cache, where
that prefill takes 22,072 misses. Re-running the original five-leg sweep on the
same binary gives only 3.3%-11.7%, because the legs run in sequence and share
n-gram rows, so the cache warms and the miss count falls to 2-7k:

    268 tok 1660 -> 1467 | 1140 2648 -> 2397 | 2309 4320 -> 3971
   ~4700   8956 -> 8573 | 7980 16394 -> 15860

Both are real; they measure different cache states, and the honest summary is
"3% warmed, 15% cold" rather than either alone. Real prose should land nearer
the cold figure: the sweep's filler draws from a 26-WORD vocabulary, so its
n-grams collide far more than real text and its cache warms far faster than a
production workload's would.

MTP RE-VERIFIED on this binary after the PLE change, since that work touched
the prefill path:

  arm         C=1      C=2     greedy sha
  base      17.905   26.715    35eb56891bb5
  MTP K=2   21.650   25.300    35eb56891bb5

+20.9% at C=1, byte-identical output, tok_step 1.771, and the throughput gate
still correctly declines MTP at C=2. Matches the figures 4abe0b8 and 6d978e7
recorded, so nothing regressed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…n was wrong

4b22494 said the third verify row costs 1.40x because the verify FFN streams
the UNION of activated experts, and predicted 1.485x from 512*(1-(1-10/512)^R).
That was arithmetic over end-to-end throughput, never a measurement of the
verify itself — because the verify is the one width neither the decode nor the
prefill profiler covers, and `verify_k3_step` recorded ZERO timing phases while
its K=2 and K=4 siblings record fifteen each. K=3 was unmeasurable.

Three probes close that: `ATLAS_QWEN4EXP_VERIFY_PROF=1` (per-stage clock in the
batched mHC path), `ATLAS_MTP_MAX_DRAFTS` (raise the clamp far enough to profile
the width it forbids), and the timing records `verify_k3_step` was missing — its
`t_verify`/`t_propose` Instants already existed for a debug line and were simply
never handed to the accumulator.

THE VERIFY, mean us per layer call:

    stage          K=2      K=3     ratio
    moe          287.6    374.1     1.30
    hc_pre_attn  184.9    184.5     1.00
    hc_pre_ffn   183.8    184.5     1.00
    gdn_block     16.8     17.0     1.01
    TOTAL        698.9    786.9     1.126

MoE scales 1.30x, not the predicted 1.485x, and the whole SSM verify only
1.126x — BELOW the 1.354 token ratio. On the SSM half alone K=3 would WIN. The
union model over-predicted, and it was never the binding term.

WHERE THE COST ACTUALLY IS, per step:

    phase        K=2       K=3       delta
    fwd        73.54 ms  103.32 ms  +29.78   (90% of the penalty)
    propose     3.64 ms    7.27 ms   +3.63   (the second draft pass, as
    d2h         1.98 ms    1.67 ms   -0.31    expected: it doubles)
    step_mtp   80.01 ms  113.07 ms  +33.06

The 36 SSM layers are only +3.17 ms of that +29.78 ms forward. So +26.6 ms —
80% of the entire K=3 penalty — is the NON-SSM half: 12 attention layers, the
LM head over 3 rows instead of 2, the embedding. That half scales 1.55x where
the SSM half scales 1.126x.

K=3 still loses, measured end to end on this binary at C=1 with the gate forced:
21.72 tok/s at tok_step 1.715 against 20.20 at 2.323, i.e. step ratio 1.456
against token ratio 1.354. But THE CLAIM THAT IT IS STRUCTURALLY DEAD IS
WITHDRAWN. What loses it is an unexplained 1.55x in the attention-half forward,
not a bandwidth floor; bring that to the SSM half's 1.126x and the step ratio
falls under the token ratio.

Qwen's review of the earlier analysis asked for exactly this and I had not done
it: "before calling K=3 structurally dead, we need to fix the K=3 exactness
defect and profile actual expert unions and per-component step costs." The
per-component costs say the union was the wrong suspect.

The clamp stays at K=2 — K=3 is still slower AND still not output-exact (greedy
sha b47ec495171c against K=2's 35eb56891bb5). Raising it now needs, in order:
a per-stage probe on the attention half, a fix for whatever that finds, and the
row-2 defect. The first is the open question, and it is no longer a physics one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…sics

4d99f70 localised 80% of K=3's step penalty to the non-SSM half of the forward
and left "nothing here explains why yet". This is why.

`verify_a.rs` batches the 36 GDN layers into one call and runs the 12
full-attention layers like this:

    if layer_type == LayerType::FullAttention {
        // Attention layers: sequential per-token (need per-token metadata)
        for t in 0..k {

One pass per verify row, re-uploading per-token attention metadata and
re-running the entire layer — its 512-expert MoE FFN included — every time. So
the half that batches scales 1.126x and the half that loops scales 1.550x,
which is simply 3 passes where K=2 took 2. Measured:

    half                          K=2       K=3     ratio
    SSM, batched (36 layers)   25.16 ms  28.33 ms  1.126
    attention, per-row (12)    48.38 ms  74.99 ms  1.550

    per attention layer          4.03 ms   6.25 ms
    per SSM layer                0.699 ms            (5.8x)

5.8x per layer, for layers whose only structural difference is attention
instead of GDN — and the GDN block itself is 17 us of that 699.

THE PRIZE. Bring the attention half to the SSM half's 1.126x and K=3's step
falls 113.07 -> 92.55 ms:

    step ratio 1.157 against a token ratio 1.355   ->  K=3 PAYS
    K=3 25.10 tok/s against K=2's 21.43 today      ->  +17.1%

That is the first arithmetic in this investigation under which K=3 wins, and it
does not need better acceptance, a kernel, or a numerics change — 4b22494's
"K=3 would have to draft better than K=2 merely to draw" was computed against a
step cost that is 20 ms larger than it needs to be.

The machinery already exists. `decode_verify_batched_dispatch` (verify_e.rs)
batches attention across all R rows through `decode_multi_seq` with per-row
block tables, and weight-bearing ops through the M-generic arms, gated by
`supports_verify_batched`. It is wired for the CROSS-SEQUENCE case — n
sequences by their k rows — and not for the single-sequence K-row case that a
C=1 verify is.

NOT WIRED HERE, deliberately. Routing C=1 through it is a scheduler change, and
whether the mHC highway survives that path is unverified: this model's verify
lands its rows on the hyper-connection highway through `hc_pre_site`/
`hc_post_site`, and a path that never ran an mHC model would fail silently
rather than loudly if it skipped them. That is a measurement I have not made,
and shipping it on the strength of arithmetic is how the expert-union story got
written in the first place.

The clamp stays at K=2. Raising it needs, in order: route the single-sequence
verify through the batched dispatch (or batch the attention loop in place),
confirm the mHC sites still run correctly per row, and fix the row-2 exactness
defect. None of those is a numerics problem, and none of them is physics.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… tested

5b36080 projected +17.1% for K=3 from batching the 12 full-attention layers
the verify runs `for t in 0..k`, on the assumption that the 1.55x scaling of
that half was per-row WEIGHT re-streaming. It is not. Measured, and the
projection is withdrawn.

REACHING THE BATCHED PATH took five gates, and the last one is a real bug:
`impl_a1.rs` allocates `verify_hidden_stash` under `proposer.is_some()`, but
qwen4_exp installs its proposer AFTER construction, so the stash is NULL and
`can_batch_verify` returns false forever. The sibling allocation two lines
below uses `has_mtp` for exactly that reason and documents it; this one was
missed. The other four are the scheduler's `verify_idxs.len()>=2`, its
`chunk.len()>=2`, `can_batch_verify_dispatch`'s `n>=2`, and an internal
`ensure!(n >= 2)` in the dispatch body.

WITH ALL FIVE RELAXED IT RUNS, and correctly: 324 dispatches at n=1 R=3, zero
errors, and the greedy completion byte-identical to the per-row path
(b47ec495171c both ways). So the mHC highway's per-row `hc_pre_site`/
`hc_post_site` DO survive `decode_multi_seq` — the silent-skip risk I named as
the reason not to try this does not materialise.

AND IT IS NO FASTER: 20.195 tok/s batched against 20.13 per-row, against the
25.10 the projection wanted. K=3 does not move.

So the 1.55x is not per-row weight re-streaming. Three mechanisms have now been
offered for K=3's cost — expert union (4b22494), per-row attention batching
(5b36080), and this — and all three were refuted by the measurement that
followed them. What the attention half actually spends 4.03 ms per layer on is
still unattributed. The next attempt should start with a probe INSIDE the
attention layer rather than with a fourth mechanism guess.

Reverted: the five gate relaxations and the stash change. The stash fix is
probably correct on its own terms, but shipping it would make a previously
unreachable path reachable at C>=2 on this model, and I have validated it only
at n=1 — enabling an unvalidated path in production is not worth a diagnostic.
Kept: `ATLAS_QWEN4EXP_VERIFY_PROF`, `ATLAS_MTP_MAX_DRAFTS`, and the K=3
stepper's timing records, which are what made any of this measurable.

The clamp stays at K=2.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…1% of K=3's gap

6001c01 measured that batching the per-row attention verify does not help and
left the 1.55x unattributed. This says how much of it that duplication ever
could have been, and the answer is: less than a third.

`ATLAS_QWEN4EXP_ATTN_PROF=1`, mean us per attention-layer call:

    ffn (MoE)    376.1 us   55.3%
    attention    303.5 us   44.7%
    TOTAL        679.6 us

The 12 full-attention layers run once per verify row, so K=2 pays
12*2*679.6 = 16.3 ms and K=3 pays 12*3 = 24.5 ms. The per-row duplication is
worth +8.2 ms at K=3, against a measured non-SSM delta of +26.6 ms — 31%.
That is exactly why eliminating it moved throughput 20.13 -> 20.195 and nothing
else, and it retires the "+17.1% from batching" projection properly rather than
just noting that it failed.

WHAT IS LEFT IS NOW BOUNDED BY SUBTRACTION. The K=3 step costs +33.1 ms. Of
that: +3.2 ms in the 36 SSM layers (profiled), +8.2 ms in the 12 attention
layers (profiled), +3.6 ms in the drafter's second propose (timed). The
remaining ~18 ms is in what the forward does AROUND the layers at 3 rows
instead of 2 — LM head, embedding, final norm, per-row metadata uploads — and
none of that has a probe.

Stated as subtraction, deliberately. Three mechanisms have been offered for
K=3's cost in this file — expert union, per-row weight re-streaming, per-row
layer re-execution — and each was refuted by the measurement that followed it.
I am not offering a fourth. The next attempt should probe the forward's
non-layer work before proposing anything.

The clamp stays at K=2: K=3 is slower (20.20 vs 21.72 tok/s) and not
output-exact (b47ec495171c vs 35eb56891bb5).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…erms each cover it

Everything written here so far implied K=3 needs a large recovery. It does not,
and the number matters more than any of the mechanism stories that preceded it.

K=2 steps in 80.01 ms at 1.715 tok/step; K=3 in 113.07 at 2.323 (ATLAS_MTP_TIMING,
same binary, gate forced, C=1). Token ratio 1.3545, so K=3 breaks even at
80.01 * 1.3545 = 108.38 ms against a measured 113.07:

    SHORTFALL 4.69 ms — 4.2% of the K=3 step

Against the attributed budget of the +33.06 ms penalty (+3.2 ms SSM layers,
+8.2 ms attention-layer per-row duplication, +3.6 ms drafter second propose,
+18.1 ms unattributed), TWO single terms each exceed the whole shortfall.
Recovering either one pays for K=3.

AND THAT EXPOSES A CONTRADICTION I should name rather than leave implicit. The
batched-verify experiment removed the per-row attention duplication and moved
throughput 20.13 -> 20.195 — about nothing — when 8.2 ms off a 113 ms step
should have been worth roughly 2 tok/s. So either `decode_verify_batched_
dispatch` does not actually stop running attention per row (its own doc says
attention goes through `decode_multi_seq` "with per-row block tables", which
may still be a loop), or the +8.2 ms attribution derived from the
per-attention-layer probe is wrong.

Resolving that is the cheapest next move by a wide margin, and it is a
measurement — instrument inside the batched path and count attention-layer
calls per verify step — not another mechanism.

No behaviour change; the clamp stays at K=2.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… it batches nothing

5de7bd5 flagged a contradiction: the batched-verify experiment removed the
per-row attention duplication yet moved throughput 20.13 -> 20.195, when 8.2 ms
off a 113 ms step should have been worth ~2 tok/s. Either the path did not
actually stop looping attention, or the attribution was wrong.

It did not stop looping. Counting attention-layer calls per verify step with
`ATLAS_QWEN4EXP_ATTN_PROF=1`, K=3, same binary, gates relaxed:

    arm        attention-layer calls    mean us/call
    per-row              64                256.5
    batched              64                252.6

Identical. `decode_verify_batched_dispatch` batches ACROSS SEQUENCES — its
"per-row block tables" are per row OF THE BATCH, i.e. one per sequence — so at
n=1 there is nothing for it to batch and one sequence's K rows still enter
attention one at a time. The null result was measuring a no-op.

THIS IS THE USEFUL DIRECTION. The +8.2 ms of per-row attention duplication is
real and still unrecovered, and it is larger than the 4.69 ms K=3 is short. The
change K=3 needs is to batch the 12 full-attention layers across the K VERIFY
ROWS OF ONE SEQUENCE — exactly what the 36 GDN layers already do via
`decode_batched_hc`, and what the attention layers do not.

That is real work rather than a flag. `verify_a.rs`'s `for t in 0..k` exists
because each row carries its own position and block-table metadata, and a
batched arm has to carry that per row. But it is the first identified change
that would make K=3 pay without needing better acceptance, a kernel, or a
numerics change — and it would help K=2 as well, which pays the same
duplication twice instead of three times.

Experiment reverted again (five gates + the stash allocation). The clamp stays
at K=2. What is kept is the four probes that made any of this measurable, and
they now bound the whole K=3 penalty: +3.2 ms SSM layers, +8.2 ms attention
duplication, +3.6 ms drafter second propose, +18.1 ms unattributed forward.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… measurement

78ab7df states flatly that `decode_verify_batched_dispatch` batches across
sequences and therefore does nothing at n=1. The equal attention-layer call
counts (64 in both arms, 256.5 / 252.6 us) ARE a measurement; that explanation
for them is not.

The call-count run had the gate probes reverted, so it shows the counts are
equal without independently confirming the batched arm engaged that time. Two
readings produce equal counts — "taken, and does not batch attention" and "not
taken at all" — and only the first is ruled in, by the earlier run under
identical gates that logged can_batch=true with 324 dispatches and zero errors.

A strong chain, but a chain. The reason this investigation ran as long as it did
is three mechanism stories asserted ahead of their evidence, so the distinction
is worth marking rather than letting the next person inherit my inference as a
fact. Re-run the count with the probes in place before building on it.

Unchanged: the +8.2 ms of per-row attention duplication is real, unrecovered,
and larger than the 4.69 ms K=3 is short.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ile — withdrawn

5b36080, 858585e, 78ab7df and fdf8ea3 all rest on one mistake: I read
`verify_a.rs::decode_verify_dispatch`, saw it run the full-attention layers
`for t in 0..k`, and attributed 80% of K=3's step penalty to that duplication.

K=3 does not go through that function. It goes through
`verify_c.rs::decode_verify_graphed_k3_dispatch`, which already batches the
attention layers across the verify rows, and says so:

    // k ROWS of ONE sequence, not k sequences: per-sequence aux state (the
    // QSA indexer) must advance once per row against this sequence's own
    // state. See `decode_multi_seq_rows`.
    layer.decode_multi_seq_rows(hidden, residual, k, ...)

So there is no per-row attention duplication in the K=3 path. The +8.2 ms
attributed to it does not exist, the "12-of-48 layers" framing is wrong, and
the projected +17.1% was never available.

It also explains two results I had explained wrongly. The batched-verify
experiment moved nothing because attention was ALREADY batched — not because
`decode_verify_batched_dispatch` batches across sequences (which may be true
but was never the reason). And the 64 equal attention-layer call counts came
from a probe in `decode_inner_hc`, the SINGLE-TOKEN path, which the verify does
not use; it was never measuring the verify at all.

WHAT SURVIVES, all directly measured:

    K=2 step 80.01 ms @ 1.715 tok/step | K=3 113.07 @ 2.323
    token ratio 1.3545 -> break-even 108.38 ms -> K=3 SHORT BY 4.69 ms

    +3.2 ms   36 SSM verify layers   (VERIFY_PROF, 698.9 -> 786.9 us/layer)
    +3.6 ms   drafter second propose (MTP_TIMING, 3.64 -> 7.27 ms)
    +26.3 ms  everything else in the forward — UNATTRIBUTED

The unattributed term is LARGER than when this file claimed to have explained
it. Four mechanisms have now been asserted here and refuted — expert-union
bandwidth, per-row weight re-streaming, per-row layer re-execution, and a
12-of-48 batching gap. Three fell to measurement; this one fell to reading the
right file, which I should have done before the first of them.

No fifth mechanism is offered. The next step is a probe inside `verify_c`'s
forward at K=2 against K=3. The clamp stays at K=2.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…d two bad readings

A probe inside `verify_c`'s own forward — the one K=3 actually runs — gives per
verify: norm 9 us, lm_head 1508 us, argmax 289 us. About 1.8 ms, matching the
~3.17 ms roofline the batched NVFP4 vocab GEMV is documented at, and far too
small to be the +26.3 ms K=3 spends over K=2. The tail is not the answer.

TWO READINGS FROM THAT PROBE ARE DISCARDED, not reported.

An earlier arrangement of it showed "norm+lm_head+argmax = 84.25 ms, 85.5% of
the forward". That was a bucket-boundary artifact: its final accumulator fired
after everything else and absorbed all time no other bucket had claimed. Split
properly, the same region is 1.8 ms. Had I stopped at the first arrangement I
would have reported an LM-head bottleneck that does not exist.

The split version also prints `layers=0us`, which is not a measurement either —
the layer-loop accumulator never fires. That is why the forward is still
unattributed: the probe answered the question it could and failed the one that
mattered.

The probe is REVERTED rather than left in tree. An instrument that prints
plausible wrong numbers is worse than none, and this one printed two.

Where K=3 stands, measured: short by 4.69 ms (step 113.07 vs break-even
108.38 at a 1.3545 token ratio). Attributed: +3.2 ms SSM verify layers,
+3.6 ms drafter second propose. Unattributed: +26.3 ms. Ruled out so far:
expert-union bandwidth, per-row weight re-streaming, per-row layer
re-execution, a 12-of-48 batching gap, and now the lm_head/argmax tail.

Next person: instrument `verify_c`'s layer loop with a bucket verified to fire
before trusting what it prints.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
AzeezIsh added a commit that referenced this pull request Sep 2, 2026
qwen4_exp serving (#16) + GB10 validation fixes, Windows leg fix and passing gate records
@AzeezIsh
AzeezIsh merged commit 50c17f5 into main Sep 2, 2026
18 of 23 checks passed
@AzeezIsh
AzeezIsh deleted the feat/qwen4exp-serve branch September 27, 2026 07:15
AzeezIsh pushed a commit that referenced this pull request Nov 1, 2026
… markup

A forced or required Poolside v1 call decodes a property with an enum or
const from that set: a string as raw text, any other value as its JSON
with optional separator spaces. Open properties keep the free-text value
rule, auto mode is unchanged, and a closed grammar that does not compile
falls back to open values. For literal-XML models whose format owns the
<tool_call> envelope (GLM), the stream sanitizer keeps <arg_key>/
<arg_value> text outside it, as blocking already returns it.

Tests from SparkGLM 0.2.0's qualification probes: closed enum/const sets
(string, array, object, const, the guard canary's operations), open values
beside closed ones, auto left open, spelled call markup streaming like
blocking, and arguments delivered in generated key order.

spark-shared #16. Ported from Enntity/atlas 928f7de and be6b53d
(AGPL-3.0-only).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AzeezIsh added a commit that referenced this pull request Nov 10, 2026
…the 27B verify and Ripple shapes; rowgemv at M=8/16

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AzeezIsh added a commit that referenced this pull request Nov 10, 2026
…at defaults, thinking off per request); kbench #16 batch8 arity

gufo_bench.py takes extra request fields from H2H_REQ_EXTRA (Halogen thinks by default and has no server flag);
wait_ready takes a try count so a first-start weight download can finish.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

4 participants