Skip to content

DeepSeek-V4.1 EXL3 Metal: the indexer's one-shot select covers prefill chunks past 4096 keys - #3734

Open
BlivionIaG wants to merge 163 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-exl3-indexer-select
Open

BlivionIaG wants to merge 163 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-exl3-indexer-select

Conversation

@BlivionIaG

@BlivionIaG BlivionIaG commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #3382 (see Stack). One behavior: the indexer's one-shot radix select also covers prefill chunks whose tile scores overflow the scratch. Host-side change in one file plus a device test; no kernel source changes.

What and why

For a prefill chunk past about 4096 keys the tile-major scores of all rows no longer fit the scratch, so the one-shot select was skipped and the chunk fell to the one-thread-per-row heap path. The one-shot path now runs over sub-blocks of fit / 64 * 64 rows (every key tile of a sub-block fits the scores scratch), over the same tile-major scores and with the same tie order. Single row, candidate and masked paths are unchanged. No new setting. The scratch holds as many rows as the prompt chunk (8,192 by default), so a chunk takes this path whenever ceil(keys / 4096) * rows passes the chunk size; an 8k prompt's single chunk already does.

Kernel level

An M5 Ultra, GPU timestamps, median of 7, per indexer call (one layer). A standalone harness (not part of the PR) replays the host's dispatch sequences from csa2_index.zig on seeded inputs: the base's heap path (tensor-tile scorer, then clear, seed, filter, insert per tile, then the parallel finish) against this PR's (row scorer and the one-shot select per sub-block). The PR's total therefore also includes the row scorer, which the one-shot path already used on the base when a chunk fit. The base's select time is its total less the same scoring kernels run alone, so it is derived; the PR's is the select launches alone.

chunk, rows x keys base total PR total base select PR select
8,192 x 32,768 (32k prompt, last chunk) 50.9 ms 27.9 ms 18.7 ms 3.3 ms
8,192 x 16,384 (16k prompt, second chunk) 29.7 ms 12.2 ms 15.6 ms 1.8 ms
8,192 x 8,192 17.5 ms 4.7 ms 12.7 ms 1.2 ms
8,192 x 28,672 (ratio 2) 48.2 ms 26.0 ms 18.2 ms 3.1 ms
8,192 x 65,536 (16 tiles, sub-blocks of 512) 91.3 ms 61.6 ms 22.2 ms 6.1 ms
4,096 x 32,768 (4,096-row scratch) 31.7 ms 15.7 ms 14.0 ms 1.8 ms
4,096 x 16,384 (4,096-row scratch) 20.4 ms 7.3 ms 12.0 ms 1.1 ms
16,384 x 32,768 (16,384-row scratch) 80.7 ms 46.6 ms 25.4 ms 5.4 ms

Exactness

The same harness compares the two sequences' whole 512-slot position arrays, int for int, at 24 shapes: all identical. 19 take the heap path on the base and the one-shot path here: 8,192-row chunks at 8,192, 16,384 and 32,768 keys, at 16,384 and 28,672 keys with ratio 2, and at 65,536 keys (16 tiles, sub-blocks of 512); 4,096-row chunks at 16,384 and 32,768 keys in a 4,096-row and in an 8,192-row scratch; 4,097 rows at position 0 (the first chunk size just past the scratch); tail sub-blocks (5,000 rows at 32,768 keys in blocks of 1,024; 8,191 rows at 24,576 keys in blocks of 1,344; 4,097 rows at 16,384 keys in blocks of 2,048; 5,000 rows from position 0, a tail of 904); 100 rows at 40,100 keys in an 800-row scratch (blocks of 64); a 16,384-row scratch; and tie-heavy scores (three distinct bf16 values) at 32,768 keys and on a 4,097-row tail. Five take the same path in both: 4,096 keys, 4,097 keys with 4,096 rows (two tiles exactly fill the scratch), one row at 32,768 keys, and 65 rows and 63 rows in scratches too small for any block, which stay on the heap path.

