Skip to content

DeepSeek-V4.1 EXL3 Metal: the indexer row scorer uses all four simdgroups - #3736

Closed
BlivionIaG wants to merge 202 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-exl3-indexer-row-scorer
Closed

BlivionIaG wants to merge 202 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-exl3-indexer-row-scorer

Conversation

@BlivionIaG

@BlivionIaG BlivionIaG commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #3382 (see Stack). One behavior: the indexer's row score kernel runs on 32-row threadgroups with all four simdgroups live (index_exl3_nax.metal, plus the one-line dispatch change in csa2_index.zig), and a device test.

What and why

The prompt score tile kept two of its four simdgroups idle after staging the key tile for sixteen rows. It now scores thirty-two rows (two 16x32 simdgroup blocks by two key blocks) per staged tile. Arithmetic and summation order are unchanged.

Kernel level

An M5 Ultra, GPU timestamps, median of 9, base kernel (16 rows a threadgroup) and this branch's (32) on the same seeded inputs, every 4,096-key tile of the keys scored, in a standalone harness (not part of the PR):

rows at position, keys base this PR
1,024 at 24,576, 31,947 keys 2.73 ms 2.43 ms (-10.8%)
1,024 at 12,288, 16,384 keys 1.41 ms 1.26 ms (-10.9%)
4,096 at 12,288, 16,384 keys 5.87 ms 5.17 ms (-11.9%)
8,192 at 24,576, 32,768 keys 23.25 ms 20.49 ms (-11.9%)
8,192 at 0, 8,192 keys 3.46 ms 3.05 ms (-12.0%)
4,096 at 24,576, ratio 2, 14,336 keys 5.43 ms 4.82 ms (-11.2%)

Exactness

Scores bit-identical at 75 shapes in the standalone harness: every score a row's select reads (its first min(keys, (position + row + 1) / ratio)), compared as bit patterns in the tile-major layout the one-shot select reads, on seeded random inputs. The shapes: the six above; 1,024 rows at position 0; one row at position 0 and at 30,000; nine rows; 24 row counts from 2 to 4,097 around the 16-, 32- and 64-row edges (2, 8, 9, 15, 16, 17, 31, 32, 33, 47, 48, 49, 63, 64, 65, 96, 100, 127, 128, 129, 1,000, 1,023, 1,025, 4,097) each at ratio 1 and ratio 2; keys of 1, 2, 63, 64, 65, 4,095, 4,096, 4,097, 8,191, 8,192, 8,193 and 12,289 at 70 rows; 70 rows at position 0 (70 keys), and at position 4,090 with 4,100 keys and with 1 key; and tie-heavy inputs (three distinct bf16 values) at 1,024 rows x 31,947 keys and 4,096 x 16,384. An earlier version of this text cited eight shapes; that count came from a scratch harness whose log no longer exists, so it was replaced by this one.

The cells past a row's visible keys are not required to match and the select never reads them. In 9 of the 75 shapes (ratio 2, from 96 rows up) some differ, 0.02% to 0.3% of the cells past every row's visible keys: a threadgroup now holds 32 rows, so its early-out for a key tile past all of its rows' visible keys is decided for 32 rows instead of 16, and a cell between the two bounds holds a computed score here where the base wrote -inf. At ratio 1 and at the six timed shapes none differ.

In the repo: index_row_score_test.zig (in test-deepseek-v41) runs the whole indexer on seeded keys with the row scorer and with TF_DSV41_INDEX_ROW_SCORE=0 (the tensor-tile scorer) and compares every visible score bit for bit: 12 row counts from 9 to 127 (the 16- and 32-row block edges), both ratios, random and tie-heavy inputs. It passes on an M4 Pro and an M5 Ultra and fails when the dispatch covers too few row blocks. It skips cleanly without the two scorers.

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.527 s (4.523-4.536) -0.002 s
16,095 tokens 7.753 s (7.716-7.790) 7.749 s (7.744-7.777) -0.004 s
31,947 tokens 14.105 s (13.708-14.368) 14.091 s (14.023-14.312) -0.014 s

No end-to-end effect is measurable for this PR alone (unsalted prompts: +0.003, -0.013 and +0.034 s). By the dispatch condition the base runs the one-shot select, the only user of this scorer, only when ceil(keys / 4096) * rows fits the scratch's row count: with 8,192-row chunks that is no chunk of these prompts, so this PR changes nothing at those chunk sizes; stacked on #3734, whose sub-blocks put every chunk on that path, the 10-12% of a scoring pass in the kernel table applies. (Read from the code, not measured: #3734 and this PR were not run together.)

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 new test also ran on an M4 Pro); 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 bb0e891a5f)

  • zig fmt --check clean; python3 tools/pr_check.py --base 5d1f3d6418 --pr 3736: 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): 71 passed, 3 skipped on an M4 Pro; 74 of 74 on an M5 Ultra. The new test skips cleanly without a device.
  • tf-kernel-contract --only "dsv41 ix" (FP8 index kernels): 4 kernels pass, 4 controls red, same on base and this head; it does not cover the EXL3 index kernels, so it does not exercise this change.
  • 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.
@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 refreshed scorer keeps the same per-row arithmetic, and the new test compares every visible score bit for bit. The scorer, dispatch and test match your latest reported revision.

When we combine this with #3734's selector on our side, we'll keep its bounded sub-block loop, dispatch 32 rows using the local sub-block row count, and keep both test imports. The remaining evidence is that combined path's exact selected positions and full reply tokens, plus timing where the scorer actually runs. The older whole-model cells bypassed it and do not measure the combined gain.

  • 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, the updated #3382 head (bab2613de8) and the updated #3735 head (89e9a11f14). The one-shot-select conflict resolved as #3734's row sub-blocks plus this PR's 32-row four-simdgroup dispatch; the other conflicts were the changelog and a test import. Merge-tree is clean.

@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