Skip to content

Draft: DeepSeek-V4.1 prefill on CUDA, decode on Metal over MCDMA (extends #1594, stacked on #2648 and #2373) - #3381

Closed
BlivionIaG wants to merge 136 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-long-relink
Closed

BlivionIaG wants to merge 136 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-long-relink

Conversation

@BlivionIaG

Copy link
Copy Markdown
Contributor

Draft, for alignment with #2648. Not for merge as one PR. It is the full working stack as a base to agree on; once the gate is agreed in #1594 it will be split into the per-unit PRs linked below.

What this changes

Before: a GB10 pair (CUDA, tensor parallel 2) can serve DeepSeek-V4.1-Flash and a Mac can serve the EXL3 lane (#2373), but a prompt prefilled on the pair never reaches the Mac. After: the pair exports a request's prompt state over the #2648 hand-off (--mcdma-produce, kv_transfer_params, MKVH protocol 2) and the Mac pulls it with --prefill-from, lands it in a blank snapshot of the served lane, prefills the tail and decodes. Off unless both flags are given; the prefix is labelled exact_mode: remote_prefix and is never kept as a native state.

The series, each unit also open as a draft on the fork for per-unit review (BlivionIaG/TensorFold):

Checks on this head

  • Head commit: 83e4297c74.
  • python3 tools/pr_check.py --base upstream/main: 0 errors, lean 384 against 385 on main, 0 new; 4 advisory warnings (three documentation or CLI-help IPv4 addresses, --pr note).
  • Tests and numbers per unit are in each fork PR body; they were not re-run as one tree against main. CI: not run.
  • Not run: Metal-linked tests, kernel contract and the CUDA build on this exact head, because this draft is the integration of already-checked units.

Receipt

Open questions for the maintainers

  1. Is a second family on the Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b)  #2648 hand-off welcome, and does it need its own gate issue?
  2. Where does a router that picks between a pair and a Mac per prompt belong: in tree or out of tree?
  3. Pair with the author of Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b)  #2648: share the wire format and rebase on whichever lands first, rather than two implementations.

Checklist

  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.
  • Receipt incomplete: this is a draft; see above.

…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 added 25 commits November 11, 2026 17:01
… Mac, not queued behind the pull

The DeepSeek V4.1 Mac pulls (ConnectX and HTTP) held a mutex across the trigger,
the export and the transfer, so a second long prompt waited out the first one's
multi-second prefill with the Mac idle. They now keep a try-lock gate
(core/lane_remote_route.zig): a prompt that finds the pair busy is prefilled
locally unless the pull under way ends soon enough that waiting for it, then
pulling, beats the Mac's own prefill; a wait already begun ends when that stops
being true. TF_PREFILL_ROUTE=always keeps the old one-at-a-time queue. No wire
change.
…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.
…dicted times

Source.wants returns a verdict and is told how many streams are decoding. In
TF_PREFILL_ROUTE=auto (default) a prompt goes to the pair when a stream decodes
on the Mac, or when the pull is predicted no slower than the Mac's own prefill,
from running averages of pulls, the Mac's own prompt passes and its last-token
pass (seeds TF_PREFILL_LOCAL_TPS, TF_PREFILL_REMOTE_TPS); a busy pair is not
waited for beyond what prefilling here costs. Transient verdicts are weighed
again while the prompt waits for a lane and logged once per reason. The route
state machine and the rates are host-tested. always keeps today's behaviour.
TF_PREFILL_ROUTE, TF_PREFILL_LOCAL_TPS and TF_PREFILL_REMOTE_TPS were read with a
direct getenv, which the lean check refuses; they now go through environment.read.
…ode on a Mac

Hardware, the link's set-up and its traps, launch flags and environment, the export and decoder profiles, measured time to first token against
the Mac alone, the fallback when the pair or link is down, and what is not measured.
mcdma-rpcd connect unlinks and recreates /mcdma-rpc.NAME at every start, so a
mapping taken once keeps the dead object: the client's renew fails with
LinkDown for good. Relink keeps the link's name beside the mapping and the
client; renew checks that the name still maps the object held and, if not,
maps the new one (a refused map waits 1 s doubling to 30 s) and makes a new
client in place.