The change is covered in the repo now: index_select_blocks_test.zig (in test-deepseek-v41) runs the whole indexer on seeded keys on the default path and with TF_DSV41_INDEX_SELECT_ONE=0, and compares every row's picks, at sub-block sizes of 64 and 128 rows with tails, a tie-heavy case and a case that stays on the heap path. It passes on an M4 Pro and an M5 Ultra, and fails when a sub-block's position is left unshifted. It skips cleanly when no Metal device is present.

Greedy output is identical 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.546 s (4.531-4.550) +0.017 s
16,095 tokens 7.753 s (7.716-7.790) 7.703 s (7.677-7.706) -0.050 s (-0.6%)
31,947 tokens 14.105 s (13.708-14.368) 13.798 s (13.710-13.961) -0.307 s (-2.2%)

This PR's own effect is small. At 7.8k it is nil, at 16k the ranges do not overlap but the gain is 0.6%, and at 32k the base's boot-to-boot spread (0.66 s) is larger than the median difference; the same prompts unsalted give 4.553 / 7.761 / 13.982 s on the base and 4.567 / 7.697 / 13.834 s here (7.8k within noise, 16k -0.8%, 32k -1.1%). The kernel-level table above is the firm result; end to end this is at most a 1-2% TTFT gain at 16k and 32k, and none at 7.8k.

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 end-to-end and kernel numbers (the new test also ran on an M4 Pro, where it takes the non-tensor scoring path); 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 ad1b101801)

  • zig fmt --check clean; python3 tools/pr_check.py --base 5d1f3d6418 --pr 3734: 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

Copy link
Copy Markdown
Contributor Author

Refreshed as you asked, after #3382: head 4507efacb1, a merge of the refreshed #3382 head b79e344ff8 (which contains main at b192eaa298); no conflicts, this PR's own diff is unchanged. Receipt and the one structural change (Metal engine in model_metal.zig/load_metal.zig) are in the #3382 comment: exact reply hashes on 8 fixed prompts are identical to #3382 (two runs each), decode 51.1-51.9 tok/s and cold-prompt first-token times at 2k-32k are within the run-to-run spread of #3382. git diff --check, zig fmt --check clean; lean 0 new; the Linux CI jobs run on this head.

…+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

Thank you, @BlivionIaG. We re-checked this head as the base of the DeepSeek-V4.1 EXL3 Metal stack.

The index-selection change is narrow and looks right: each sub-block shifts its position, query and weight views and its output slice together, keeps the original stride, and keeps the existing scoring choices and heap fallback; no Metal source changes. We found no new bounds, lifetime or precision problem by inspection.

Serving the pinned EXL3 pack is fine: TensorFold's rule is that we reproduce the loaded checkpoint bit for bit, whichever build it is. What remains for this slice is an exact comparison of the selector against its serial reference on the final integrated tree, on both an earlier Apple GPU and the newer tensor path, plus the stack's own README notes (later attention repairs invalidate older served qualification, and the recorded projection failures) before the stack as a whole is served.

  • 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 24, 2026

Copy link
Copy Markdown
Owner

Thank you, @BlivionIaG. The selector code is unchanged, and the row offsets, scratch bounds, tails and heap fallback look consistent. The pinned community EXL3 pack is fine; the earlier objection based only on its format is withdrawn.

This slice is ready for an exact comparison against the heap path on the final integrated tree, on an earlier Apple GPU and on the tensor path. It sits on the stack from #2373, though, and one gate there applies to all of it: our review of #2373 found its projection kernels and drafter code following mlx-serve line for line. Before any of the stack can land, that code has to be rewritten from TensorFold's own code, or shown to have been written independently. Please tell us which it is at the current head.

  • Synthena

@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart. The copy question is answered on #3382: the #2373 projection kernels and drafter are its author's code and I cannot show they were written independently. The commits this slice adds are mine (3 beyond #3382's 39), kept separate under my name so they can be reviewed or rebased onto whatever replaces #2373's code. The tensor-path run on the M5 Ultra at #3736's head (e880b33471, which contains this slice) passes test-exl3-gpu 41/41 and test-deepseek-v41 77/77 with nothing skipped. The exact comparison against the heap path on the final integrated tree is not run yet; I will run it on the tree that is settled by that decision, on the M4 Pro and the M5 Ultra.

This branch has not been deployed

No deployments
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