Skip to content

DeepSeek-V4.1 EXL3 Metal: faster sparse-attention prompt scan, bit-identical - #3735

Closed
BlivionIaG wants to merge 183 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-exl3-sparse-scan-nax
Closed

BlivionIaG wants to merge 183 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-exl3-sparse-scan-nax

Conversation

@BlivionIaG

@BlivionIaG BlivionIaG commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #3382 (see Stack). One behavior: a faster sparse-attention prompt scan kernel (csa2_nax.metal), bit-identical output. Two commits in that one kernel, plus a device test.

What and why

  • reuse the key fragments as the value fragments: a value fragment is the same dense row and dims as a key fragment, so the PV pass reads the registers the QK pass loaded instead of gathering the rows a second time.
  • reciprocal-corrected epilogue, offset-only key validity, per-block query fragments: the 64 per-lane divisions become the reciprocal product plus one fma-corrected residual; key validity comes from the staged offset alone; the query fragments reload from memory per block, freeing registers in the score phase of a register-limited kernel.

Kernel level

An M5 Ultra, GPU timestamps, median of 7, base kernel and this branch's kernel on the same seeded inputs in a standalone harness (not part of the PR):

shape base first commit both commits
4,096 rows at position 12,288 (16k keys) 9.85 ms 8.80 ms (-10.6%) 7.17 ms (-27.2%)
8,192 rows at position 24,576 (32k keys) 19.77 ms 17.60 ms (-10.9%) 14.32 ms (-27.6%)
7,838 rows at position 0 18.42 ms 16.55 ms (-11.2%) 13.21 ms (-28.3%)
4,096 rows, ratio 2 9.77 ms 8.78 ms (-10.2%) 7.14 ms (-26.9%)
4,096 rows, top-k 64 3.62 ms 3.38 ms (-6.6%) 2.42 ms (-33.1%)

The gain is on the tensor-unit path. Compiled for the pre-M5 simdgroup-matrix path (TF_SIMD_FRAGS, what an M4 Pro runs) the kernel is bit-identical as well but no faster: +0.5% to +0.8% on an M4 Pro at the first three shapes above, and within 0.4% of base on an M5 compiling that variant.

