Repository navigation
qwen4_exp serving (#16) + GB10 validation fixes, Windows leg fix and passing gate records - #17
Conversation
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.
Prefix caching is correct with LongCat now. Cache ON scores 60/60 across five prompt lengths and 16/16 on the probe that used to regurgitate the system prompt, with zero cross-stream nonce bleed. The bug, from fef7959: `paged_mla` attends over the K/V it just assembled ("not from paged cache", per its own comment), so a prefix-cache SKIP hides the cached tokens from attention entirely — the model answers from the tail of its prompt. Q/K/V were bit-identical to the validated arm (cos 1.000000, all 32 heads) while attn_out diverged on 27/32, which is only possible if the KEY SET differs. The honest fix is absorbed attention against the compressed cache, because MLA keeps a LATENT KV cache — there is no expanded K/V to gather, and every `prefill_attention_paged_*` variant (the ones with the `q_offset` this needs) wants an expanded-layout cache. That is a real piece of work, not a patch. So: decline the SKIP, not the cache. `prefill_b_prefix_lookup` takes `PrefixMatch::empty()` when any layer reports `uses_local_mla_prefill()`, exactly as it already does for prompt-logprob collection — same reason, that path also needs every position live. Prefix caching stays ON and CORRECT: block reuse still happens, the decode path still reads the cache, and prefill pays full price instead of quietly answering from half the prompt. Cost, measured and stated plainly: the prefix TTFT win is gone for MLA models (1487 ms cold -> 1486 ms warm, +0%). It was 1513 -> 32 ms while wrong. A correct 1.5 s beats a wrong 32 ms, and this is recoverable — absorbed attention gets it back. ATLAS_MLA_PREFIX_SKIP=1 opts back in for whoever implements that. Scope is the smallest that is honest: `uses_local_mla_prefill()` defaults FALSE on the trait, so every non-MLA model is untouched, and it is true only where `mla.is_some()`. This also catches Mistral-Small-4 and DeepSeek-V4-Flash, which have the same hole and have simply never been run with prefix caching against a partial hit. Supersedes fef7959's guard, which refused the request outright. Refusing was right while the cause was unknown; now that it is known, serving correctly beats erroring. 648 spark-model + 104 spark-server tests green, workspace clippy and fmt clean.
The min_p/top_n_sigma precedence work pushed
`spark-server/src/api/chat/sampling_setup.rs` to 518 lines, and
`.github/workflows/file-size-cap.yml` does not excuse it: the allow-list
is 111 entries and this file is not one of them. Adding it there would be
the wrong fix — the allow-list exists for files that were already over
when the cap landed, not for new growth.
The 111-line `#[cfg(test)] mod tests` block moves to a sibling
`sampling_setup_tests.rs`, declared the way `msg_entry_tests.rs` already
is in this same directory:
#[cfg(test)]
#[path = "sampling_setup_tests.rs"]
mod sampling_setup_tests;
Parent 518 -> 410, tests file 117. No behaviour change; the resolution
logic is untouched.
One trap worth naming, because it has now cost time twice on this branch:
moving a `mod tests` body into its own file changes what `super` means.
Inside `sampling_setup.rs` the block was one module deep, so `super::foo`
reached the parent's items. As a `#[path]` sibling it is still a child
module — but its `use` lines were resolving names that live in
`api::chat`, not in `sampling_setup`, so they need `super::super::`.
`cargo clippy --all-targets` catches it (E0432); a plain `cargo build`
does not, because it never compiles the test cfg.
Verified locally against the workflow's own allow-list (a script that
parses `allow_list=( ... )` out of the yml rather than guessing):
PASS, every .rs under crates/ is <=500 LoC or allow-listed.
`cargo fmt --all --check` clean, `cargo clippy -p spark-server
--all-targets` clean, `cargo test -p spark-server --lib` 104 passed.
Note on the one red test in this crate: `cargo test -p spark-server`
also reports `the_baked_attestation_reproduces_from_the_tree` failing on
`gb10/qwen3.8-27b/nvfp4`. That is not from this change and not from the
longcat kernel symlinks. A target's closure hash covers
`kernels/<hw>/common/*.cu` plus its own model dir; commit 0c8222f added
`kernels/gb10/common/moe_topk_softmax_bias.cu` for the zero-expert
router, which is in *every* gb10 target's input set, so every hash baked
before it is stale. The build re-bakes on a real kernel build. The
symlink commit fe2c76a touched only
`kernels/gb10/longcat-flash-lite/nvfp4/`, which is not in qwen3.8-27b's
set at all.
Bumped from 8 while exercising concurrency on the LongCat serve path. Both are still env-overridable (MAX_NUM_SEQS / MAX_BATCH_SIZE).
LongCat ships plain BF16 with no NVFP4/FP8 calibration metadata, so every
weight is runtime-quantized to 4 bits at load. The PR body called that out
as "how much quality that costs is unmeasured". This measures it.
WHAT WAS MISSING: a quality metric at the LOGIT level. The existing
`full_forward_cmp.py` compares per-sublayer hidden states, which says the
port is wired correctly but not what the output distribution costs — a
0.995 hidden-state cosine can still reorder the top of a 131072-way
softmax, and reordering is what the sampler sees.
`bench/ngram_ref/logit_quality.py` closes that. It compares Atlas's final
logits against the reference's `logits_last` over the FULL vocabulary:
top-1 agreement, top-k overlap, logit cosine, and KL(ref||atlas). It
drives the existing `ATLAS_NEMO_DUMP` hook rather than the API, because
`/v1/completions` logprobs are keyed by decoded STRING and capped at 20 —
two ids that decode alike collide and the tail is invisible.
MEASURED (16-token golden prompt, deterministic — bit-identical on repeat):
arm KL vs ref logit cos top-100 tok/s
default (all NVFP4) 0.0464 0.998250 86/100 24.31
ATLAS_NVFP4_MLA=0 0.0382 0.998567 87/100 20.18
+ ATLAS_LONGCAT_BF16_FFN=1 0.0240 0.999033 90/100 16.67
The baseline is not harmless: reference gives its own top token p=0.0170,
baseline Atlas says 0.0209 (23% overconfident), the both-levers arm 0.0176.
And only 3 of the reference's top 5 survive in the baseline's top 5 — the
model card recommends `top_k: 4`, so the sampler is drawing from a partly
wrong shortlist.
NEW LEVER: `ATLAS_LONGCAT_BF16_FFN=1` keeps the per-sublayer dense FFN in
BF16, reusing the `set_bf16_weights` path already built for Gemma-4. The
MLA half (`ATLAS_NVFP4_MLA=0`) already existed and was never measured.
DEFAULT OFF, deliberately. Decode here is weight-bandwidth bound and each
lever costs throughput in proportion to the extra bytes it reads per token:
MLA -> BF16 +1.28 GB/tok read EVERY token
dense FFN -> BF16 +2.21 GB/tok read EVERY token
Calibrating against the measured pair gives ~185 GB/s effective, which
then PREDICTS the MLA-only arm at 20.80 tok/s against 20.18 measured (3%).
-31% decode is not a trade to make silently, so both stay opt-in and the
serve script documents the table.
WHERE THE REMAINING ERROR IS: with MLA, dense FFN, embed_tokens and
lm_head all BF16, the per-sublayer cosine drops once at layer 1
(0.9999 -> 0.9986) and then stays FLAT through layer 12 (0.9984-0.9992).
It does not compound with depth, which is the signature of a per-layer
quantization floor rather than a propagating bug — and the only component
still quantized is the routed experts. They are 63.0 of the 70.2 GB
resident, so they are the whole remaining gap.
Two groups turned out to need nothing, worth recording so nobody re-checks:
- the n-gram tables are ALREADY BF16 (the NVMe row cache serves raw rows,
superseding the older FP8-quantize-on-load path)
- `embed_tokens` and `lm_head` are ALREADY BF16 (plain `dense()`)
NEXT, and the reason the numbers above are laid out this way: the experts
are read SPARSELY — top-12 of 256 per layer — so upgrading them to FP8
costs only +0.74 GB/tok, LESS than either lever here, while addressing the
error source both of these leave untouched. Predicted ~22.2 tok/s (-9%)
against the 24.31 baseline. That needs a BF16->FP8 block-scaled quantizer;
`moe_fp8_grouped_gemm.cu` already consumes exactly that layout.
…earest
The previous commit measured what NVFP4 costs LongCat and shipped two BF16
levers to buy it back, then narrowed the remaining error to one place: with
MLA, dense FFN, embed_tokens and lm_head all BF16, the per-sublayer cosine
drops once at layer 1 and stays FLAT to layer 12. Nothing compounds. The
only component still quantized is the routed experts, and they are 63.0 of
the 70.2 GB resident.
BF16 experts do not fit (+47 GB against a 97.3 GB budget at 0.80 util).
FP8 does: +10.6 GB measured, 51.9 -> 62.5 GB pre-KV, KV still 570k tokens.
MEASURED (same golden prompt and harness as the previous commit):
arm KL vs ref logit cos top-5 tok/s
default (all NVFP4) 0.0464 0.998250 3/5 24.31
FP8 experts 0.0344 0.998588 4/5 22.69
NVFP4_MLA=0 0.0382 0.998567 3/5 20.18
NVFP4_MLA=0 + FP8 experts 0.0301 0.998799 4/5 ~19.2
NVFP4_MLA=0 + BF16_FFN 0.0240 0.999033 3/5 16.67
FP8 experts alone is -26% KL for -6.7% decode, and it STRICTLY DOMINATES
the MLA lever — better KL, better cosine, better top-5, and 12% faster.
It is also the only arm that repairs the top-5 shortlist, which is what
the model card's `top_k: 4` actually samples from.
THE COUNTERINTUITIVE PART, and the reason to write it down: the experts
are 90% of the weights but the CHEAPEST group to upgrade, because routing
reads only top-12 of 256 per token. Per-token weight bytes added:
experts -> FP8 +0.74 GB/tok sparse
MLA -> BF16 +1.28 GB/tok dense, every token
dense FFN -> BF16 +2.21 GB/tok dense, every token
Decode is bandwidth-bound at ~185 GB/s effective, calibrated from the
default-vs-both-BF16 pair. That model then PREDICTED the MLA-only arm at
20.80 (measured 20.18) and FP8-experts at 22.16 (measured 22.69) — two
independent confirmations, so the ordering above is structural, not a
quirk of one prompt.
WHAT THIS ADDS
1. `quantize_bf16_to_fp8_blockscaled.cu` — the missing runtime quantizer.
Atlas had BF16->NVFP4 and BF16->FP8-per-ROW; the FP8 grouped MoE GEMM
reads BLOCK scales `[N/128, K/128]` FP32. Feeding it a per-row buffer is
not a shape error it can detect — it would index a shorter array and
dequant with the wrong scale, which is why `Fp8Weight::scale_format` is
tagged and asserted at dispatch.
2. `ATLAS_LONGCAT_FP8_EXPERTS=1` on the LongCat loader. The NVFP4 expert
slot is `ExpertWeight::null()` when it is on, so both copies are never
resident; the BF16 source is freed after quantize, mirroring the
Bf16Raw NVFP4 arm (without that free the 63 GB of BF16 experts stay
alongside their FP8 copies). The shared-expert slot gets ZERO-FILLED
FP8 buffers, not nulls — LongCat has no shared expert, but the fused
kernels read the slot unconditionally, same reason `mk_zero` exists for
the NVFP4 twin.
3. Zero-expert routing on two more dispatch variants. Turning FP8 on first
produced a NAMED REFUSAL rather than wrong output, which is the guard
working — but it had to be wired, in two places:
- `forward_prefill_fp8`: gate GEMM was sized `num_experts`, which on
LongCat computes 256 of 384 logits and routes on a truncated
distribution. Now `router_logits_n`, matching the NVFP4 twin.
- `forward_batched`: this is where a SHORT FP8 prefill lands —
`forward_prefill` only takes the grouped GEMM above 64 tokens, so
every conversational turn under 65 tokens was refusing. Wired via a
per-token `router_softmax_bias_one`, whose `zero_accum` is offset by
`t*4` because that buffer is `[N]`, one scalar per token; passing the
base pointer would make every token overwrite token 0's identity
weight.
4. The six zero-expert refusals now name their dispatch variant. They
shared one message, so a refusal said the model was blocked but not
WHERE — that cost a full load cycle to narrow down by hand.
Also folds `forward_batched`'s three-way correction-bias scoring dispatch
into `router_bias_one`, which keeps that file under the 500-LoC cap and
puts the three scoring functions side by side, where picking the wrong one
is a silent mis-route rather than an error.
Gates: LoC cap PASS, `cargo fmt --all --check` clean, spark-model builds,
all-targets release build green (178 kernels for longcat-flash-lite).
Default is unchanged — every lever is opt-in.
First code on the qwen4_exp port. Parser only — no loader, no forward. `Qwen4ExpForConditionalGeneration` is a ~180B hybrid multimodal MoE: 48 layers interleaving GDN and full attention 3:1, 512 experts top-10 plus a shared expert, a 4-stream hyper-connection residual, a QSA indexer on the full-attention layers, PLE n-gram injection at ONE layer, and a ViT tower. It nests `text_config` like qwen3_5_moe, but four features put it outside that arm, so it gets its own parser rather than another `dispatch.rs` case. WHAT MAPS ONTO EXISTING FIELDS — most of it, because the DeepSeek-V4 port already built the two hardest pieces: hc_count -> hc_mult (Atlas already runs hc_mult=4) indexer_n_heads -> index_n_heads indexer_head_dim -> index_head_dim indexer_budget -> index_topk indexer_compress_ratio -> compress_ratios (per-layer, see below) ngram_size -> emb_neighbor_num heads_per_ngram -> emb_split_num layer_types -> LayerType, verbatim (serde snake_case already fits) NEW FIELDS (5): `hc_lowrank`, `ngram_vocab_size_base`, `ngram_split_parts`, `ple_layer_ids`, `ple_conv_kernel_size`. `hc_lowrank` is the load-bearing one. Atlas's mHC plumbing is DeepSeek-V4's, whose mixer is a Sinkhorn-normalized square matrix; Qwen4-Exp mixes the same 4 streams through a LOW-RANK pair (rank 320) instead. The stream-major `[T, hc_mult, H]` layout and `hc_mult` carry across unchanged — only the mixing math differs — so a non-zero `hc_lowrank` is what will select the variant once the kernel lands. Streams-without-rank is REFUSED rather than silently falling into the Sinkhorn path and mixing with the wrong math. `compress_ratios` is built per-layer from `layer_types`: only the 12 full-attention layers carry an indexer, since the 36 GDN layers have no KV to select over. Encoding it here means the attention path can index `compress_ratios[l]` without re-deriving the 3:1 interleave. TWO THINGS THE PARSER ASSERTS THAT ARE EASY TO GET WRONG LATER: 1. The n-gram head slices are CONCATENATED, not projected. 16 heads x 160 dims = 2560 = hidden_size. LongCat projects each 256-dim row up to hidden and SUMS; Qwen concatenates. So the head count must divide hidden_size exactly, and the error says why rather than just "not divisible". 2. `layer_types` must be present and its length must equal `num_hidden_layers`. Falling back to `full_attention_interval` would be a guess, and a wrong interleave puts GDN weights on attention layers. Partial config is refused for both the hyper-connection pair and the indexer trio: a half-declared feature means a key rename we have not learned yet, and this parser's whole job is to notice that. TESTS: 14, including `parses_the_real_config_json_when_present`, which parses the SHIPPED config.json when `ATLAS_QWEN4_EXP_CONFIG` points at a checkpoint and skips otherwise (CI has no checkpoint; the GB10 box does). Verified against RadixArk/Qwen3.8-Flash-Next-NVFP4: 48 layers, exactly 12 full attention, hidden 2560, 512 experts, hc 4/320, indexer budget 2048, 16 n-gram heads, ple_layer_ids [2], vision present. The hand-written fixture can drift from the real file; that test is what catches it. Also confirmed while sizing (#753 items 1-2): `model.safetensors.index.json` maps all 206 files across all three families (192 `layer-*-experts-*`, 4 `model-bf16-*`, 10 `model-plefp8-*`), 296,475 tensors, and its `total_size` of 135,195,303,851 bytes is 125.91 GiB — consistent with the per-family split, so the 78.3 GB resident figure the checkpoint decision rests on holds. 126 atlas-core tests green, clippy --all-targets clean, LoC gate PASS.
`ns_audit.py` collapses the checkpoint's 296,475 tensors into 111 name families and gives each an explicit destination keyed to the issue's work items. A loader that silently skips a family produces a model that RUNS and is WRONG, so the useful artifact is the complete list — including the families being dropped on purpose (MTP). All 111 families classify; none unclassified. Two architectural facts this surfaced that config.json alone does not: - There are NO standalone `input_layernorm` / `post_attention_layernorm` tensors and no final `model.norm`. Normalization lives inside the hyper-connection blocks (`hc_norm`), and the model-level `hyper_connection_mixer` — which collapses the 4 residual streams back to one before `lm_head` — carries the final norm. A loader looking for the usual per-layer norms finds nothing, and must fail rather than paper over it with defaults. - The PLE block has a `conv1d`, matching `ple_conv_kernel_size: 4`. It is not a plain embedding lookup, which is further evidence for the cross-attention reading flagged as the top correctness risk in #753 item C. `ckpt_split.py` prices the single-Spark fit from real file sizes rather than a paginated Hub listing: 63.32 GB experts + 47.68 GB PLE + 14.91 GB backbone = 125.91 GB, of which 78.23 GB is resident once the PLE tables defer to the NVMe row cache, against a 97.3 GB budget. It also documents the unit trap: index.json's `total_size` is BYTES (135,195,303,851 = 125.91 GiB), and reading it as GB invents a 9 GB discrepancy that is not there.
…t claim
Inferact published a second NVFP4 quantization of the same base model. Their
`text_config` is IDENTICAL to RadixArk's field-for-field except one key, so
the whole config-layer difference is the name:
RadixArk model_type: qwen4_exp Qwen4ExpForConditionalGeneration
Inferact model_type: qwen3_8_flash_next Qwen3_8FlashNextForConditionalGeneration
Qwen3.8-Flash-Next shipped under the older name and was renamed later;
quantizers pinned to different transformers revisions emit different ones.
Both now route to `parse_qwen4_exp` and NORMALIZE to `qwen4_exp`, so
kernel-target resolution and every downstream `model_type ==` sees one
family. The architecture fallback covers a config that declares only
`architectures` (the same path LongCat needed).
CORRECTION — the previous commit's message and #753 item G both said the
routed experts ship as FUSED 3-D per-layer tensors
(`gate_up_proj [512,1280,2560]`). That is true only of the MTP block, which
we are dropping for v1. The 48 main-model layers, in BOTH releases, are
per-expert separate gate/up/down in standard ModelOpt NVFP4:
weight U8 [640, 1280] packed E2M1
weight_scale F8_E4M3 [640, 160] per-16 block
weight_scale_2 F32 scalar per-tensor
input_scale F32 scalar
That is `Nvfp4Variant::Standard` — the layout `quantized_any` already loads.
294,912 expert tensors in each release (48 x 512 x 12), verified by reading
shard headers from both. So item G is close to a non-issue rather than the
small-medium job it was scoped as. Issue updated.
THE REAL DELTAS between the two releases, for the loader:
- PLE dtype. RadixArk: FP8 E4M3 + one BF16 scalar scale, 47.7 GB. Inferact:
plain BF16, no scale, 95.4 GB. BF16 is the simpler path AND the more
accurate one — on LongCat, BF16 n-gram rows measured 0.0050 error against
the reference vs FP8's 0.0247. The per-token gather is ~5 KB, so the
extra NVMe bytes cost nothing that matters.
- Deferral must key on TENSOR NAME, not filename. RadixArk isolates the
tables in `model-plefp8-*`; Inferact buries all 128 shards inside one
95.4 GB `model-00001-of-00004.safetensors`. Keying on
`.ple.ple_embedding.ngram_embedding.shard_` works for both and does not
depend on how a quantizer packed its files.
- MTP: RadixArk BF16 fused (31 tensors), Inferact NVFP4 per-expert (6,173).
Both dropped for v1.
Sizing, from the indexes: RadixArk 125.91 GiB total / 78.2 GB resident;
Inferact 170.19 GiB total / 74.8 GB resident. Both fit the 97.3 GB budget.
Inferact is 3.4 GB SMALLER resident (its MTP is quantized) while needing
44 GB more disk.
`bench/qwen4_exp/cmp_repos.py` reproduces the side-by-side from the two
indexes.
15 qwen4_exp tests (new: `both_naming_revisions_route_to_this_parser`, which
goes through the full `parse_config` dispatch rather than calling the parser
directly). 127 atlas-core tests green, clippy --all-targets clean.
Hard prerequisite for loading anything: Atlas resolves a kernel target by model_type, and none existed, so the model could not resolve at all. Compiles as target 24 (gb10, qwen3.8-flash-next, nvfp4) — **169 kernels, ZERO model-specific overrides**. The nvfp4 shadow is a module map and nothing else. That empty-shadow shape is deliberate, not a stub. It is already supported (`nllb-200-3.3b/bf16` ships the same way), and it is the honest starting point because the startup kernel audit is FAIL-CLOSED: if a dispatch path needs something `common/` does not provide, the audit names it rather than letting the model serve wrong numbers. Guessing at overrides up front would just be adding untested code to find that out. `qwen3.6-35b-a3b` is the closest live architecture — GDN + MoE + NVFP4 + ViT, and it shares this model's vocab (248320), rope_theta (1e7), head_dim (256), partial_rotary_factor (0.25), gated attention and GDN key geometry (16 heads x 128, conv kernel 4). Its module map is copied verbatim. Its three TUNED overrides (gated_delta_rule, moe_w4a16_grouped_gemm, w4a16_gemm) are NOT: they are shaped for hidden 2048 / 256 experts where this model is hidden 2560 / 512 experts, so adopting them is a later tuning question, not a copy-them-now one. MODEL.toml records the geometry the port needs kept straight — 48 layers 3:1 GDN:full (only the 12 full-attention layers hold KV, which is why a ~19-24 GB KV budget goes further here than 48 layers suggests), 512 experts top-10, the 4-stream / rank-320 hyper-connection residual, the QSA indexer, and the PLE n-gram geometry (16 heads x 160 dims = 2560, so CONCATENATED rather than projected-and-summed like LongCat's). Only `qwen4_exp` is bound in [[model_types]] because dispatch.rs already normalizes `qwen3_8_flash_next` onto it — one family, one binding. Sampling comes from the checkpoints' generation_config.json (temp 1.0, top_k 20, top_p 0.95). No per-category card guidance exists for this model yet, so all four categories carry the vendor defaults rather than numbers invented here; revisit when agentic runs give evidence. Serving is NOT complete — mHC, the QSA indexer and PLE are unwired.
The existing n-gram work was described as groundwork for "the LongCat /
Qwen3.8-Flash-Next family". Read against the published weights, that grouping
does not hold: Qwen3.8-Flash-Next uses a different algorithm, not a different
parameterisation.
Both hash token ids into K*(N-1) heads of width embed_dim/(K*(N-1)), both reset
their shifts at document boundaries, and both therefore decode from the last
N-1 tokens. Past that they share nothing. LongCat sums a polynomial in powers
of the vocab size over tables of `ratio*V + 2i + 1` rows and fills an
out-of-segment shift with 0. qwen4_exp XORs `shift_d * m_d` where the
multipliers are seeded SplitMix64 draws, sizes each head's table at the next
consecutive PRIME above a base, concatenates the heads into one tensor
addressed by per-head offsets, and fills with the EOS id. A LongCat id handed
to a qwen4_exp table reads an unrelated row, so the two are separate types and
a test asserts they do not coincide.
Everything derived here is reproduced from config.json alone and checked
against Qwen/Qwen3.8-Flash-Next-FP8 itself rather than against a reference we
also wrote: the layer_multipliers, ngram_heads_vocab_sizes and
ngram_heads_offsets buffers, and the [2_500_012, 160] x 128 shard geometry.
That is the only authority that can settle a hash — a wrong multiplier does not
crash, it reads the wrong embedding and the model degrades into noise.
Two traps are encoded as tests rather than comments, both of the kind that load
a real tensor from the wrong place:
* ple_layer_ids is ONE-indexed. The config says [2]; the weights live at
layers.1.ple.*.
* seed is ABSENT from that config.json, so it must default to 1234. Zero
draws different multipliers and hashes every token wrong, silently.
shift_right_ignore_eos gains a fill parameter rather than a second copy: the
segmentation is the one thing the two families genuinely share, and two walks
would drift apart.
Config only. docs/porting/QWEN4_EXP.md is the gap list for the rest —
dispatch, low-rank hyper-connections, the sparse-attention indexer, the PLE
tower, the 512-expert MoE, the vision tower, the hybrid MTP head — and leads
with the constraint that decides the whole port: 185.5 GB of FP8 weights
against a GB10's ~119 GB.
Derived independently from the Apache-2.0 reference in huggingface/transformers
(src/transformers/models/qwen4_exp/); attribution in docs/porting/QWEN4_EXP.md,
mirroring how bench/ngram_embed/LICENSE carries Meituan's MIT notice.
Co-Authored-By: Claude Opus 5 <[email protected]>
`qwen4_exp` was rejected by name in parse_config. It now parses, pinned against
the published Qwen/Qwen3.8-Flash-Next-FP8 config.json vendored whole into
test_data/ rather than trimmed -- 48 layers on a 4-stride hybrid schedule (12
full attention, 36 linear), 24 q heads over 2 kv at head_dim 256, 512 experts
top-10 with a 640-wide shared expert, one MTP block, interleaved MRoPE
[11,11,10] at quarter rotation, block-scaled FP8, and a vision tower.
Two defaults in that file are absent rather than stated, and both fail silently
rather than loudly:
* `norm_topk_prob` -- HF defaults it true, serde defaults it false. Wrong, it
skips the top-K renormalisation and routing weights stop summing to 1.
Forced true here, the same way the qwen3_5 arm already does.
* `seed` -- HF defaults it 1234. Wrong, it draws different SplitMix64
multipliers and every n-gram token hashes to an unrelated row. A test
asserts the parsed config still reproduces the checkpoint's shipped
layer_multipliers, which is what makes the default load-bearing rather
than cosmetic.
Q is ungated here: full-attention layers carry q/k/v/o plus q_norm and k_norm
with no interleaved gate. `output_gate_type = "sigmoid"` describes the LINEAR
attention pathway's gate, which is its own tensor (`linear_attn.in_proj_z`).
Parsing is not serving. There is still no qwen4_exp weight loader, and the
checkpoint is 185.5 GB against a GB10's ~119 GB. docs/porting/QWEN4_EXP.md
remains the gap list.
Co-Authored-By: Claude Opus 5 <[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]>
…or now The recipe YAML, quickstart header and serve_qwen4exp_tui.sh all still teach the pre-#754-merge behavior (ATLAS_PLE_MAX_TOKENS defaults to 2048; >8K context needs it raised). Since qwen4_exp.rs derives the floor from config.max_batch_tokens (.max(2048)) and demotes the env var to a warned override, those notes now contradict the code. Align them. Docs only; no functional change.
The 2048 row cap lived twice — in the arena sizing (buffers/sizes.rs) and in the consumer (qsa_select.rs), with a comment warning they must agree. Hoist it to pub const QSA_SELECT_SCRATCH_ROWS in spark-runtime next to the arena sizing and reference it from both sites. Value unchanged. cargo check --workspace clean.
…tive rows The batched highway decode inferred padding from the state contents (ple: None -> skip), which silently drops the n-gram injection for any LIVE row whose state arrived carry-less through a different construction path. Thread active_seqs from the schedulers (decode_a2: n, decode_b: n_decode, verify_fused: m) through the decode_multi_seq trait down to the PLE loop: padding rows [active_seqs..num_seqs) still skip cheaply; an active row without its carry now fails loudly, naming the row. Adds a negative test driving decode_multi_seq_inner_hc on MockGpuBackend. cargo check --workspace clean; spark-model tests pass.
The indented QD/resolve table in the fault_threads doc comment is an indented code block, so cargo test --doc tries to build it as Rust and fails (expected one of `!` or `::`, found `resolve`). Fence it as ```text. cargo test -p spark-storage --doc now passes.
|
Thanks for the contribution. Before we can merge, please sign our Contributor License Agreement by replying to this comment with:
I have read the CLA Document and I hereby sign the CLA 0 out of 2 committers have signed the CLA. |
|
|
recheck |
|
I have read the CLA Document and I hereby sign the CLA |
Mechanical rustfmt over the five files cargo fmt --check flags on this branch (four pre-date this PR; ngram_cache.rs picked up its violation in the doctest-fence commit here). No semantic change; drop freely if it conflicts with local work.
|
CI triage on the three red gates:
Local verification after the fmt commit: |
Three real splits and one policy-compliant allow-list entry: - hyper_connection_lowrank.rs (509) -> 476: gemm_raw + hc_finish_block move to hyper_connection_lowrank_gemm.rs - qwen4exp_oracle_tests.rs (503) -> 493: backend() harness moves to qwen4exp_oracle_common.rs - ngram_cache.rs (614) -> 491: the fault-queue machinery (fault_threads, Fault, ArenaPtrs, RowSource, fetch_row) moves to ngram_cache_fault.rs - qwen3_ssm/trait_layer.rs (670): allow-listed with rationale — it is the single impl TransformerLayer block whose bodies already live in trait_* siblings; one trait impl cannot span files. Tracking: Atlas-Inf#18 cargo fmt --check clean; cargo check --workspace clean; spark-model + spark-storage: 766 tests, 0 failed.
Current unsloth uploads of the Qwen3.6/3.8 checkpoints spell the gate "swish" (x * sigmoid(x) — the same function). The strict match turned a fresh download of the same weights into a model-build failure while an older download served fine. Accept it alongside "silu".
|
Per your two asks — both verified at this PR's head on our GB10: KL drift: unchanged — 0.6218 nats, exactly your baseline. Accuracy subsets: passing with margin. Full gate records for all ten required benches are committed at this head (
Fresh-box notes that cost us a night, in case they're worth a line in CONTRIBUTING: the recipe index has no headless bootstrap (TUI-only); BFCL's scorer venv needs That's the key features in — ready for a look. |
The 500-LoC split moved gemm_raw into hyper_connection_lowrank_gemm.rs but left its doc comment and #[allow(clippy::too_many_arguments)] behind, orphaned above hc_pre_split — a duplicated attribute plus an empty line after an outer attribute, both denied under clippy::all. The decoration now lives on the function it describes. Verified: cargo clippy --workspace --tests exits 0; cargo fmt --check clean.
ba1f6a1 to
8be2587
Compare
Four gate records rode along in a8ce22c; this PR carries code only — gate records are the base branch's concern.
The Windows release legs (windows-x86_64-nvidia-cuda, windows-x86_64-amd-hip)
failed on this branch: RefStore::raw pulled in std::os::unix::fs::FileExt for
a positional read, which does not exist on x86_64-pc-windows-msvc (E0433 +
E0599). ngram_table.rs already carries a cfg(unix)/cfg(windows) read_exact_at
pair for exactly this reason, so widen it to pub(crate) and call it from the
reference store instead of re-spelling the unix-only form.
Verified with the cross-target check the CI leg effectively runs
(ATLAS_SKIP_BUILD=1 cargo check -p {atlas-core,spark-model,spark-storage,
spark-runtime,atlas-kernels} --target x86_64-pc-windows-msvc) plus clippy,
fmt, and the atlas-core unit tests on the host.
Measured on a DGX Spark GB10 at the PR head (61f6976, which is what CI diffs against: the base feat/qwen4exp-serve is an ancestor, so the merge tree is this tree). One record per required gate, each run with the parameters the gate definition prescribes and --pull-request-gate: agentic-webserver, vision-fidelity, video-fidelity, ttft-warm-gate, ttft-cold-gate, bfcl-subset, bfcl-subset-echolp, ssm-state-poisoning-gate, decode-floor, concurrency-sweep `spark benchmark --pull-request-gate-check` at this tree: 10/10 PASS. No baseline files were changed.
On top of #16
b16bfb775b48904af58ad96d08b01aaafault_threadstiming table (fix 4)0b5f044bcargo fmt— clears the fmt gatea8ce22cctrait_layer.rsallow-listed, see #18)e38c4692output_gate_type=swishas the SiLU alias (fresh unsloth configs)8be2587fgemm_rawwith its doc +too_many_argumentsallow — clears clippy64f842e961f69768windows-x86_64-*release legs (std::os::unix::fs::FileExt→ the existing cfg'dngram_table::read_exact_at)62dacc1961f69768— all ten required gates PASS on gb10 (spark benchmark --pull-request-gate-check= 10/10 at this head, and at a simulated merge with currentmain)Gate numbers at
61f69768(DGX Spark GB10, RadixArk NVFP4): decode-floor 22.7 tok/s · concurrency-sweep c16 90.7 tok/s aggregate · ttft warm 919 ms / cold 991 ms (median) · bfcl-subset 86.53 / 83.38 · bfcl-subset-echolp 87.95 / 88.00 · ssm-state-poisoning 12/12 · vision 13 probes+integrity · video 13 legs · agentic-webserver ok. KL drift vs the CPU reference: 0.6218 nats, matching the #16 baseline exactly.Original description (the four fixes)
Four small fixes from an independent GB10 validation run of this PR, each a separate commit so any can be dropped:
serve_qwen4exp_tui.shstill describe the pre-merge behavior (ATLAS_PLE_MAX_TOKENSdefaults to 2048; >8K needs it raised). Sinceqwen4_exp.rsderives the floor fromconfig.max_batch_tokensand demotes the env var to a warned override, the notes now contradict the code. Docs only.buffers/sizes.rsandqsa_select.rswith a comment warning they must agree; hoisted topub const QSA_SELECT_SCRATCH_ROWSin spark-runtime, referenced from both sites. Value unchanged.ple: None→ skip), which would silently drop the n-gram injection for a live row whose state arrived carry-less via a different construction path.active_seqsis now threaded from the schedulers (decode_a2: n,decode_b: n_decode,verify_fused: m) down to the PLE loop: padding rows still skip cheaply, an active carry-less row fails loudly naming the row. Includes a negative test onMockGpuBackend.fault_threadstiming table — the indented QD/resolve table is compiled as a Rust doctest and failscargo test --doc -p spark-storage; fenced astext.Validation (third independent GB10, sm_121 / CUDA 13.0, RadixArk NVFP4)
Ran your quickstart before and after these commits:
cargo check --workspacecargo test -p spark-modelcargo test --doc -p spark-storageTwo environment notes from the run, in case they're worth a line in CONTRIBUTING:
cargo build --release -p spark-serverlinks-lnccl, which a bare GB10 doesn't ship; the quickstart's--no-default-features --features cudapath avoids it.instruction_format/irrelevanceoccasionally flaky in CI-style gating; best-of-2 on the format-sensitive probes would keep the temp-1.0 philosophy and the signal.🤖 Generated with Claude Code