POSIX shared memory on a Mac has no inode, so the check writes a nonce into the
client's own payload bytes, which nothing reads between calls, and looks for it
through a fresh mapping of the name; the bytes are put back. The test runs the
daemon's life on a fake object: replaced, refused as unsafe, and adopted before
its link is up.
exportAt took a snapshot and handed it to the exporter even when the request had
been cancelled in the pass before the cut, leaving a held export that nobody
will read until its time to live ends. It now returns at once for a cancelled
request. 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.
…'s pull, report each pull's phases

A pull's time limit follows its predicted time (TF_PREFILL_TIMEOUT_S if set,
else 15 s plus three times the prefix at the pair's measured rate plus the tail,
30 s to 30 min) for the trigger and, over HTTP, the transfer. Failures of the
pair or its link count in a circuit breaker (TF_PREFILL_BREAKER, default 3;
TF_PREFILL_COOLDOWN_S, default 30): open, prompts are prefilled here and the
router answers `down`; after the cool-down one pull is the trial, preceded by a
GET /health on the producer's server and, over MCDMA, by Relink's re-open of the
connect daemon's mailbox. A refusal or a mismatch is an answer, not a failure.

A request that ends while its pull is under way tells the pull (Ticket.gone,
Source.fill's new argument): the gate wait, the trigger's exchange and the
decoder's calls between frames stop with Aborted, a held export is closed, and
nothing is logged as a failure. The producer's own prompt pass is not touched.

A reply's tensorfold block gains remote_route (the router's verdict) and, for a
pulled prefix, remote_queue_seconds, remote_trigger_seconds, remote_pull_seconds,
remote_land_seconds, remote_tail_seconds, remote_bytes and
remote_tokens_per_second; the server logs one line per pulled prompt.
A pulled hand-off's ring parts (layers 40..42, the last 128 keys of the DSpark
stages) were always read and dropped. When the slot's Packed has the three
stages (43 layers) they now land in its live bytes through Import.landRing, the
code a direct import uses: the part must be bf16 [rows, 512] named ring, rows no
more than min(upto, 128), the same rows for every stage, each stage once, and the
three stages all arrive or none. A 40-layer slot still reads and drops them and
reports drafter_dropped. A producer ships rings only in its full-prefill profile
with drafts on; the replay profile has none, which is unchanged.
…ine, cancel, phase metrics and drafter-ring paragraphs
The cut stands in the step that finishes a piece-run prompt (after its last piece and the decoder replay, before the last token's window, in finish and in the joined tail), so --mcdma-produce no longer refuses TF_DSV41_PREFILL_PIECES. Lanes arm the export point at begin, the GPU target runs it once.
The read-back stays at the cut; the bf16 conversion runs on its own thread (two at a time, a third inline), a reader waits for an export still converting, and stop waits for the converters.
Remote takes the extra links' clients and pulls one producer per shard, each in
its own thread into its own sink, so a pair cabled to two ports moves a split
KV pool at the sum of the links. The landing keeps a sink per shard and the
importer counts its parts atomically.
Each name opens its own mailbox and client; a single name keeps the single
producer path.
A rank's export holds the pages it stores (shard k of the world); shard 0 also
carries the rings, carries and 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.
Rank 0 sends an export op at the cut; a follower started with
TF_DSV41_PRODUCE_LINK serves its pool pages under the same hand-off id on its
own link.
…ngth

A stream of synthetic finite rows with the real shapes, for timing the landing
and decode at a context nothing has prefilled. A hand-off file is read in 1 GiB
steps (a single read of 2 GiB or more fails on macOS) and its blob keeps the
parts where the stream holds them instead of copying them twice.
# Conflicts:
#	CHANGELOG.md
#	zig/src/fabric/prefill_source.zig
#	zig/src/families/deepseek_v41/handoff/landing.zig
#	zig/src/native/deepseek_v41_remote.zig
A prompt that takes the producer minutes to prefill outlived the clients
made before the trigger when an rpcd daemon re-linked meanwhile: the
finished export was not pulled (LinkDown after the whole prefill, the Mac
prefilled the prompt again). Remote.renew is called between the trigger and
the pull; the DeepSeek V4.1 pull makes every link's client afresh and waits
up to 30 s for a link that is down at that moment. A fake-link test flaps
two KV_SPLIT links inside the trigger.
@BlivionIaG

Copy link
Copy Markdown
Contributor Author

Superseded by #3386: the same tree with 37 commit identities corrected to the public noreply address (a push to this branch would have been a force-push). Closing.

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