Repository navigation
Conversation
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]>
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]>
|
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. |
`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]>
The constants were already pinned to the checkpoint, but the id ARITHMETIC was not checked against anything external -- it was written by reading HF's algorithm, so a transcription error in the XOR mix or the shift semantics would have been invisible to every test Atlas writes about itself. bench/ngram_embed/qwen4exp_xcheck.py runs the real Qwen4ExpTextNGramEmbedding.forward and diffs the row ids it would gather with against a new `qwen4exp_ngram_ids` example. Over 32 streams -- the EOS edge cases plus 25 seeded random ones -- 5408/5408 ids match. It needs no GPU and no weights. The embedding tensor is 320_001_536 x 160 (~51 GB), so nn.Embedding is stubbed during construction; every buffer that actually feeds the ids is built by the real __init__ and left alone. The cargo invocation falls back to `--features metal` so it runs without a CUDA toolchain. Also records what the smallest published repack tells us about placement. RadixArk/Qwen3.8-Flash-Next-NVFP4 excludes `*.ple.*` from quantization, so the n-gram tower ships FP8 in its own model-plefp8-* shards -- ~52 GB of the 135.3 GB total, already separated. Host-resident gather would leave ~83 GB on device, which fits a GB10; the full 135.3 GB does not. That makes offload the thing that decides whether the model runs, not a later optimisation. Co-Authored-By: Claude Opus 5 <[email protected]>
Updated — the id core is now cross-checked against HF, and the config parsesThree things landed since this opened. 1. The ids are diffed against HuggingFace's own moduleThe constants were already pinned to the checkpoint, but the id arithmetic was not checked against anything external — I wrote it by reading HF's algorithm, so a transcription error in the XOR mix or the shift semantics would have been invisible to every test Atlas writes about itself.
EOS edge cases plus 25 seeded random streams. No GPU, no weights — the embedding tensor is 2.
|
| block | precision | size | placement |
|---|---|---|---|
| routed experts | NVFP4 | ~60 GB | device |
| PLE / n-gram table | FP8 | ~52 GB | host |
| backbone, vision, MTP, norms | BF16 | ~23 GB | device |
~83 GB device-resident fits a GB10's ~119 GB. The full 135.3 GB does not. So host-resident embedding gather is not a later optimisation — it is what decides whether this model runs at all.
Still config-layer only: there is no qwen4_exp weight loader, and docs/porting/QWEN4_EXP.md remains the gap list.
The smallest published Qwen3.8-Flash-Next repack is 135.3 GB (RadixArk NVFP4). A GB10 has ~119 GB of memory and, on the box we have, 72 GB of free disk -- so the checkpoint fits neither, and a weight loader cannot be developed against something nobody can hold. scripts/dev/make_tiny_qwen4_exp.py emits one that is 8.7 MB and 2.17M params but structurally faithful where it counts: every tensor name at the same nesting, the 4-stride hybrid schedule, PLE on a linear-attention layer at a one-indexed id, the n-gram head geometry with real prime table sizes and cumulative offsets padded to make_ngram_vocab_size_divisible_by, and `mrope_section * 2 == head_dim * partial_rotary_factor`. `norm_topk_prob` and `seed` are omitted exactly as the published config omits them, so a loader that mishandles those defaults fails here too. Dimensions and values are not faithful -- this checks plumbing, not numerics. Both parsers accept it. HF's own Qwen4ExpTextConfig validates it, its derived ngram buffers match the ones the generator wrote, and the cross-check now runs against either config: 6128 ids on the real geometry and 2944 on the tiny one (N=3 K=4 base=1024, 8 heads x 16), all matching. Agreeing at one set of dimensions can hide an index bug that only bites at another, which is the whole reason for the second geometry. Running it at the tiny dimensions turned up a real contract boundary. The multipliers are bounded by (2^63-1)/vocab_size, so `validate` can only promise `token * multiplier` stays in range for in-vocab tokens; a larger id wraps, and wraps differently in u64 here than in the reference's i64. That is now stated on `ngram_ids` rather than implied, and the harness builds its streams from the config under test instead of hardcoding ids from the big model. Co-Authored-By: Claude Opus 5 <[email protected]>
…etic, and an order Records why the real checkpoint is not an option on the GB10 we have -- 135.3 GB against 119 GB of memory and ~72 GB of free disk, and ~95 GB even after deleting everything of ours -- and that host-resident PLE fixes the memory side but not the disk side. Serving it there needs more disk, a different box, or a repack that does not exist. Also writes down the order the remaining work wants to go in, with host-resident gather pulled early because it decides whether the thing runs at all rather than how fast. Co-Authored-By: Claude Opus 5 <[email protected]>
I set `attn_gated = false` on the reasoning that the full-attention layers carry plain q/k/v/o plus q_norm and k_norm. The checkpoint says otherwise, and it is the only place that does: `q_proj` is [12288, 2560], while 24 heads x head_dim 256 is 6144. The projection is 2x wide. The reference builds it as `num_attention_heads * head_dim * 2` and splits per head -- `chunk(view(..., -1, head_dim * 2), 2, dim=-1)` -- which is exactly the interleaved Q+gate layout `attn_gated` denotes. `o_proj` is [2560, 6144], confirming the gate is consumed inside attention rather than projected out. Left wrong, this halves the Q the model actually attends with: the loader would read the gate half as query values. Nothing would fail. This is a separate gate from `output_gate_type = "sigmoid"`, which belongs to the linear-attention pathway and has its own tensor (`linear_attn.in_proj_z`). Conflating the two is what produced the wrong call. The test now pins both widths against the checkpoint's actual q_proj rows and o_proj columns, so the next config that disagrees fails here rather than at inference. Found by reading real tensor shapes out of the safetensors headers over HTTP range requests -- no download. Co-Authored-By: Claude Opus 5 <[email protected]>
…ckpoint
A loader's first job is knowing which tensors to ask for and how wide they are.
Writing that down separately buys two things the loader alone does not: it can
be checked against a published checkpoint's index WITHOUT downloading 135 GB of
weights, and a shape that disagrees fails there rather than at inference.
`atlas_core::weight_manifest::qwen4_exp_manifest` enumerates every language-model
and MTP tensor from the config. Against Qwen3.8-Flash-Next-FP8's
model.safetensors.index.json -- 152,089 tensors, of which 333 are model.visual.*
and 75,264 are FP8 weight_scale_inv siblings -- it covers the remaining 76,492
with ZERO missing and ZERO unexpected, every scale attaches to a routed-expert
weight it expects, and 1,653 shapes read out of real safetensors headers over
HTTP range requests all match.
It earned its keep on first run, catching three wrong widths in the tiny
development checkpoint -- each one the kind that loads real numbers from the
wrong place and fails nothing:
* hyper-connections operate on hc_count * hidden (10240), not hidden. The
residual really is four streams concatenated.
* q_proj is 2x q_dim for the interleaved gate.
* the indexer's index_qk_proj is (n_heads + kv_heads) * head_dim -- it fuses
the query and key projections.
The config gained the fields those shapes need: hc_count / hc_lowrank and the
indexer_* group. They are deliberately NOT the existing hc_mult / index_* fields,
which describe DeepSeek-V4's Sinkhorn mHC and CSA -- related concepts whose
mapping onto this model is unestablished, and sharing them would route one
model's weights through the other's mixing.
Vision is out of scope and quantization awareness is future work; both are
stated rather than implied, and the verifier checks the scale invariant instead.
Co-Authored-By: Claude Opus 5 <[email protected]>
Weight manifest — and it caught a bug in what I'd already pushedThe bug firstI had committed The reference builds it as Left wrong, a loader reads the gate half as query values and halves the model's effective attention. Nothing fails. I'd conflated it with The manifest
Zero bytes of weights downloaded — tensor names come from the index, shapes from safetensors headers fetched with HTTP range requests. It earned its keep on the first run, catching three wrong widths in the tiny development checkpoint, each the kind that loads real numbers from the wrong place and fails nothing:
New config surface
Scope, stated rather than impliedVision is out of the manifest (independent tower, separate config block). It is not quantization-aware — it describes logical weights, and the verifier checks the invariant that every Verified134 tests + clippy green both on macOS ( |
The manifest described logical weights and left the FP8 scales to an invariant
check. It now derives them, so manifest + siblings is 151,756 tensors -- the
entire published Qwen3.8-Flash-Next-FP8 checkpoint except its 333 vision
tensors -- with ZERO missing and ZERO unexpected, and 3,189 shapes matching
headers read over HTTP range requests.
`modules_to_not_convert` was going unparsed. That is HF's spelling of the
ignore list for native FP8 block-quant, and this checkpoint ships 943 LITERAL
entries (no globs). Read as "nothing is excluded", a loader would expect a scale
sibling beside every norm and embedding. `weight_block_size` is parsed now as
well: [128, 128] means the sibling is [ceil(rows/128), ceil(cols/128)], verified
against a real expert down_proj -- [2560, 640] -> [20, 5].
Two rules are not guessable from the names, and both are pinned by tests:
* Only 2-D linear weights take a block scale. Norms, biases, integer buffers
and 3-D conv kernels do not, and none of them are in the ignore list
either -- so the rank check cannot be delegated to that list.
* A group carrying its own `weight_scale` is quantized PER TENSOR and takes
no `weight_scale_inv`. The 128 n-gram shards are exactly this: FP8 behind
one shared BF16 scale, and absent from `modules_to_not_convert` because
they ARE converted, just by another scheme. Treating them as block-scaled
over-generates by exactly 128, which is how it was found. The rule keys off
the manifest rather than off the name, so any future per-tensor group is
handled without another special case.
ModelOpt NVFP4 -- what the RadixArk repack uses -- has a different sibling set
(weight_scale, weight_scale_2, input_scale) and returns None rather than a wrong
guess.
Co-Authored-By: Claude Opus 5 <[email protected]>
…atch exactly
The manifest covered the FP8 release. It now covers RadixArk's NVFP4 repack as
well, and both are exact against their published indexes:
Qwen/...-FP8 151,756 tensors (ex-vision) 0 discrepancies
RadixArk/...-NVFP4 296,142 tensors (ex-vision) 0 discrepancies
NVFP4 does more than add siblings -- it REPACKS the weight. A [2560, 640]
projection is stored U8 [2560, 320], two FP4 values per byte, alongside
weight_scale [2560, 40] (one per group of 16 along the input dim) and scalar
weight_scale_2 / input_scale. A caller that only appended siblings would still
expect the wrong shape for the weight itself, so `quantized_manifest` returns
the adjusted list rather than an addendum.
Three things the tensor names do not reveal, each found by the diff going
nonzero:
* ModelOpt's ignore list is globbed (`*.self_attn.*`, `mtp.*`) and `*` has to
span dots, or `*.self_attn.*` never matches a real module path. HF's native
FP8 list has no globs at all. Both forms are matched now.
* `group_size` lives at config_groups.*.weights.group_size for
compressed-tensors, not at the top level.
* Expert layout is a packaging choice, not an architectural one. HF's native
Qwen4ExpTextExperts stores gate_up_proj as one
[experts, 2*moe_intermediate, hidden] tensor and chunks it at use; ModelOpt
works per nn.Linear, so quantizing splits the stack. The FP8 release is
split throughout; RadixArk is split for the quantized routed experts and
STACKED for the MTP block, which it excludes from quantization entirely.
`Qwen4ExpLayout` expresses both, and the verifier tries both rather than
making the caller know which a checkpoint used.
That last one is why RadixArk sat at 1,538 discrepancies after the scales were
right: 1,536 per-expert MTP tensors we expected and it had fused, plus the 2
fused tensors we did not know to ask for.
Co-Authored-By: Claude Opus 5 <[email protected]>
…e split I wrote that host-resident PLE would leave ~83 GB "on device, which fits". That is wrong on this hardware, and it pointed the plan at the wrong first feature. The GB10 is fully coherent unified memory: `nvidia-smi -q` reports `Addressing Mode: ATS` and `memory.total [N/A]` because there is no separate GPU pool. MemTotal is 125,418,660 kB (~119.6 GiB), and that one pool is what both the CPU and the GPU allocate from -- a process showing 100 GB of "Used GPU Memory" is holding 100 GB of the RAM the OS sees. Moving a tensor "to host" frees nothing. What works is demand paging, not residency. The n-gram table is a pure row gather -- one token touches at most 16 rows of 160 bytes, ~2.5 KB -- so the model-plefp8-* shards should be mmap'd and left to the page cache. That leaves ~83 GB resident, ~52 GB on disk, and ~36 GB for KV cache and activations, which is a workable budget on one box. So the first loader feature is mmap-backed n-gram gather, not offload. Full residency of 135.3 GB is not reachable on a 119 GB box by any placement strategy. Co-Authored-By: Claude Opus 5 <[email protected]>
The manifest could only be checked from Python. This is the same check as something a loader can actually call: read every shard header, diff against the manifest, refuse by name before loading a byte. That ordering is the point. A checkpoint missing a tensor, or carrying one at the wrong shape, should be caught here rather than halfway through a 135 GB load -- or not caught at all, because a wrong-but-plausible shape reads real numbers from the wrong place and fails nothing. Header parsing goes through crate::safetensors::tensor_span, so a crafted or truncated file is refused on the same terms as the loading path rather than on looser ones, and the header length prefix is bounded before it becomes an allocation. Expert layout is tried both ways and the closer fit reported, since it is a packaging choice: both published releases split their trunk experts and differ only on the MTP block, which a quantizer leaves alone when it excludes `mtp.*`. Callers should not have to know which a checkpoint used. Verified against the tiny checkpoint's real files: 0 missing, 0 unexpected, 0 mismatched. Co-Authored-By: Claude Opus 5 <[email protected]>
Found by running the preflight against 296,142 real tensors -- the first check of this manifest against actual weight files rather than an index. Exactly one discrepancy, and it was ours: mtp.pre_fc_norm_hidden.weight: manifest [2560] vs checkpoint [10240] 10240 is hc_count * hidden. The MTP's two inputs are not the same width and nothing but the checkpoint says so: `pre_fc_norm_embedding` normalises a plain token embedding, while `pre_fc_norm_hidden` normalises the trunk's hyper-connection state, which is four streams wide. Both published releases agree, so this was wrong for the FP8 one too -- the index-only check could not see it, having no shapes. The tiny development checkpoint had inherited the same mistake and is fixed with it. That is the fourth width the manifest has caught in that generator, which is the argument for having it. Co-Authored-By: Claude Opus 5 <[email protected]>
…heckpoint 296,142 tensors, 0 missing, 0 unexpected, 0 mismatched, in 2.81 s and 372 MB RSS. Headers only, so it is cheap enough to run at load time rather than as a dev-only script, and it auto-detected both the stacked-MTP layout and the NVFP4 config from the checkpoint itself. Co-Authored-By: Claude Opus 5 <[email protected]>
Verified against the real 126 GiB checkpoint — and a correctionRadixArk's NVFP4 repack is downloaded ( 296,142 tensors, names and shapes. 2.81 s because it reads headers rather than weights — cheap enough for a loader to run at startup instead of as a dev script, which is why it moved from Python into What the real weights caughtExactly one discrepancy, and it was mine:
Correction: a GB10 has no host/device splitI said earlier in this PR and in the porting doc that host-resident PLE would leave "~83 GB on device, which fits". That is wrong on this hardware, and it pointed the plan at the wrong first feature.
What works is demand paging, not residency. The n-gram table is a pure row gather — one token touches at most 16 rows of 160 bytes, ~2.5 KB — so the
So the first loader feature is mmap-backed n-gram gather, not offload. Full residency of 135.3 GB is not reachable on a 119 GB box by any placement strategy. Also worth knowing for laterRadixArk excludes 138 tests, clippy clean, on macOS and the GB10. |
The n-gram table is 51.2 BILLION parameters -- 320_001_536 x 160 -- larger than the rest of the model put together, and ~52 GB even at FP8. On a GB10 there is nowhere to put it: the box is coherent unified memory (Addressing Mode: ATS, ~119.6 GiB total), so CPU and GPU draw on one pool and "moving it to host" frees nothing. It does not need holding. The table is a pure row gather -- one token touches K*(N-1) rows, 16 on the published model, of 160 bytes each, about 2.5 KB -- so NgramTable reads rows on demand and lets the kernel's page cache keep the hot set. pread rather than mmap, deliberately. Both go through the page cache so the caching is identical, but a page fault inside a CUDA-adjacent thread stalls it invisibly, and a truncated or concurrently-modified file becomes SIGBUS under mmap versus an ordinary io::Error under pread. Opening validates that the shards actually tile the table: split_ngram_parts of them, contiguous, summing to the padded total the config implies, all one dtype, each span matching rows x row_bytes. A checkpoint that disagrees is refused rather than serving rows from the wrong place. Element width is read from the checkpoint rather than assumed, so the F32 tiny checkpoint and the F8_E4M3 published ones both work. Also adds locate_checkpoint, which keeps the validated byte spans the preflight was discarding -- that is what makes row-level reads possible at all. Co-Authored-By: Claude Opus 5 <[email protected]>
… GB table The open question behind the whole memory plan was whether reading the n-gram table on demand is fast enough to sit under decode, given it cannot be held on a GB10. Measured against the real table on the Spark: table : 320,001,536 rows x 160 B (51.2 GB), opened in 443 ms cold : 820 us/token (16 rows, every one off NVMe) -> 1,219 tok/s ceiling warm : 8.85 us/token (page-cached) -> 112,994 tok/s ceiling Even fully cold that is an order of magnitude above the decode rate this class of model runs at -- under a tenth of a decode step at ~100 tok/s, in the worst case where no row is resident. Warm it is negligible. Resident memory did not move during the run; buff/cache held at 13 GB. So the plan holds: ~83 GB resident weights, the 52 GB table read on demand, ~36 GB left for KV cache and activations, on a 119.6 GiB box. Co-Authored-By: Claude Opus 5 <[email protected]>
9347184 to
a8060c3
Compare
`qwen4_exp` was rejected by name in `loader_for_config`. Atlas now recognises
it, loads every tensor the forward pass will need, and fails with a message that
says WHAT is missing instead of "unsupported model type".
Qwen4ExpWeights loads the trunk hyper-connection mixer, and per layer: both
hyper-connection blocks, the mixer (gated-Q full attention with its fused
indexer, or the gated-delta-net linear attention), the router, the shared expert
and gate, and the PLE projections where `ple_layer_ids` puts them -- one-indexed,
so layer i hosts the tower iff i+1 is listed. `dense_auto` already handles the
FP8 block-scaled dequant this checkpoint needs.
Two things the trait forced into the open, both worth recording:
* There is NO separate final norm. The published checkpoints carry no
`model.language_model.norm.weight` at all; the trunk's
`hyper_connection_mixer.hc_norm` is what normalises the residual before the
LM head, and it is hc_count * hidden wide because the residual is that many
streams concatenated.
* load_mtp_weights returns None. The checkpoint does ship an MTP block, but
its shape is not the MtpWeights any existing family uses -- own 512-expert
stack, own indexer, own hyper-connections, and two input norms of DIFFERENT
widths. None means `--speculative` is refused at preflight rather than
half-wired.
The n-gram table is deliberately not loaded here: 51.2 B parameters read by row
at use time through atlas_core::ngram_table::NgramTable.
load_layers still bails. The layers it would return do not exist yet -- low-rank
hyper-connections, the PLE tower and the sparse-attention indexer are new work,
and the linear-attention and 512-expert MoE paths need adapting. Compiles clean
on the GB10 under the real cuda feature set.
Co-Authored-By: Claude Opus 5 <[email protected]>
a8060c3 to
9f1208e
Compare
Without a MODEL.toml, `spark serve` cannot resolve kernels for this checkpoint and the loader can never be exercised end to end -- it fails before reading a tensor. This makes the target resolvable. Records the architecture from the checkpoint rather than from the paper: gated Q (q_proj is 2x q_dim), hc_count 4 with a low-rank sigmoid mixer rather than DeepSeek-V4's Sinkhorn mHC, the indexer on full-attention layers only, and ple_layer_ids as the ONE-indexed value it really is. Also writes down why 180B is the wrong way to read this model: 51.2 B of the 179.6 B total is the PLE n-gram table, which is a lookup rather than a matmul and is never resident. Active is ~2.4 B of experts plus the backbone. And why NVFP4 is not merely the smaller choice but the only workable one -- the FP8 release's experts alone are 123.3 GB resident against a 119.6 GiB box. kernel_source reuses qwen3-next-80b-a3b: nearest relative by a distance, same 48-layer 12/36 hybrid schedule, same 512-expert top-10 MoE, same head_dim and partial rotary. It is UNVERIFIED and said so in the file -- it buys resolvability, not correctness, and nothing here has run a forward pass. thinking_default is false, deliberately: a first bring-up should not spend its token budget inside a reasoning block, which is exactly the trap Nemotron-3.5-Lightning walked into earlier today. Co-Authored-By: Claude Opus 5 <[email protected]>
The first end-to-end load of Qwen3.8-Flash-Next got as far as: Selected kernel target: (sm_121, qwen3.8-flash-next, nvfp4) (167 modules) Model config: 48 layers, 12 attention, 36 SSM, 512 experts Quantization config: method="modelopt", algo="NVFP4" Fast-load pre-flight: 125.87 GB on-disk, 1.3x = 163.64 GB peak, 114.26 GB free OOM pre-flight: peak 163.64 GB + 4.00 GB reserve exceeds 114.26 GB free The loader was trying to make the n-gram table resident. It must never be: it is 51.2 B parameters, 41% of the checkpoint, and it is GATHERED BY ROW -- one token touches about 2.5 KB of it. Reading it from disk was already built and measured (820 us/token fully cold, 8.85 us warm, against the real 51.2 GB table); nothing had told the weight loader to leave it alone. `demand_paged_patterns` does. Tensors matching are excluded from the load AND from the pre-flight estimate -- the estimate matters as much as the load, since counting bytes that will never be allocated refuses models that in fact fit. That takes this checkpoint from 163 GB to roughly 96 GB against 114 GB free. The predicate sits ahead of the expert-parallel check rather than inside it, because it applies on a single rank, where that check returns early. The server derives it from `ple_layer_ids` rather than from `model_type`: it is the presence of the tower that decides this, not the family name. A pattern listed here MUST have a reader that goes to disk -- atlas_core::ngram_table is the one that does. Nothing enforces that from the loader; a name listed without a reader is simply absent from the store, and the model loader fails on it by name. Co-Authored-By: Claude Opus 5 <[email protected]>
First end-to-end run of the real checkpoint through spark serve on a GB10: kernel target resolves, NVFP4 is detected, and all 296,347 weight tensors load in 69 s at ~88 GB peak with ~26 GB spare. The demand-paged exclusion is the whole difference. With the n-gram shards counted, pre-flight is 163.64 GB and refuses on a 114.25 GB budget. Without them it is 78.19 GB on disk, 101.65 GB peak, and loads with headroom. Every tensor Qwen4ExpWeights asks for is present and correct on the published checkpoint -- 48 layers, 1 PLE tower -- so the load path is done. It stops exactly where it should: the forward pass, which is now the only thing left. Co-Authored-By: Claude Opus 5 <[email protected]>
… weights `gather_dequant` turns gathered rows into the PLE tower's actual input: the per-head slices of one token's embedding, concatenated in head order and scaled. FP8 E4M3 via the crate's LUT, with BF16 and F32 paths so the tiny development checkpoint works too. The scale is a single scalar, not a per-block tensor -- the table is quantized PER TENSOR, which is why its 128 shards share one BF16 `weight_scale` and carry no `weight_scale_inv`. scripts/dev/check_ngram_rows.py verifies it against the checkpoint independently: it parses the safetensors headers itself and does its own FP8 decode, so a mistake in Atlas's shard arithmetic or its LUT cannot cancel out. Rows are chosen to straddle shard boundaries, which is where offset arithmetic goes wrong. Co-Authored-By: Claude Opus 5 <[email protected]>
The PLE tower is the most novel of the three layers this model needs and the
easiest to get plausibly wrong, so it now has a CPU reference checked against
HuggingFace's own Qwen4ExpTextPLELayer at real weights: worst relative error
5.079e-7 across three sequence lengths, which is f32 rounding.
Four steps in it do not do what their names suggest:
* the RMSNorm is GROUPED -- each of hc_count streams normalises over its own
hidden_size slice, not the whole 10240-wide row;
* its weight is an OFFSET FROM 1 (`x * (1 + w)`), so a checkpoint of zeros is
the identity and a checkpoint of ones doubles;
* the gate takes a SIGNED SQUARE ROOT, floored: sign(g) * sqrt(max(|g|,1e-6));
* the depthwise conv is DILATED by ngram_size, so its state is
(kernel-1)*ngram_size = 9 wide, not kernel-1 = 3.
Getting the match also turned up a real bug in the tiny development checkpoint:
it wrote `layer_multipliers` as ZEROS. Loading it overwrites the values the
reference derives in __init__, every mixed id collapses to 0, and every token
hashes to its head's first row -- the model still runs, still produces fluent
shapes, and is quietly reading one embedding for every input. It is now derived
with the same SplitMix64 draw, and the divergence is what exposed it.
This is a correctness reference, not the serving path. The GPU implementation
gets checked against it.
Co-Authored-By: Claude Opus 5 <[email protected]>
…1.6e-7
Second of the three unbuilt layers to get a numerical oracle. Checked against
HF's own Qwen4ExpTextGatedResidual at real weights, over all three variants the
model uses -- the per-layer attention and MLP blocks, and the trunk mixer that
has no injection: worst relative error 1.559e-7.
Three steps that are not what the shapes suggest:
* the mixing gate divides by hc_count BEFORE its activation, and does it
twice -- once into the low-rank SiLU, again into the injection sigmoid;
* the block output is a MEAN across streams, so a hc_count * hidden input
comes back hidden wide. Reading it as a sum is a 4x error that looks like
a temperature change rather than a bug;
* injection weights are 2 * sigmoid(...), centred on 1 rather than 0.5 --
the fixture's mean is 0.995, which is what "no injection yet" looks like.
Renames ple_reference to qwen4exp_reference now that it covers more than the
PLE tower.
Co-Authored-By: Claude Opus 5 <[email protected]>
`cargo clippy --all-targets` fails on `too_many_arguments (8/7)`. Rather than widen the threshold, drop the two parameters that were never free: `key_dim` is `k.len()` and `value_dim` is `v.len()`, and every call site was already passing exactly that. This is the stricter version, not merely the shorter one. Taking both as parameters gave a caller a way to disagree with its own slices, and the only assert that would have caught it (`state.len() == key_dim*value_dim`) passes for any consistent-but-wrong pair. Now q/k agreement is asserted too. This lint was reachable only after the E0063 fixture break was fixed at 1a75969 -- clippy stopped at the first compilation failure, so --all-targets had not actually linted atlas-core since.
`cargo clippy --all-targets` fails on three examples this branch does not touch -- they are byte-identical to origin/main: dense_gemv_bf16_batchm_microtest.rs:124 uninlined literal in println! w8a16_gemv_numeric.rs:255 k % 16 != 0 w4a16_gemv_sw_microtest.rs:74 k % GROUP_SIZE == 0 `manual_is_multiple_of` and the empty-format-string lint both arrived with the pinned 1.93.1 clippy, so they fire on main too. They were invisible until now only because clippy stops at the first compilation failure, and the E0063 fixture break (fixed at 1a75969) came first. Fixing them here so that `--all-targets` is actually green on this branch and a reviewer can reach this PR's code. They belong on main independently and this commit is safe to drop in a rebase.
Positional args were taken with a bare `args.next()`, so the flag itself became the fixture path and the run died opening a file named "--generate". Only the `<ckpt> <fixture.json> --generate N` form worked, which is not the form anyone reaches for first. Found while writing the invocation into a review reply -- worth noting that the bug was invisible from the inside, because every run I had made passed a fixture.
|
Thank you — this is the most useful report the branch has had, and it found more than the two items it lists. Everything below is at Build health: all three fixed, plus three your run made reachable
The second one matters more than it looks, because fixing it unblocked clippy, and clippy immediately found a kernel that had never compiled.
nvcc rejects the file outright. The incremental build never re-entered it, so Two more became reachable only once clippy could run at all — it stops at the first compilation failure, so
Current state on a GB10, CUDA 13, rustc 1.93.1: Your three review questions1.
|
| FP8 bytes | total | fraction | verdict | |
|---|---|---|---|---|
| with the demand-paged skip (what the loader sees) | 7.03 GiB | 78.19 GiB | 9.0% | false |
| whole checkpoint, no skip | 54.72 GiB | 125.87 GiB | 43.5% | still false |
Every resident FP8 byte is a weight_scale tensor — NVFP4 block scales, which is precisely the case the function's doc comment describes ("NVFP4 models have a few FP8 scale tensors but the bulk is uint8"). This is an NVFP4 checkpoint that contains FP8 scales, not an FP8 checkpoint. So 1.3× is the intended multiplier rather than a lucky one, and your measured 90.38 GB peak against the 101.65 GB projection is the estimate being conservative rather than the detector being wrong.
Worth stating plainly: had this been a genuine FP8 checkpoint with a demand-paged table, the skip could flip a true verdict to false. It does not here, but that is a property of this checkpoint, not a guarantee from the code.
2. KV settings — you are right, and the recipe was wrong. Now bf16.
Only 12 of 48 layers carry a KV cache at all (2 KV heads, head_dim 256). At 2048 ctx that is 48 MiB per sequence in bf16 and 24 MiB in fp8 — the entire saving at 8 concurrent sequences is 192 MiB, against ~83 GB of resident weights.
That is a bad trade even before the missing scales, and with them it buys 192 MiB in exchange for clipping BF16 into E4M3's [-448, 448]. Atlas-Inf/sparkrun-recipes@f3ab63f switches kv_cache_dtype to bf16, with that arithmetic recorded inline. Once decode exists this gets revisited with a measurement; until there is something to measure, bf16 is the setting that cannot be wrong.
3. Vision — intentional, and it should have been written down
Text-only. The published index carries 333 vision tensors on top of the 296,142 text ones; they load and are unused, and the target has no vision_encoder module. Now stated in the recipe and in the PR description.
What would be most useful to validate next
Not another load run — you have pinned that leg more precisely than I had.
The highest-value target is the GPU microtest, because it needs no checkpoint and it is where a second machine could actually catch me being wrong:
cargo run --release -p spark-model --example qwen4exp_grouped_norm_microtest \
--no-default-features --features cuda
At 9bf118bed on a GB10 it reports:
grouped: max|diff| 3.909e-3 over 30720 values (up to 1.917e0), relative 2.039e-3
ungrouped control: max|diff| 1.227e0 (must be large)
GROUPED RMS NORM MATCHES THE ORACLE
hyper-connection: mixed max|diff| 2.944e-3 (up to 7.640e-1, relative 3.853e-3)
hyper-connection: injection [0.9766, 0.9961, 1.0469, 1.0078] vs oracle [0.9763, 0.9957, 1.0456, 1.0072]
HYPER-CONNECTION BLOCK MATCHES THE ORACLE
PLE tower: max|diff| 3.443e-3 over 122880 values (up to 6.623e-1), relative 5.199e-3
conv contribution: 5.862e-1 (must be large)
PLE TOWER MATCHES THE ORACLE
GDN decode step: max|diff| 1.401e-5 over 6144 values (up to 4.306e-3), relative 3.254e-3
head-group mapping exercised: true
GDN DECODE STEP MATCHES THE ORACLE
To be exact about coverage: that is four block types, covering all 48 layers' norm/hyper-connection path, the single PLE layer, and the 36 linear-attention layers. The fifth — full attention, 12 layers — now has a kernel that compiles (q4e_attn_decode, above) but is not yet checked against its oracle. That check is the next thing I write.
Each check carries a control that must fail — otherwise a kernel that ignored the property under test would pass silently. The oracles are themselves checked against HuggingFace at real weights, so agreement chains to the reference rather than to another guess. If this agrees on your GB10 as well, that is independent confirmation of the numerical core.
Second, if you still have the checkpoint resident, the CPU reference forward — this is where the token-identity claim lives, and the claim I would most want a second opinion on:
cargo run --release -p atlas-core --example qwen4exp_forward -- <ckpt-dir> --generate 4
One caveat, and thank you for the indirect prompt: that exact invocation was broken until 9bf118be. Positional arguments were taken with a bare args.next(), so --generate itself became the fixture path and the run died opening a file by that name. Every run I had made passed a fixture, so the bug was invisible from the inside. Fixed.
Fair warning on cost: ~33 s/token, ~20.7 GB RSS. It is a correctness oracle, not a serving path.
Still not a deployment
Unchanged, and worth repeating rather than burying: load_layers bails, no GPU forward runs end to end, and there is no serving speed number. The forward gate you hit is the accurate state of the branch. The remaining work is decode sequencing the verified pieces against Atlas's KV paging and buffer arena, plus the 512-expert MoE and gated-Q attention paths.
Completes the fifth and last block type. `q4e_attn_decode` covers the 12
full-attention layers; the other four checks already cover the norm and
hyper-connection path on all 48, the single PLE layer, and the 36
linear-attention layers.
The oracle is `attention_decode_step`, extracted from `attention_forward`
rather than written fresh -- `attention_forward` now calls it, so agreement
chains to the code that matches HuggingFace at 8.0e-7 instead of to a
second transcription of the same equations. A separate oracle would have
been free to be wrong in the same direction as the kernel.
Two controls, both of which a plausible-but-wrong kernel would fail:
* gate contribution -- recompute with every gate forced to +8 (sigmoid
~ 1, effectively ungated) and require the answer to move. A kernel that
ignored the gate entirely would otherwise pass, and this model's whole
distinguishing feature is that gate.
* kv head-group mapping -- 24 query heads share 2 KV heads, so heads
0..11 and 12..23 read different K/V and must disagree. Per-query-head
mapping would collapse that difference.
PAST is 37, deliberately not a multiple of the block width.
Two pieces of model-level plumbing that the layer cannot be built without. `q4e_hc_expand` tiles the embedding across all hc_count residual streams. DeepSeek-V4's `hc_expand` does the same job, but it lives in that model's shadow rather than in common/, so it does not resolve for this target -- the same module-scoping rule that forced the q4e_ prefix in the first place. Verified in the microtest, with a sentinel pre-fill: a kernel that wrote only stream 0 would match on the part it wrote, so the check fails unless every slot is overwritten. `hc_streams` is now sized for qwen4_exp as well. It was gated on `hc_mult > 0`, which is DeepSeek-V4's spelling; qwen4_exp says `hc_count`. Only the stream COUNT is shared -- `hc_post`/`hc_comb` stay V4-only, because the Sinkhorn intermediates have no counterpart here. The element size is per-family and that is not cosmetic. V4 stores f32 deliberately (norm-preserving mixing, bf16 collapses generation at scale). qwen4_exp must be bf16, because `q4e_hc_stream_mix` and `q4e_hc_scatter_add` stride by __nv_bfloat16 -- sizing it f32 would not fail, it would read the wrong half of every value. Whether 48 layers x 2 blocks of bf16 accumulation drifts is UNMEASURED and recorded as such; if it does, the kernels and the sizing move together. Also registers `q4e_attn_decode` in Qwen4ExpKernels.
Three cases, because the failure mode is silent in each direction:
hc_count set -> a real bf16 highway. Before this it fell through the
`hc_mult > 0` gate to the 256-byte placeholder, and the
first write past it would have been another buffer.
hc_mult set -> still f32. Widening qwen4_exp must not narrow V4, whose
norm-preserving mixing needs the range.
neither set -> stays a placeholder, so the common case does not pay for
a hidden-size allocation it never reads.
All five block types are now GPU-verified, and the trunk entry existsFollow-on to the validation reply. At Attention — the fifth and last block type
The oracle is Two controls, both of which a plausible-but-wrong kernel would fail:
The trunk entry, and the wide residual it writes intoTwo pieces of model-level plumbing the layer cannot be built without.
The element size is per-family, and that part is not cosmetic:
Sizing the qwen4_exp arm f32 would not have failed — it would have read the wrong half of every value. Three tests pin all three cases (each family, and neither-set staying a placeholder). Open and recorded as such: qwen4_exp's mixer is contractive (it divides by Still not a deploymentUnchanged. What is left is integration rather than unknowns: |
The 512-expert MoE is reuse, not adaptation — and it now loadsThe porting doc listed this as "adapt Qwen3.5's path". It needs no adaptation.
and the target checkpoint's trunk experts are Worth being precise about what changed: the routed expert bodies were not previously loaded at all. Verified against the real 126 GB checkpoint, not just the compilerthen the expected gate:
Two caveats I am not glossing
Still not a deployment
|
Each hyper-connection kernel is already checked alone. This checks them
COMPOSED, in the order Qwen4ExpLayer::decode will run them -- collapse,
block, scatter -- because the errors that survive per-kernel checks live
BETWEEN the kernels:
* a scatter that accumulates onto the NORMALISED copy rather than the raw
residual (both are `wide` and both are in scratch),
* an injection indexed per-hidden instead of per-stream,
* a collapse whose scratch aliases the residual it is still reading.
None of those change either kernel's own output, and all three still
produce text.
The block is a fixed vector rather than a real mixer: what is under test is
the plumbing, and a known block output makes the expected residual
computable in closed form.
The control is that the four streams must have DIVERGED. Each receives the
same block output scaled by its own gain, so a single shared gain -- or a
mis-indexed injection -- makes the per-stream deltas coincide. The
injection weights carry the 1/sqrt(wide) scale for the same reason the
standalone check does: a saturated gain agrees regardless of sign, which
would make the control vacuous.
The composed check agreed with the oracle at 4.5e-3 and then failed its own control: the per-stream spread was 3.4e-2, only 5x the error rather than the 10x demanded. That was the test, not the kernel. I had copied the standalone check's 0.5/sqrt(wide) injection scale, which exists to keep the sigmoid off saturation -- but at that scale every gain sits at 2*sigmoid(0) = 1.0, so all four streams receive near-identical updates and the control cannot tell a correct per-stream scatter from one that broadcast a single gain. The anti-saturation fix had quietly created the opposite degeneracy. 5/sqrt(wide) lands the gains around 0.85..1.15, off both rails. The new assertion pins that range directly instead of trusting the constant -- otherwise a future change to the RNG or the norm weights could re-degenerate the gains and the spread check would pass vacuously rather than fail.
`Qwen4ExpLayer` plus the sandwich that is the whole layer's structure -- collapse the residual, run a block on the `hidden`-wide result, scatter that output back per stream. It happens twice per layer: once around the mixer, once around the MoE. The shape worth writing down: this layer does NOT touch the `hidden` pointer the trait hands it. The trunk state is the hc_count-stream residual in `ctx.buffers.hc_streams()`, `hc_count * hidden` wide for the whole depth. `hidden` is `hidden_size`, so writing the residual through it would overrun by 4x on the published config. DeepSeek-V4's mHC layers take the same shape for the same reason. `mlp_block` is complete and is built only from checked pieces -- the sandwich against the oracle (`hc_sandwich_roundtrip`), and `MoeLayer::forward` as the shared 512-expert path. It is identical on all 48 layers. HcScratch is allocated per layer rather than borrowed from the arena deliberately: `norm_output` is `hidden`-wide and every buffer here except `mixed` is `hc_count * hidden`. Borrowing the narrower one would overrun it without failing. The mixer half (gated-delta-net on 36 layers, gated-Q attention on 12) and the PLE tower are not wired yet, so `load_layers` still bails -- nothing half-built can run.
|
Confirmed micro test on a second GB10: AGREE — every reported metric is digit-for-digit identical to the author’s GB10 run. cargo run --release -p spark-model --example qwen4exp_grouped_norm_microtest SHA: 9bf118b
A few execution notes:
From this independent GB10 run, the grouped RMS norm, hyper-connection block, PLE tower, and GDN decode path all reproduce the oracle, while the negative/control cases behave as expected. |
|
Confirmed on GB10 at 9bf118b. I ran the requested end-to-end forward test twice against the real RadixArk/Qwen3.8-Flash-Next-NVFP4 checkpoint: cargo run --release -p atlas-core --example qwen4exp_forward -- --generate 4 Environment:
Both runs exited 0 and produced the exact same generated sequence: step 0/4 -> 5013 The second run reproduced the first token-for-token. This is a plumbing/integration validation rather than a generation-quality result, since the example uses arbitrary seed IDs. What it confirms is that the full 48-layer forward path now executes end-to-end against the real NVFP4 checkpoint on GB10 without crash, panic, NaN, or Inf. That includes the integrated grouped RMS norm, hyper-connections, PLE tower, sparse-attention indexer, 512-expert MoE routing, and GDN decode paths. This also confirms the --generate N argument parsing works at this SHA. One reproducible issue: --generate 4 executes steps 0..=4 and appends 5 tokens, not 4. Both runs show the same off-by-one behavior. Verdict: PASS — end-to-end forward path works and reproduces deterministically on GB10. |
|
Additional, unrequested text-generation sanity check at 9bf118b. This was not part of the requested validation, but I wanted to confirm that the real checkpoint could also produce sensible text rather than only exercise the forward plumbing. Experiment: qwen4exp_forward, raw prompt, greedy argmax Prompt: The capital of France is Tokenized prompt: [760, 6511, 314, 9338, 369] Generated tokens: [11751, 13, 11751, 369, 264, 3177, 13, 14833, 11] Decoded continuation: " Paris. Paris is a city. Therefore," So the first generated token is the expected answer: Paris. This is only a sanity check, not a quality benchmark: it uses a raw prompt, greedy decoding, no chat template, and no stop condition. Still, it confirms that the real NVFP4 weights produce a coherent and factually correct natural-language continuation through the implemented forward path. It also independently reproduces the generation-count issue noted above: --generate 8 executes 9 generation steps and appends 9 tokens. No changes were made to the worktree. |
PLE parity, same construction as the mHC gate: the whole kernel chain
(`ple_gate` -> `ple_conv` -> `ple_add_highway`) against
`qwen4exp_reference::ple_forward`, with no checkpoint and no Python.
#753 called the PLE tower the port's top correctness risk, and the three
details that make it one all leave a finite, plausible gate when dropped:
the offset-from-1 norms (the checkpoint's `ple.norm_key` centres at -0.1067,
so the fixture centres there too — zero-centred weights would let a kernel
that dropped the offset look close), the GROUPED norm at group_size = hidden,
and the gate's signed square root.
Compared against the oracle's own COMPOSITE `ple_forward` rather than a
formula re-derived in the test: a second transcription is free to be wrong in
the same direction as the kernel. The two host-side projections use the
oracle's own `linear`, for the same reason.
Two controls, because the checks above would otherwise pass on a kernel that
ignored the conv entirely:
conv≠0 the gated value alone — what the output would be with every
tap zero — must miss by 20x the tolerance
dilation=1 re-runs the same conv undilated. The conv is dilated by
ngram_size, so its state is (4-1)*3 = 9 steps, not 3; a kernel
silently treating dilation as 1 reads t-3..t instead of
t-9,t-6,t-3,t and the parity check alone would not notice
`ple_embed_dim` is 512 here rather than the checkpoint's 2560: it enters only
the two host-side projections, so shrinking it avoids a 105 MB host matmul
without changing any kernel path. Noted in place.
The oracle projects in FP32 while the kernel reads BF16 key/value (which is
what `ple.cu` deliberately keeps in BF16 — they are read once and not
cancelled against anything). That is ~0.4% relative on one input to a
2560-term dot product, inside a tolerance set at 5% of the reference's RMS,
and it errs in the honest direction: the kernel is held to the sharper number.
ALSO: `--generate N` in `qwen4exp_forward` appended N+1 tokens, because the
loop was `0..=generate`. Reproduced twice on a GB10 during independent
validation of #13 (`--generate 4` -> 5 ids, `--generate 8` -> 9). Now exactly
N, with `--generate 0` keeping its own meaning — one pass, print the
per-position argmax, diff the fixture, append nothing.
AND: documented why the demand-paged skip rule must NOT become what withholds
the n-gram table. The shard loop checks `is_ngram_table` first and takes those
tensors down the DEFERRED path, which records each one's file and offset —
which is what `NgramRowCache` reads rows through. A plain skip records
nothing, so if that predicate stopped matching the PLE shards, the general
rule would quietly take over and the PLE loader would fail its own
"no shard was deferred" check at load.
Local gate 5/5. Both oracle tests are `#[ignore]` and have not run — no GPU.
…nforces `.github/workflows/file-size-cap.yml` caps every `.rs` under `crates/` at 500 lines, with an allow-list that requires a rationale and a tracking issue. It runs on `pull_request`, and FOUR files on this branch already breached it before today's work — so #13 is currently red on a gate nobody ran locally, because the reviewer checked fmt, clippy and tests, and this is a separate job: qwen4exp_grouped_norm_microtest.rs 1093 qwen4exp_reference.rs 783 weight_manifest/qwen4_exp.rs 698 config/ngram_qwen4exp.rs 532 Plus two this stack pushed over: `qwen3_ssm/init.rs` (504, from carrying both sides' kernel-name helpers after the merge) and `examples/qwen4exp_forward.rs` (505, from a comment I added). None is allow-listed and none needed to be. Split along the seams the code already has: * `qwen4exp_reference.rs` -> one file PER BLOCK (`qwen4exp_reference/{ple,hc,moe,attn,gdn}.rs`), which is also how the port is verified — one oracle per block, each checked against HuggingFace at real weights — so a reader looking for the PLE tower opens `ple.rs` instead of scrolling past the MoE. Re-exported flat, so every existing caller path (`atlas_core::qwen4exp_reference::ple_forward`) still resolves. * the microtest example -> one file per block check under `examples/qwen4exp_microtest/`, sharing the device helpers through `use super::*` so the harness cannot drift between them. * `ngram_qwen4exp.rs` and `weight_manifest/qwen4_exp.rs` -> tests to a sibling `*_tests.rs`, the pattern used everywhere else in this tree. * `qwen3_ssm/init.rs` -> the two config-driven kernel-NAME helpers (`gated_norm_kernel`, `hc_kernel`) move to `kernel_select.rs`, which is already the "which kernel do we resolve" module. 504 -> 471. * `qwen4exp_forward.rs` -> the new comment tightened. 505 -> 500. Nothing else moved: these are pure relocations, and the 158 atlas-core tests still pass after each one. The gate script now also runs the three CI jobs that need no toolchain — `check_spdx.py`, `check_kernel_shadows.py`, and the LoC cap itself — because all three are greps, and finding out from a red PR is a wasted round trip. Local gate: 13/13 PASS. 2,823 tests execute here (158 atlas-core + 2306 spark-server + 87 spark-storage + 272 spark-runtime).
CI caught a real breakage that predates today's work and that no local gate on this branch could see. `atlas-kernels/tests/kernel_shadow_detector.rs` asserts that no model shadow drops a kernel its `common/` namesake declares — the invariant that stops a tuned shadow from silently removing a kernel some dispatch path resolves. #13 added four kernels to `common/rms_norm.cu` (`rms_norm_grouped` plus the three sigmoid gated-norm twins), and ten targets carry their own `rms_norm.cu`, so all ten now "dropped" all four: 40 shadowing file(s) drop a kernel their common/ namesake declares `[shadow_exempt]` in `kernels/gb10/common/KERNEL.toml` is the mechanism, and the entry directly above ours is the same argument for the same file: the HF-vanilla norm pair, added to common for Laguna-S, resolved only behind a predicate no shadowing model satisfies. These four are qwen4_exp-only — `rms_norm_grouped` normalises the `hc_count` streams independently inside one `hc_count * hidden` vector, which no other family has, and the twins are selected from `output_gate_type == "sigmoid"`, a field only this checkpoint sets. qwen3.8-flash-next does not shadow `rms_norm.cu`, so it always gets them; none of the ten that do is a qwen4_exp model. The comment records WHY they live in common/ rather than in this target's shadow, because that was a deliberate call: #754 shipped a per-target `gated_norm_sigmoid.cu` whose own header warned a fix to the SiLU originals "should be re-derived here". One copy means the twins and their originals cannot drift. Two safety nets are unchanged, and the comment says so: `gated_norm_kernel` calls `gpu.kernel(...)` rather than `try_kernel`, so a target that forks rms_norm.cu and needs them still hard-errors by name at the fail-closed startup audit; and `check_qwen4exp_kernel_names.py` independently asserts all four resolve for THIS target. Exempting "a shadow may omit" is not the same as "nobody needs them", and both directions are now checked. WHY THE LOCAL GATE MISSED IT: it ran `--lib` for every crate, and these invariants live in `atlas-kernels`' TEST TARGETS — pure CPU, they parse the .cu files and KERNEL.tomls. That row is now in the gate (and takes no feature flags: atlas-kernels has no `cuda` feature, the backend is a build.rs concern there). 17/17 gates pass.
…eck it locally With `aux.rs` renamed, the Windows release leg got past checkout and reached the compiler, where it failed on OUR file — `atlas-core/src/ngram_table.rs`, the PLE row reader from #13: error[E0433]: failed to resolve: could not find `unix` in `os` error[E0599]: no method named `read_exact_at` found for struct `File` `std::os::unix::fs::FileExt::read_exact_at` was imported unconditionally. The positional read is the load-bearing part — reading at an absolute offset without moving the file cursor is what lets the PLE gather run without a mutex around the file — so the Windows arm has to preserve that, not just compile. `seek_read` is the Windows equivalent (`OVERLAPPED` underneath, also leaves the cursor alone), but it is a SHORT read like `read`, so it needs the loop that `read_exact_at` gives for free. Both arms behind one private helper, with the difference documented at the definition. VERIFIED LOCALLY, not guessed: `rustup target add x86_64-pc-windows-msvc` makes this checkable from a mac, and all three crates the port lives in now cross-compile clean — cargo check -p atlas-core -p spark-storage -p spark-runtime -p spark-model \ --lib --target x86_64-pc-windows-msvc --features cuda -> clean That is a gate row now, skipped with a message when the target std is absent. `spark-server` is excluded because `ring`'s build script needs a Windows C toolchain to cross-compile and macOS has none — a limitation of the check, not a gap in the code. WHY THIS KEPT SLIPPING THROUGH: a missing `cfg(unix)` is invisible on both platforms anyone develops on here, and the Windows matrix leg is the only thing that builds it. Two Windows defects in two rounds — one a filename, one an API — so the gate now covers both classes. Also updated the gate's closing note: the kernels ARE compiled by the PR's `nvcc -> PTX (all gb10 targets)` job, which passed, so that line no longer belongs under "only a GB10 can close it". 19/19 gates pass.
Folded into #16 — closing to leave one PR for this work#16 now targets Two PRs for one deliverable was confusing, and that was my doing — I based @maplepaladin73 — your five reports on this PR were the most useful signal it had, and they are not being discarded: this thread stays readable, and the work they drove is in #16. Your independent confirmations here (the micro tests on a second GB10, the AGREE on every reported trap, the text-generation sanity check at Everything from here on is in #16. |
… record removed by 7e6455a (#663) #663 removed AzeezIsh from three governance files. Restore each to its exact pre-#663 content (none has changed since): - .github/CODEOWNERS: @AzeezIsh back on all 18 rules - .github/workflows/cla.yml: AzeezIsh back in CLA_ALLOWLIST - signatures/version1/cla.json: the AzeezIsh signature record (signed 2026-05-06, PR #13) back in signedContributors Every other entry, including @tbraun96 in all three, is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Config-layer groundwork for
qwen4_exp— Qwen3.8-Flash-Next — plus a correction to how the existing n-gram work was described.The correction
The n-gram commits already on this branch were described in the CHANGELOG as groundwork for "the LongCat / Qwen3.8-Flash-Next family". Read against the published
Qwen/Qwen3.8-Flash-Next-FP8weights, that grouping does not hold. Qwen3.8-Flash-Next uses a different algorithm, not a different parameterisation.The two agree on the shape and nothing else — same
K*(N-1)heads of widthembed_dim/(K*(N-1)), same document-boundary resets, so both decode from the lastN-1tokens:ngram.rs)qwen4_exp(new)Σ shift_d · (V^d mod T)shift_d · m_dratio·V + 2i + 1(odd)0eos_token_idA LongCat id handed to a
qwen4_exptable reads an unrelated row — a real embedding from the wrong place. So they are separate types, and a test asserts they do not coincide on the same tokens.The config surface could not express this model either:
ngram_vocab_size_ratiois a multiplier onvocab_size, and Qwen's base is 20,000,000 against a vocab of 248,320 — not an integer ratio.What this adds
Qwen4ExpNgram— the id core and table geometry, derived fromconfig.jsonalone.Pinned against the checkpoint itself rather than a reference we also wrote, which 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. Reproduced bit-exact from config:
layer_multipliers→[23703573157769, 20109073645365, 8052911324071]ngram_heads_vocab_sizes→ the 16 consecutive primes above 20,000,000ngram_heads_offsets→ their running sum[2_500_012, 160] × 128Two traps are encoded as tests rather than comments, both of the kind that silently load a real tensor from the wrong place:
ple_layer_idsis ONE-indexed. The config says[2]; the weights live atlayers.1.ple.*.seedis ABSENT from thatconfig.json, so it must default to 1234. A zero default draws different multipliers and hashes every token to an unrelated row, without failing.shift_right_ignore_eosgains afillparameter rather than a second copy — the segmentation is the one thing the two families genuinely share, and two walks would drift apart.Scope: what this does and does not do
Superseded note (this section originally said
qwen4_expwas in neitherparse_confignor
loader_for_config, and that the target was the 185.5 GB FP8 release).Both statements are now stale; the current state is below.)
Atlas now recognises
qwen4_exp, loads every weight of the NVFP4 repack, andresolves kernels for
(sm_121, qwen3.8-flash-next, nvfp4). It does not serve:load_layersbails at an explicit unsupported-forward gate, and there is noserving speed number. A CPU reference forward produces coherent, token-identical
output from the real weights at ~33 s/token — correctness evidence, not a
serving path.
The checkpoint is
RadixArk/Qwen3.8-Flash-Next-NVFP4, not the FP8 release.The FP8 release does not fit: its routed experts alone are 123.3 GB resident
against a GB10's ~119.6 GiB. The repack quantizes only the experts and lands at
~83 GB resident.
The 51.2 B-parameter n-gram table is never resident. It is 41% of the
checkpoint. Making it resident puts the pre-flight at 163.64 GB; it is read by
row from NVMe instead (
demand_paged_patterns, derived fromple_layer_ids).Note this is not an offload in the llama.cpp sense — a GB10 is coherent unified
memory (
Addressing Mode: ATS) and there is no second pool to move anything to.This port is text-only. The published index carries 333 vision tensors on top
of the 296,142 text ones. They load and are unused; the kernel target has no
vision_encodermodule and Atlas warns at startup. A caller sending images willnot get what it expects.
MTP is not implemented. Its shape is not the
MtpWeightsany other familyuses (its own 512-expert stack, its own indexer, two input norms of different
widths).
load_mtp_weightsreturnsNoneand--speculativeis refused atpre-flight rather than half-wired.
Remaining forward work:
decodesequencing the verified pieces against Atlas'sKV paging and buffer arena, the 512-expert MoE path, and gated-Q attention.
docs/porting/QWEN4_EXP.mdis the running gap list.Verification
On a GB10 (CUDA 13, rustc 1.93.1), at HEAD:
Numerical agreement with HuggingFace at real weights, per block: hyper-connections
1.6e-7, gated delta net 3.2e-7, MoE 3.4e-7, PLE tower 5.1e-7, attention 8.0e-7.
A full forward on a reduced checkpoint is token-identical to HF (max|diff| 7.45e-7).
Four block types are additionally verified on GPU against those oracles, each with
a control that must fail:
cargo run --release -p spark-model --example qwen4exp_grouped_norm_microtest.Full attention (12 layers) has a compiling kernel (
q4e_attn_decode) that is notyet checked against its oracle.
Provenance
Derived independently from the Apache-2.0 reference in
huggingface/transformers(src/transformers/models/qwen4_exp/). No upstream file is vendored and the Rust is not a transliteration, but the constants, the mixing order and the prime-selection rule are the reference's, and the attribution travels with them — indocs/porting/QWEN4_EXP.md, mirroring howbench/ngram_embed/LICENSEcarries Meituan's MIT notice for the LongCat derivation.