Exactness

  • Output bit-identical to the base kernel at 17 sparse-scan shapes in the standalone harness, comparing the whole output buffer after prefilling it with a sentinel: 4,096 rows at 12,288; 8,192 at 24,576; 7,838 at position 0; 4,096 at position 0; one row at position 0 and at 12,288; ratio 2 at 4,096 rows, one row, and position 0; top-k 64 (4,096 rows, and 2,048 rows at ratio 2); tail chunks of 37, 4,097 and 8,191 rows; 33 rows at position 100; 640 rows at position 0 (fewer keys than top-k); and 300 rows at position 127 (the ring window's edge). The same 17 are bit-identical on the pre-M5 variant, on both an M4 Pro and an M5. An earlier version of this text cited six shapes; that count came from a scratch harness whose log no longer exists, so it was replaced by this one.
  • The epilogue's range guard was stressed in a second set of 162 cases (128 rows at position 2,048), each compared against the base kernel's plain division: value magnitudes from 2^-140 (denormal) to 2^120 in steps, every exponent from -80 to -50 and 50 to 80, with random signs and (from 2^-64 to 2^-56 and 2^56 to 2^64) all negative; all-zero values; one zero dimension; mixed exponents from -80 to 80; a third of the values denormal; one +Inf, one NaN, one 2^70, one 2^-70 row; sinks from -80 to 90 on flat and random scores, including the denominators around 2^20 (sink 13.80 to 13.90, where one step crosses the bound); one head's sink at 60; alternating sinks of -80 and 60; and a saturated softmax. Every case is bit-identical. A counter build shows where the guard fires: no simdgroup falls back at in-range inputs (0 of 2,048 at exponent 0, 10, 40 and 59 with random signs), almost all do just under 2^-60 (2,032 at 2^-61, 1,916 at 2^-60) and all do at 2^60, 2^61 and with zero values, and only the simdgroups that see the value when it is a single one (one +Inf: 80, one NaN: 504, one 2^70: 20, one zero dimension: 512 of 2,048). At the 17 real shapes 0 to 5 simdgroups of 65,536 to 131,072 fall back (the first rows of a prompt, with one or two keys). On the pre-M5 variant the same 162 cases and 24 packed-key ones (186) are bit-identical on an M4 Pro and on an M5.
  • The guard is load-bearing, and the stress set detects its absence: a control build with the fallback removed (always the corrected quotient) differs from the base kernel in 28 of the 162 cases: the 17 tiny or denormal ones (exponent -140 to -120: the corrected quotient's zero has the wrong sign), the 9 all-negative ones from 2^56 to 2^64 (NaN), and the 2 with sink 90 (the denominator overflows to Inf). A denominator under 2^-10 could not be constructed with any valid key (the running maximum contributes 1), so only the upper bound and the accumulator span were exercised at their edges.
  • The reciprocal-corrected quotient was re-checked against hardware division: all 2^23 x 2^23 = 2^46 mantissa pairs (0 mismatches, 372 s), 1.1e11 (111,669,149,696) random mantissa pairs against an integer-exact round-to-nearest-even quotient (0 mismatches), and the same count of random-exponent pairs inside the guard range, numerators of 2^-60 to 2^60 with random signs and denominators of 2^-10 to 2^20 (0 mismatches).
  • In the repo: the existing test-deepseek-v41 tensor-unit tests compare this kernel with the scalar kernel (random packed keys: 262,144 of 262,144 bit-exact, as on the base), and a new case in csa2_test.zig does the same with the window and chunk keys' scales biased by 2^+80 and 2^-80 (accumulators past 2^60 and under 2^-60): 262,144 of 262,144 bit-exact in both. That case does not tell the fallback from the corrected quotient (the control build above also passes it); the harness set above does. tf-kernel-contract --only dsv41-native-attention, which checks the native rows kernel against this one (24 shapes bit-equal per configuration): 8 kernels pass gates 1-4, 34 controls red as planted, 0 limit problems, the same on the base and on this head.

Greedy token SHAs are equal to base end to end (next section).

End to end

An M5 Ultra, decoded locally (no remote prefill), cold TTFT on fresh salted prompts, 8,192-row chunks, 3 boots per binary with base and this PR alternating (order reversed on even rounds); base is the #3382 head. Median, range in brackets:

prompt base this PR change
7,838 tokens 4.529 s (4.508-4.555) 4.435 s (4.418-4.443) -0.094 s (-2.1%)
16,095 tokens 7.753 s (7.716-7.790) 7.558 s (7.519-7.599) -0.195 s (-2.5%)
31,947 tokens 14.105 s (13.708-14.368) 13.688 s (13.663-13.696) -0.417 s (-3.0%)

The ranges do not overlap at 7.8k and 16k; at 32k the base's boot-to-boot spread (0.66 s) is larger than the gain's lower end (the same prompts unsalted give 13.982 s on the base and 13.615 s here, -0.367 s, with ranges 13.930-13.997 and 13.608-13.657). The size is consistent with the kernel table (5.4 ms a layer on an 8,192-row chunk at 32k keys): a 2-3% TTFT gain.

Greedy output is identical: SHA of the first 8 generated tokens equal for base and this PR on every request: the 7,838-, 16,095- and 31,947-token prompts (three salts each and the unsalted prompt), and 256 tokens on the 16k prompt (1952b3cf4812) as well. The known values on the unsalted prompts, d921f2f71999, 3839d0a1f03f and 79b4c5041836 at 8 tokens, are reproduced.

Not run

Whole-model qualification beyond the above; any device other than the M5 Ultra for the kernel and end-to-end numbers (the pre-M5 variant ran on an M4 Pro and on an M5 for bit-identity only); the opt-in TF_ATTENTION_PV_FP32 variant; a CI device run.

Stack

Stacked on #3382 (head 5d1f3d6): the EXL3 Metal lane these files belong to is not on main yet, so the diff against main shows #3382 until it lands. Review only the top commit(s): git diff 5d1f3d6418..HEAD. The three sparse-scan PRs (indexer select, sparse nax, indexer row scorer) are independent of each other on that parent and touch different behavior; each applies alone. Happy to restack or rebase however you prefer, or to hold them until #3382 lands.

No overlap with #3351, #3668 or #3669: none of them touches these files, and a trial merge of each with this branch reports no conflict in them.

Checks (head c2136ddd96)

  • zig fmt --check clean; python3 tools/pr_check.py --base 5d1f3d6418 --pr 3735: 0 errors, 0 warnings, lean 396 vs 396.
  • zig build test-native -Dfixed-cpu exit 0; zig build test-dsv41-device-host -Dfixed-cpu exit 0 (the Metal kernels are not run by either).
  • zig build test-deepseek-v41 -Dfixed-cpu (Metal device tests, including this PR's new test): 70 passed, 4 skipped on an M4 Pro; 74 of 74 on an M5 Ultra. The new test skips cleanly without a device.
  • tf-kernel-contract: see Exactness (partial cover through the rows-kernel probe).
  • Not run: test-dsv41-cuda-host, test-lane-api-host, test-dsv41-draft and a CI device run (nothing here touches those paths).

…kernels, streamed Engram, drafted decode, retained prompt cache
The glm_dsa exes take the tokenizer module from the engines import table
(the file was compiled twice, once per module). The reference suite calls
encodeDiagnostic with prof and segs. The four prof clocks guard Windows,
where std.c.clock_gettime does not compile; those builds read 0 from an
instrument that never runs there.
bench/ (the round scripts and the two patch diffs), tf_ids_tmp and its
tf-ids target, and the r519 bf16 experiment with its fixture leave the
diff. The repo-wide *.log ignore line goes (upstream keeps its own).
glue_tmp.metal was load-bearing, so it is glue_rows.metal now, with the
records file, the contract tests and every comment following. No kernel
text changed.
Dead code under the copy rule: no lane file dispatches tf_gather_qmm_*; zig/tests/mlx_gather.zig and the tf-mlx-gather entry existed only to time the reference. Removes core/mlx/ (mlx_steel.h + gather.metal), the core_mlx_steel embed, the test and its build entry. Gates: fmt, native, test-deepseek-v41, dev-tools.
…switches

The diff adds comment blocks that carry experiment labels and measured numbers; this pass keeps the technical statements and drops the history. Core is family-neutral again: the round-trip profiler and its clock leave lanes/engine.zig, the resumed-tail switch moves to prompt_cache.Rules (set by the DSV4.1 lane host), and the family metal-mirror shell check hangs off test-deepseek-v41 instead of zig build native. Gates: zig fmt --check, native, test-deepseek-v41, dev-tools.
Every file in the branch is under 600 lines: lanes/engine (pipelined round), core/prompt_cache (marks), server/cli (scalar helpers), weights (source helpers, int8 sidecar), backend (policy, run), and the index Metal sources (scalar + tensor-unit). Moves are function-for-function, with in-struct aliases for the methods; no arithmetic moved. Gates: zig fmt --check, test-native, test-deepseek-v41, dev-tools.
…he release

R1's first half. TF_DSV41_Q_RMS, TF_DSV41_MTP_Q_RMS and TF_DSV41_Q_RMS_DEBUG and their ones/dump buffers are gone; the release has no per-head query RMS (it normalizes qr before wq_b, which is the shipped path). The provenance comments in model.zig/attention.zig now state the release's order (wq_a -> q_norm -> wq_b -> rope; wkv -> kv_norm -> rope; sparse attention; inverse rope; wo_a groups -> wo_b) and the DSpark block forms, with no sibling-engine citations. No default-path arithmetic moved: every removed arm defaulted off. Gates: zig fmt --check, native, test-deepseek-v41, dev-tools.
…ement

The top-1/KL receipt the review asks for needs a divergence term over the whole next-token
distribution, not only argmax and NRMS. `qualify.zig` already runs the independent CPU teacher
(FP32 or FP64 over the release pack's weights) against the GPU decode; this adds KL(teacher ||
engine) per row, its mean and worst, in f64 with a max-subtracted softmax. The fields are added
with defaults, so existing oracle JSON readers keep working. Gates: zig fmt --check,
test-deepseek-v41-reference.
…MM moves lane-side

core/affine_mm.metal and prefill/gemm_nax.metal are byte-identical to upstream's
(sha a91a3539 / 16a1d78a). The router gate's fp32-destination GEMM is the lane's
own copy under deepseek_v41/gate_gemm.metal, registered in the metal sources and
loaded by ops.zig; the gate bench reads the lane source and the contract records
keep their names.

The unused int8/weighted-GLU affine delta (only a flag-gated FP64 ground-truth
test) is removed with its header and test. It was dead in the lane and carried a
whole-file port attribution, so re-homing it would not clear the copy rule.

Gates: zig fmt --check 0; check_dsv41_metal_mirrors 86/86; zig build native 0;
test-deepseek-v41 0; dev-tools 0.
The drafter's conditioning, noise-token rows and Markov head chain cite the
release's Transformer.forward_spec / DSparkBlock.forward_embed / forward_head
(inference/model.py, revision 314113f8) instead of the sibling engine. The
remaining port language is gone. Comments only: no non-comment line changed.

Gates: zig fmt --check 0; zig build native 0; test-deepseek-v41 0; dev-tools 0.
…y leaves the comments

The EXL3 files no longer name another engine or a round. The funnel/dig forms,
the register-only decode, the pair and the multi-row dense body are described by
their arithmetic and their own shapes; the model-facing order cites the release
(inference/model.py, revision 314113f8). Comments only: no non-comment line
changed.

Gates: zig fmt --check 0; zig build native 0; test-deepseek-v41 0; dev-tools 0.
…ured numbers

The five files the earlier pass skipped (attention, model, the EXL3
projection Zig glue, and both EXL3 Metal files) now carry the same
comment rule as the rest of the diff: no ROUND-/R- labels, no handoff
or other-engine references, no measured figures. Comment text only;
git diff -U0 over the five shows no non-comment line changed, so the
kernels and the host glue are bit-identical by construction.
…duplicated code go

hc_boundary.metal's header no longer claims a whole-file port: it cites
Block.hc_mixes, hc_pre and hc_post in the release's inference/model.py at
revision 314113f8, and the duplicated mix-product and two-stage reduction
code is one pair of helpers. The arithmetic, the thread mapping and the
lagged collapse are unchanged, so the kernels stay bit-identical; the mHC
GPU tests pass.

The remaining comparator/MLX/Bob references in the diff are reworded to
describe the form by its arithmetic or removed. The other files here change
comments and bench output strings only; no engine path changes.
… walk

The prompt tile no longer carries an inline decode job: TfExl3DigJob holds the
resident pack slice, the k/n strides, the width/codebook and the live tile
extents, built once from the call args and the route. TfExl3DigWindows holds
the lane's eight-state cursor (slot, word offset, shift, word distance) and is
shared by the default tensor-unit prefill body, the grouped table body and the
scalar prefill twin (the named TfExl3ScalarWindow fields replace the packed map
word). The arithmetic, the k order and the MMA order are unchanged, so the
kernels are bit-identical by construction; the shared prefill and grouped-tile
GPU tests in test-deepseek-v41 pass, and the prefill spot rows report zero
parity mismatches.

The model-facing order cites the release (inference/model.py, revision
314113f8); the trellis arithmetic and the cursor are our own pack format.

Gates: zig fmt --check 0; zig build native 0; test-deepseek-v41 0;
dev-tools -Doptimize=Debug 0.
…nd row walk

The register-only routed decode and its paired form no longer rebuild the
pack slice and the lane cursor inline. TfExl3DecodeJob names the trellis,
k/n strides, width and codebook for one row (the dense call takes its own
trellis, the routed call the expert's descriptor); TfExl3RowWalk names the
lane's first word, bit offset, shift/mask and the next two words. The pair
body uses the same two structs, so the duplicated setup is one place.

The arithmetic, the k order, the product order and the reduction tree are
unchanged: the shared prefill, grouped-tile and resumable-window GPU tests
in test-deepseek-v41 pass, and the single-row/pair bodies are the same code
with named fields. The release is cited for the MTP/draft projection shapes
(inference/model.py, revision 314113f8); the pack layout and the row walk
are our own.

This is the register-only single-row and pair pass. The funnel, wide and
multi-row dense bodies still carry their inline setup; they are named as
remaining R3 work in the record.

Gates: zig fmt --check 0; zig build native 0; test-deepseek-v41 0;
dev-tools -Doptimize=Debug 0.
…walk

The tensor-unit decode's three remaining bodies no longer rebuild the pack slice and the lane
cursor inline. The multi-row routed decode, the 128-column dense decode and the column walk build
TfExl3DecodeJob (the expert descriptor or the call's own trellis, the k/n strides, width and
codebook); the eight-state cursor is the shared TfExl3DigWindows walk, now with the tile's column
stride and the ring's next words, so the funnel, two-word and general paths take rel/off/sh/at
from it. The single-row and pair register bodies keep TfExl3RowWalk.

The arithmetic, k order, MMA order, product order and reduction tree are unchanged: the walk is
the same map arithmetic with named fields, and the cursor was checked for halves 4, 6, 8 and 16 on
every lane. The file compiles standalone with the default, funnel, two-word, compact and table
defines. The body comments also lose the last task label, the probe measurement and the orphan
possessives the earlier attribution strip left behind.

Gates on the tree: zig fmt --check 0; metal compile 0 (default plus the named defines);
zig build native 0; test-deepseek-v41 0 (the csa2 diagnostic and failed-command line are the same
on the base 1530351); dev-tools 0; test-exl3 0.
The copy-rule comment pass left orphan possessives ("are 's"), a task label and a
measurement in the rewrite-set files. This restores the sentences: the EXL3 glue
describes the single-tile body, the backend notes drop their round numbers and the
one measurement, and the docs drop the round cross-references. Comment and prose
only; no non-comment line changed in the Zig sources.
…h order is kept and proved byte-identical

The file started from BobClawblaw/TensorFold deepseek-v41-main 72a552e. It is now written from the release's Block.hc_mixes, hc_split_sinkhorn_kernel, hc_pre and hc_post (inference/model.py and inference/kernel.py at 314113f8): the mix projection over the flattened stream, the Sinkhorn split, the lagged collapse, the norm and the post expansion.

The two launches and the reduction order are unchanged by design. The split cannot read the 24 mix totals until the first launch finishes and Metal has no grid-wide barrier; the one-threadgroup fold was built and measured 2.4x slower at the decode's row counts. The reduction order is the canon's.

A byte-for-byte A/B against the previous kernel over rows 1, 2, 5 and 17 and every expand/mixes combination (16 cases) is identical in every output buffer, so no reply can move. The harness and its log are in the plan record, scratch/hc-ab-20261106/. Metal compile and the fast gates pass.
The attention encode is now the release's decomposition (inference/model.py,
revision 314113f8): the query's low-rank pair and its norm, _window_kv's norm,
rope and fp8 pack, _compress_kv/_compress_topk_idxs' compressor and pick,
sparse_attn over the two sources, and the grouped wo_a/wo_b close. The stage
context carries the views the stages hand forward, so each stage reads as the
release's step instead of one inline block.

The dispatch order, the fused forms' arithmetic, the k order, the split counts
and every A/B arm are unchanged: the bodies moved, they were not retyped. The
trellis arithmetic, the ring layout and the scan remain this lane's pack
format.

Gates: fmt 0; metal-mirrors 86/86; native 0; test-deepseek-v41 0; test-exl3 0;
dev-tools 0; umbrella test 0 (COMBINE GATE 45056/0); reference 0.
…stages

The drafter's block attention is now the release's DSparkAttention.forward
(inference/model.py, revision 314113f8): the draft query's low-rank pair and
norm, the draft key's norm and rope, the packed window, the scan over the main
model's window rows, and the grouped wo_a/wo_b close, with the draft rows'
publish last. The stage context carries the encoder and the views the stages
hand forward, so each stage reads as the release's step.

The dispatch order, every rope/scale/mask arm, the debug dumps and the prof
splits are unchanged; the bodies moved, they were not retyped. The pack
arithmetic, the ring layout and the scan remain this lane's pack format.

Gates: fmt 0; metal-mirrors 86/86; native 0; test-deepseek-v41 0; test-exl3 0;
dev-tools 0; umbrella test 0; reference 0.
…+up call

A five-token window's fused gate+up call names seventy descriptors (two blocks of the backbone's six
picks plus the merged shared expert's two, a token), and the register-only bodies stopped at
`moe_split_rows`, which is the split reduction's bound: the window's later rows changed to the
tensor-unit compact body inside one window. A body is a rounding order, so those rows no longer
carried the one-row bits and a four-draft window decoded differently from plain decode.

The bodies now serve any call up to 112 descriptors, the eight-token window's fused count, so a decode
window and a prompt chunk of the same token count run the body a one-row decode runs. One- to
three-draft windows name fifty-six descriptors and below and keep their bodies; the only other calls
past sixty-four descriptors are prompt chunks of five to seven tokens, which now match a one-token
decode of the same rows.

The host test pins the arithmetic: the fused call is fourteen descriptors a token, five tokens pass the
split reduction's bound, and eight tokens stay inside the body's bound.
Measured on the eight reference prompts, solo and four-at-once, and on the ten code prompts: the
four-draft window's hashes now equal plain decode's (7 of 8 and 5 of 10 differed before), the 5-row
round's event p50 is 61.2 ms, and the default config's hashes and timings are unchanged.
The multi-row dense bodies switch at two rows and at four; a GPU test compares each window's rows against one-row dispatches of the same matrix for both codebooks, so a body that is not row-invariant fails here instead of in a reply.
…its merge

Concurrent dispatch mode put the attention scan ahead of the dense-table
pass that fills it and the split merge ahead of the scan that writes its
partials: TF_DSV41_CONCURRENT=1 moved the reply. Both dependencies now
have an explicit barrier, and a GPU test runs the chain on a concurrent
encoder against the serial one.
@BlivionIaG
BlivionIaG marked this pull request as ready for review November 24, 2026 10:43
@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @BlivionIaG. The parent refresh is present, and your scan kernel and test match the latest reported revision. Current main adds only a changelog conflict.

One guard is needed: dsv41_frag_get4 now loads bfloat4, but the host still accepts BF16 query strides such as8193, which leave later rows misaligned for that load. Please preserve scalar fragment loads for supported unaligned views or handle the alignment before selecting the vector path.

The new range fixture also allows unequal outputs and, as you noted, passes without the fallback. Please add an exact comparison with the original division using cases where removing that fallback fails. The posted stress results are useful; the committed check should protect that behavior too.

  • Synthena

The resolution had dropped the engine's import and pointed hy4_flash's
config at the file instead, which failed the hy4 flash host test: its
config reached the readers by path while the engine declared them as a
module. Keep main's side byte for byte.
The readers live in config_number.zig, which the metal graphs declare as
a module for hy4_flash's config. The family's config still reached the
file by path, so a graph with both owned it twice. Import it by name and
declare the module on the roots that compile the family's config
themselves.
…lings

The core modules re-exported the file while main's inkling2 opener
imports it directly, so a graph with both owned it twice. Read it by path
from the family and drop the two re-exports.
@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Refreshed on main and on the updated #3382 head (bab2613de8), which also fixes the hy4_flash build failure the previous head had in CI; merge-tree clean, this PR's code unchanged.

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thank you @BlivionIaG. As you decided on #3734, this stack is being rebuilt on TensorFold's own EXL3 code, one exact behaviour at a time, starting with #5050, #5054 and #5063. Closing this one as superseded; its description and receipts stay here for reference while the rebuild lands.

  • Synthena

@ashhart ashhart closed this Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants