Skip to content

DeepSeek V4.1 remote prefill: leave the Mac only the last prompt token (TF_PREFILL_TAIL) - #3597

Closed
BlivionIaG wants to merge 128 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-pull-tail
Closed

BlivionIaG wants to merge 128 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-pull-tail

Conversation

@BlivionIaG

@BlivionIaG BlivionIaG commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Before, the Mac runs the part of a prompt past the pair's last chunk boundary (96 to 461 tokens after the 512-token boundary) as a prefill pass. After, by default (TF_PREFILL_TAIL=1) the Mac asks the producer for the whole prompt but one token: the export stands one token short and the Mac runs that token as one decode-class step. TF_PREFILL_TAIL=0 keeps the chunk rule. The policy gains a tail count; no wire, manifest or producer change. Slice 9 of the chain in #3553.

Checks on this head

  • Head commit: 1690fdc4ed
  • Lean checker, python3 tools/zig/lean_check.py, on the parent head and on this head: 339 problems on the parent head, 339 on this head, 0 new (tools/zig/lean_new.py).
  • Tests run, with the command and pass, fail and skip counts:
    • All run on the same code as this head without the CHANGELOG lines; the host is an arm64 Mac, -Dfixed-cpu.
    • zig build -Dfixed-cpu test-native --summary all: 173 pass, 0 fail, 3 skip.
    • zig build -Dfixed-cpu test-lane-api-host --summary all: 709 pass.
    • zig build -Dfixed-cpu test-dsv41-handoff --summary all: 94 pass†.
    • zig build -Dfixed-cpu test-dsv41-env-host test-environment-host --summary all: 14 and 23 pass†.
    • zig build -Dfixed-cpu test-dsv41-draft --summary all: 139 pass†.
    • zig build -Dfixed-cpu test-fabric-scratch --summary all: 60 pass†.
    • compile-dsv41-server: exit 0†.
    • zig fmt --check build.zig zig and git diff --check: clean. tools/pr_check.py --base upstream/main --pr 3597: 0 errors; its advisory warnings are 0.0.0.0 bind examples in the docs and an address in Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b)  #2648's cli_remote.zig.
    • zig build -Dfixed-cpu test-native --summary all after DeepSeek V4.1 on Metal: --prefill-from pulls a prompt's prefix state and lands it in the served lane #3594's review fix (df3795f6f8, one file, deepseek_v41_lane_host.zig), at the stack tip fb3e8e93aa: 174 pass, 3 skip (63 steps). The other steps above were not re-run after it.
  • CI: no checks reported on the branch yet; nothing to claim.
  • Not run, and why: zig build test test-golden (full suite), dev-tools, test-exl3-gpu and test-deepseek-v41 on this head, any Metal run of this slice on its own. † counts were measured on the tree before a test-only fix to zig/src/native/qwen27_handoff_test.zig; those steps do not compile that file. The failing-before check for the new tests was not done.

Receipt

Checklist

  • The title and description match the head commit, including the receipt and the stack.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.

…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.
ThinkOffApp and others added 21 commits November 14, 2026 10:39
Adds the host-only record library for the DeepSeek-V4.1 prefill hand-off: the release geometry,
the codec between CUDA's fp8 cache records and the neutral bf16/f32 parts, the E2M1/E4M3 FP4
mirrors of the Metal packers, the part plan (what travels, cut into frames of at most 2 MiB)
and the CUDA-side export of a snapshot's copies into those parts. Each piece is tested against
independent tables or f64 references; `test-dsv41-handoff` runs them on the host.

Not included: the Metal packers and importer, protocol 2 adapter, landing sink and stream
file, the CUDA export, and any transport.
… landing sink

Adds the Metal side of the host-only hand-off library: the packers that write the neutral
bf16/f32 parts into the release lane's and the served lane's cache layouts, the importer that
accepts exactly the parts a shape implies, the export from a Metal snapshot, the protocol 2
adapter (`p2`: manifest check and a sink for `fabric.decoder.pull`), the landing sink and a
test-only hand-off file (`blob`). Export-to-import round trips cover both layouts, replicated and
split pools, and protocol 2 runs end to end over a fake link.

Not included: the CUDA export, the byte-stream file, any transport, and the tests and checks
that read the served lane's source.
…ompt state, and GET /v1/handoff/<id> serves it

A DeepSeek-V4.1 CUDA server started with --mcdma-produce LINK (or TF_DSV41_HANDOFF_DUMP) reads the active
slot's state back at a hand-off request's cut (the prompt less its last token, armed through the draft
lanes and run by the GPU target), builds the library's bf16 parts and holds them under the request's id
until the decoder closes them (TF_PRODUCE_HELD_GIB). `--mcdma-produce http` holds them the same way and
serves them on the server's own port: GET streams the protocol-2 replies under a Content-Length, DELETE
releases, behind the key gate and the inference scope. `handoff_file` is the stream format the dump and
the HTTP body share.

A request cancelled by its cut captures no export: exportAt returned a snapshot to the exporter even when the request had been cancelled in the pass before the cut, leaving a held export nobody reads until its time to live ends. The prompt pass itself is not cancelled: on the GB10 pair the follower rank runs every pass the leader runs, so abandoning one on the leader alone would leave the follower waiting on a collective.

Not included: the decoder's side (pull, landing, HTTP fetch), replay-mode and piece-wise prefill, a split
KV pool, and the operator guide. The export refuses those configurations at start-up by name.
…at their cut

