Repository navigation
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
Closed
BlivionIaG wants to merge 136 commits into
BlivionIaG wants to merge 136 commits into
Conversation
…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.
…gures; the partial files carry their status
…implying a finished rewrite
…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.
…eaders state the rewrite
…e variant headers state the rewrite
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.
…dy only (they sample)
…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.
This was referenced Nov 14, 2026
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 labelledexact_mode: remote_prefixand 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):
fix: a failed admission no longer stops the 27B's concurrent CUDA scheduler #59 stack base: DeepSeek-V4.1-Flash on Metal: the EXL3 2.9 bpw lane #2373 on the Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b) #2648 base (mirrors of the upstream PRs, nothing new).
Tool call emitted inside an unclosed think block is dropped (empty turn, finish_reason=stop) #60 hand-off library, CUDA export and routes, Mac pull and landing. fix: the CUDA server answers malformed requests with 400 and failed ones with 500 or a stream error event #61 replay-mode prefill is exportable. fix: say why a CUDA start is silent (SIGUSR1 stack dump, extension builds, stale build locks) #62
TF_PREFILL_TAIL. packaging: ship the 27B's CUDA sources (qwen3_5/cuda/b16.cu, b16.cpp) #66 exact decoder replay.perf(qwen3_5 cuda): keep the prompt-end cache entry one token before the prompt's end #65 per-prompt route (auto, force, never), breaker, deadline, cancel, phase metrics. MLX: a long prefill stalls every running stream's decode until it finishes (4 × 16K prompts: earlier streams drop to 1–3 tok/s) #72 a request names where its prompt is prefilled.
perf: Flash Next reads a prompt chunk's n-gram rows on 16 threads (same bytes) #73/fix: preserve prefixes when checkpoint cannot fit #74 pieces exported at their cut; split-KV over two links. Proposal: export a CUDA prompt state and resume it on MLX (Spark prefill → Mac decode), with measurements #77 link renewal after the trigger.
CUDA: read the Flash Next NVFP4 (ModelOpt FP4) checkpoint as it ships #67/feat: spill evicted conversation prefixes to disk, and --checkpoint-slots #68/fix: the CUDA server types Qwen tool parameters by the tool's schema #75/M1 Max Qwen3.8-27B agent repeats successful tool calls on 0.3.6.2 (also seen on another runtime) #76 Metal decode and prefill work on the DeepSeek-V4.1-Flash on Metal: the EXL3 2.9 bpw lane #2373 lane. fix: Qwen3.8 Flash Next and 27B on EXL3 checkpoints stop at the end of the chat turn #69/Independent run on an M5 Pro 64 GB: 64 GB memory-class cells for Qwen3.8-27B (+DFlash2, --drafter none), Nemotron 3.5 and oQ2; release checks all equal #70 prompt cache disk tier and cone prefill. Qwen3.8-27B + DFlash2 on 64 GB: the default context fits prompts it cannot retain, so conversations past ~100K re-prefill every turn #71 layer-split gate instrumentation.
feat(cuda): stop strings on every CUDA engine, and ignore_eos on the 27B's CUDA engine #63/Add Qwen3.8 MLX image input support #64 operator guide and service recipe.
Issue: Refs MCDMA over a ConnectX link, and serve --cluster on real hosts (transport only) #1594 (extends step 2b from Qwen3.8-27B to DeepSeek-V4.1). The gate for a second family is not agreed yet; see the proposal comment on MCDMA over a ConnectX link, and serve --cluster on real hosts (transport only) #1594.
Stacked on: Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b) #2648 and DeepSeek-V4.1-Flash on Metal: the EXL3 2.9 bpw lane #2373 (via the mirrors above). The diff against
maintherefore contains both until they land; whichever lands first, this rebases.atc overlap --jsonagainstmain, ATC 0.9.6: coverage incomplete (pullRequestsLimit,timeLimit,pullFilesUnavailable). Real textual conflicts with Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b) #2648 (38 files), Native Vulkan backend for Qwen3.5-2B (opt-in): engine and kernel-contract registration (stacked on #1526) #1544, GLM-5.3-Flash on CUDA keeps conversation states on disk, every rank's part (--learn-conversations) #1411, CUDA (GB10): a lending-daemon source for the display carveout, opt-in #2762, hip flashnext: an eight-row verify window, so a lone stream's copies land up to seven tokens a round #2730, moss image: serve pictures on CUDA (encoder, decoder and host for #1573) #2281, qwen35 cuda: fuse the dense MLP's NVFP4 prompt gate and up projections into one launch #2410, idol: Idol's denoiser on CUDA (stacked on #1766) #1767, glm cuda: decode windows' EXL3 experts run on the 16-pair item plan #2044, XPU: Qwen3.8-27B attention merge with 16 subgroups per head, bit-identical #2799; the rest were not testable. The Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b) #2648 conflicts come from the older base of the mirror; resolving them with that PR's author is the point of this draft.Checks on this head
83e4297c74.python3 tools/pr_check.py --base upstream/main: 0 errors, lean 384 against 385 onmain, 0 new; 4 advisory warnings (three documentation or CLI-help IPv4 addresses,--prnote).main. CI: not run.Receipt
Open questions for the maintainers
Checklist