With TF_DSV41_PREFILL=replay the cut stands after the decoder replay, so the live slot holds the decoder
layers' rings (the last 127 positions the replay wrote). The window's oldest position of those layers was
never written by the replay and is zero in the export, which is otherwise the full export's bytes. The
drafter's rings of a replay-mode slot stand outside the snapshot and are read at the cut. The producer also
logs the read-back and build times of each export.

A prompt run in pieces is exported at the step that finishes it: after its last piece and the decoder
replay, before the last token's window. The draft lanes arm the export point when the prompt begins and the
GPU target runs it once, so `--mcdma-produce` no longer refuses TF_DSV41_PREFILL_PIECES and the other
streams keep decoding while the pieces run. An export point left by a prompt that never finished, or by one
that leaves, is cleared.

The read-back stays at the cut, on the engine thread; the conversion of the snapshot's bytes to the
protocol's bf16 parts runs on its own thread, at most two at a time (a third converts inline). A reader that
asks for an export still converting waits for it (up to two minutes) instead of finding it missing, and
`stop` waits for the converters.

Not included: the exact decoder replay and a split KV pool.
…porting its own

A rank's export holds the pages it stores (shard k of the world); shard 0 also carries the rings, the
carries and the drafter rows. The producer's responder answers as tp_rank k of tp_size world, and capture
reads this rank's pool pages instead of refusing a split pool. An export of at most 8 ranks is accepted;
`--mcdma-produce http` still serves a replicated pool only.

Rank 0 sends each follower an export op at the cut (and a fail op when no export will come); a follower
started with TF_DSV41_PRODUCE_LINK=NAME, an mcdma-rpcd listen link of its own host, snapshots its pool
pages there and serves them under the same hand-off id, so a split pool is exported one shard a link.
TF_DSV41_PRODUCE_LINK is registered in platform/environment.zig and read by `tf-dsv41 follow`.

Not included: the decoder's pull of the shards.
…y and CUDA export

Joins the Metal EXL3 lane with the hand-off library, the CUDA export and the
plain-HTTP producer, on the current main. Conflicts in cli.zig, prompt_cache.zig,
lane_stream.zig, metal_dsv41_limits.zig and runtime_sources/dsv41.zig are resolved
on main's side with ashhart#2373's changes re-applied; the contract walk of the DeepSeek
gate-gemm launch skips the source when not assembling, as its siblings do. It adds
no behavior of its own.
…and lands it in the served lane

With --prefill-from URL (and --mcdma-link NAME, or --mcdma-link http) the served lane asks a producer
to prefill the prompt's prefix, pulls the MKVH protocol-2 hand-off over the link or plain HTTP, and
lands it in a blank Snapshot (model_import, Snapshot.snapshotBlank/Seal); the pass then plans from where
the landed prefix ends (a mark at the prefix, the tail run locally) and the model stays resident while a
request waits for its fill. The landed prefix is labelled remote and never kept as native. A hand-off file
is read in 1 GiB steps, since one read of 2 GiB or more fails on macOS. The start-up line no longer says
the lanes are greedy only. Not included: per-prompt routing, the breaker, TF_PREFILL_TAIL, several links.
…dicted times

The DeepSeek V4.1 pull takes the pair one pull at a time through a try-lock gate. A prompt that
finds it busy is prefilled on the Mac unless the pull under way ends soon enough that waiting
pays; a stream decoding on the Mac sends the prompt to the pair even when it is no faster;
otherwise the pull must be predicted no slower than the Mac's own prefill, by running averages
the pull and the lane feed, counting only tokens the producer computed. TF_PREFILL_ROUTE=always
queues every prompt behind the pull as before; TF_PREFILL_LOCAL_TPS and TF_PREFILL_REMOTE_TPS
seed the averages. Not included: the breaker, the tail, several links.
…recovers

A circuit breaker (TF_PREFILL_BREAKER, default 3; TF_PREFILL_COOLDOWN_S, default 30) counts failures of the
pair or its link: open, prompts are prefilled here and the router answers `down`; after the cool-down one pull
is the trial, preceded by GET /health on the producer's server and, over MCDMA, by a re-open of the link. The
link is mapped again when mcdma-rpcd connect restarts and recreates its mailbox (fabric/relink.zig; a refused
map waits 1 s doubling to 30 s). A pull's time limit follows its predicted time (TF_PREFILL_TIMEOUT_S if set,
else 15 s plus three times the predicted pull, 30 s to 30 min). A request that ends while its pull is under way
stops it (gate wait, trigger exchange, decoder calls between frames) without logging a failure; the producer's
own prompt pass is not touched. A reply's tensorfold block gains remote_route and, for a pulled prefix, the
pull's queue, trigger, pull, land and tail seconds, bytes and rate; the server logs one line per pulled prompt.
A refusal or a mismatch is an answer, not a failure. Not included: TF_PREFILL_TAIL, several links at once.
…n (TF_PREFILL_TAIL)

The Mac now asks the producer for the whole prompt: the export stands one token
short of it and the Mac runs that token as one decode-class step instead of a
96 to 461 token prefill pass after the 512-token boundary. The policy gains a
tail count (0 keeps the chunk rule); no wire, manifest or producer change.
…s attached, and keep the startup line as it was

The scratch buffer and its residency commit now exist only with --prefill-from or TF_DSV41_HANDOFF_FILE; without them the keepalive target and the startup line are the lane's own, unchanged.
@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Closing: the maintainers declined the token-changing mixed mode, opt-in included (#3553). The branch stays on the fork.

@BlivionIaG BlivionIaG closed this Nov 17, 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