Skip to content

deepseek_v41 CUDA: a split KV pool is exported by shard, each rank exporting its own - #3567

Open
BlivionIaG wants to merge 228 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-handoff-export-shards
Open

BlivionIaG wants to merge 228 commits into
ashhart:mainfrom
BlivionIaG:pr/dsv41-handoff-export-shards

Conversation

@BlivionIaG

@BlivionIaG BlivionIaG commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Before, --mcdma-produce refuses a split KV pool (TF_DSV41_KV_SPLIT). After, a split pool is exported by shard: 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 an export of at most 8 ranks is accepted. 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. --mcdma-produce http still serves a replicated pool only. The decoder's pull of the shards is not in this PR. Slice 5 of the chain in #3553.

Checks on this head

  • Head commit: ba685ce179
  • Lean checker, python3 tools/zig/lean_check.py, on the parent head and on this head: 341 problems on the parent head, 341 on this head, 0 new (tools/zig/lean_new.py). tools/pr_check.py --base upstream/main --pr 3567: 0 errors, 1 advisory warning, inherited from Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b)  #2648 (cli_remote.zig:40, a non-loopback IPv4 address).
  • Tests run, with the command and pass, fail and skip counts:
    • All run on e72446157c, the same code as this head without the CHANGELOG lines; the host is an arm64 Mac, -Dfixed-cpu.
    • zig build -Dfixed-cpu test-dsv41-handoff --summary all: 83 pass, 0 fail, 0 skip.
    • zig build -Dfixed-cpu test-handoff-routes-host --summary all: 24 pass, 0 fail, 0 skip.
    • zig build -Dfixed-cpu test-dsv41-cuda-host --summary all: 440 pass, 0 fail, 0 skip.
    • zig build -Dfixed-cpu test-dsv41-draft --summary all: 139 pass, 0 fail, 0 skip.
    • zig build -Dfixed-cpu test-lane-api-host --summary all: 681 pass, 0 fail, 0 skip.
    • zig build -Dfixed-cpu test-dsv41-env-host test-environment-host --summary all: 14 and 23 pass, 0 fail, 0 skip.
    • zig build -Dfixed-cpu test-dsv41-device-host --summary all: 223 pass, 0 fail, 2 skip (the skips need a device; Prefill on a GB10, decode on a Mac: long prompts for Qwen3.8-27B handed over ConnectX (#1594, step 2b)  #2648's head: 221 pass, 2 skip).
    • compile-dsv41-cuda, compile-dsv41-server, compile-dsv41-tool and check-native-cuda-host (Linux cross-compiles, never executed): exit 0.
    • zig fmt --check build.zig zig and git diff --check: clean.
  • CI: no checks reported on the branch yet; nothing to claim.
  • Not run, and why: zig build test test-golden (full suite), dev-tools, any GPU run: the build machine has no CUDA device, so the shard export was exercised by host tests and cross-compiled, never executed on a GPU or across two ranks in this PR. The failing-before check for the new tests was not done.

Receipt

  • Main against branch: not run; no GPU on the build machine. The end-to-end run of the whole stack, with its numbers, is in DeepSeek-V4.1 mixed mode: prefill on a GB10 pair, decode on Metal over the #2648 hand-off (gate and slices) #3553; it ran the export profile (plain prefill, replicated pool) on a later tip, so no split-pool export was measured end to end on this head.
  • Boxes it reaches: DeepSeek-V4.1 on CUDA with TF_DSV41_KV_SPLIT and --mcdma-produce.
  • New switch? TF_DSV41_PRODUCE_LINK: unset by default, a listen-link name (1 to 20 of A-Z a-z 0-9 _ -); row in docs/environment.md, registered in platform/environment.zig (scope cuda), read by tf-dsv41 follow.
  • Exactness, speed, prompt speed: not measured on this head.
  • Licence of any new weights or drafter: n/a.

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.

Update after review

ThinkOffApp and others added 25 commits November 14, 2026 10:39
…, sent as KV handoff protocol 2

hybrid_state gives Qwen3.8-27B's recurrent and attention state one byte order, header and token sha256 that CUDA and Metal both read. Protocol 2 sends a recurrent layer's state part by part with a CRC-32 a frame (ARMv8 CRC instructions where present); protocol 1 readers refuse it. The producer table holds exports for a hand-off, refuses a reused id, expires them, and caps the bytes held (HeldExportsFull). fabric_handoff and tf-mcdma-pair tests cover the fake link and the frames. (ashhart#1594 step 2b)
…a kept state, and is kept as remote

The lane host fetches a remote prefix on its own thread after the cache's peek, leads the prefix wait for requests on the same prompt, and falls back to a full local prefill on a refusal. With TF_PREFILL_KEEP (default 1) the states a pulled prefix builds are kept in the prompt cache marked remote, never written to disk or learned from, so a chat's follow-ups resume on the Mac. Tests pin provenance (remote_prefix, pulled_prefix), the keep rules and slot 0's let-go. (ashhart#1594 step 2b)
…ls them over an MKVH link

cuda_produce reads a CUDA copy in place and serves hand-off exports as the link's service, at most TF_PRODUCE_HELD_GIB held (default 32). On the Mac, qwen27_remote pulls a prefix into a blank state, checks model, checkpoint, token sha, TP, geometry and protocol, and refuses a checkpoint whose state is not Qwen3.8-27B's (Qwen3.5-9B) at start. remote_trigger asks the GB10 over bounded HTTP, with TF_PREFILL_API_KEY_FILE's key as a Bearer token and a named 401. A detected mismatch turns remote prefill off; a refusal or timeout does not. The TF_PREFILL_* settings join the environment registry. (ashhart#1594 step 2b)
… a GB10, and the hand-off's API fields

A completion's kv_transfer_params.mcdma_handoff becomes its hand-off; a malformed one now returns 400 on every native server. Replies on a remote prefix report exact_mode "remote_prefix" with remote_prefix, pulled_prefix and kept_remote_cache_tokens. docs/api.md and docs/environment.md describe both. Off unless both machines are started with the new options. (ashhart#1594 step 2b)
…ecks on real weights

The GB10 exports a state (export, tail); the Mac restores it from a file or a live pull and checks it: teacher-forced KL and top-1 (close), the backends' own gap (floor), stage times (time, multi), and agree, which lists every position where the restored state's greedy token differs from the Mac alone with both top-1/top-2 margins, plus repeat restores' bytes and tokens. State files are read in 1 GiB pieces, as macOS refuses one read over 2 GiB. (ashhart#1594 step 2b)
…rrow and no promise

A repeat hand-off whose lookup finds a remote copy at the cut resumes below it on the engine's own state and keeps the cut as its own. When a queued chat protects the remote copy and the budget has no room beside it, the guard refuses that keep (CachePromised). The test shows the export and the reply still go on, the borrow from below() is let go, no job is left holding a promise, and the remote copy still serves the next chat.
…umes on the Mac

A stream on a pulled prefix was not plain(), so leave() dropped slot 0's record, rewindPoint returned 0 and every follow-up after a hand-off started at 0 and pulled its whole prompt from the GB10 again. Such a stream now counts as plain for slot 0: its pass makes a rewind point at the history end past the cut, and leave() keeps the record, marked remote (Standing.remote). A pass that resumes on that record, here or back at its point, takes its rows' origin (inherit: reuse.remote set, reuse.pulled cleared), so its reply reports the prefix as kept remote and its keeps are marked remote, never the Mac's own. A refused copy that ran here from 0 leaves an own record. With TF_PREFILL_KEEP=0 slot 0 keeps no record and no rewind point of a hand-off's rows, and Job.kept and Job.keep keep nothing on a remote prefix. The unplanned cache checkpoint still skips remote streams. The decisions move into qwen27_resume.zig (plain, leftRemote, inherit, rewindAt, Standing.left, Standing.point, Standing.keeps), where host tests pin the hand-off chain, a refused import, each case that keeps nothing (TF_PREFILL_KEEP=0, a cancelled or failed reply, images, prompt logprobs, untaught rows) and a pull that reaches the history end, which makes no rewind point. (ashhart#1594 step 2b)
New host tests (qwen27_handoff_test.zig, "qwen27 hand-off:", run by test-qwen27-reply-cache-host) drive the real lane host with a fake backend over a device-less Metal whose slot 0 choices are qwen27_slots' own: resumeAt as the lane host's resume_peek, opening where slot 0 resumes, rewindPoint and leave. A pulled turn leaves a remote record with its rewind point at the history end; its follow-up pulls nothing, resumes in place where the turn left slot 0 and reports the prefix as kept remote. With TF_PREFILL_KEEP=0 the follow-up pulls again. A pass on slot 0's remote rows makes no unplanned checkpoint, on its own rows it does, and either way it clears a pull it overtook. To reach these host-side, takeStanding inherits the origin once after its switch (here or back), attach's TF_PREFILL_KEEP goes through remote.keepRule (lane host and slot 0 alike), and leave and rewindPoint are pub.
The cache plans a fill's marks without slot 0's in-place resume, so a follow-up that resumes slot 0 (its own rows, or a hand-off's since the last commit) can carry marks below where its pass begins. It never stands at them, yet a request arriving during its pass waited for one until the pass ended, then computed the prefix itself. The prefix wait now skips a leader's marks at or below its stream's cached rows. A request picked in the same admission as the leader, before its first chunk, is not covered: the leader's start is not known yet. Host tests: a request arriving during a fill waits for its cut and resumes it; one arriving during a fill that resumed past the cut does not wait.
…DA export needs

compile-qwen35-rounds-host builds zig/tests/qwen35_cuda_main.zig as its own module, with cuda, qwen35, core and lanes only. Since the main imports qwen35_cuda_export.zig, which reads @import("hybrid_state"), that step stopped compiling. It now gets the same hybrid_state module zig/build/cuda.zig gives tf-qwen35-cuda, built for the census target. (ashhart#1594 step 2b)
inherit now takes the plan and leaves a stream's origin alone for .none, so the decision that a pass resumed here or back at the rewind point stands on the record's rows (remote or not) lives in qwen27_resume.zig, not in takeStanding's arms. The .back arm needs rewindSlot, a GPU blit, so no host test reaches it in qwen27_slots.zig; the rule it calls is pinned by the resume tests, whose helper now calls inherit as takeStanding does instead of deciding by itself. (ashhart#1594 step 2b)
…ixture

The hand-off fixture's pass now carries opening's rewind point as chunk's saveRewind would, so the follow-up's rewind_at is the code's (turn 1's point carried; a pass resumed in a reply sent back as generated makes none), and it keeps the s.cached opening set over the fake's own fill instead of setting it again from the resumed position, so qwen27_slots.opening's line is what the reported remote prefix reads. Slot 0's hand-off rules (qwen27_resume_remote_test.zig) also run in zig build test on every OS; the Metal fixture's tests stay in test-qwen27-reply-cache-host, macOS only. (ashhart#1594 step 2b)
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.
@ashhart

ashhart commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Thanks for the split-pool export work and for the follower-dispatch failure handling (dropping rank zero's saved state and publishing failure on every rank is the right shape).

The review's open list for this PR, from the last comment:

  1. The neutral CUDA-to-BF16 decoder rounds finite values that BF16 cannot represent, so altered state can complete landing. Reject every inexact conversion and replace the test that expects rounding. (Shared with deepseek_v41 handoff: Metal packers, importer, protocol 2 adapter and landing sink #3564.)
  2. A valid empty follower shard advertises protocol 1: with a two-token prompt in TP2, the one-token cut leaves rank 1 with no pages and no layers (handoff/plan.zig:149-172 emits no empty parts, cuda_export.zig:161-178 builds zero layers), so fabric/producer.zig:20-24 selects protocol 1 while handoff/p2.zig:57-69 requires protocol 2. Preserve protocol 2 for a valid empty follower shard and add this short-prompt split control over link and dump.
  3. Split dump files write rank 0 of 1 instead of the exporting rank and world, so a dumped follower shard can look like a complete replicated export. Carry the actual shard identity into the dump manifest and test both ranks.
  4. Pending reads can still race teardown because the active-reader count increases only after pinning and unlocking (cuda_export_serve.zig:218-238 vs stop at :102-118). Count opening readers from entry through pin or refusal, reject reads while stopping, add the fail-before teardown control.
  5. Checkpoint identity still omits unindexed auxiliary weight files and does not bind the loaded snapshot on leader and followers. Cover full loader enumeration and replacement controls, with the consumer enforcing the same identity.
  6. Real CUDA rows still cannot land exactly in either Metal layout; synthetic layout equality does not close that production gap. The exact representation and consumer kernels are the shared gate with deepseek_v41 handoff: Metal packers, importer, protocol 2 adapter and landing sink #3564/deepseek_v41 on CUDA: --mcdma-produce exports a hand-off request's prompt state, and GET /v1/handoff/<id> serves it #3565/deepseek_v41 export: replay-mode and piece-wise prefill are exported at their cut #3566.
  7. Three changed Zig files are exactly 600 lines; we'll split them below the limit at pickup.

Items 2 and 3 are this PR's own and they are concrete: an empty follower shard is a valid state that the protocol selection mislabels, and a mislabeled dump manifest is worse than a refusal because it reads as a complete export. Fix those before the shared representation work.

Confirmed in source and kept: the split-page mapping, rank identities, whole-set dispatch failure (a fail op when no export will come, and a follower started with TF_DSV41_PRODUCE_LINK=NAME snapshotting its pool pages on its own host link), the allocation-free split-over-HTTP refusal, and the per-rank dump paths.

Status: waiting on items 1-6, then re-review, in landing order #3564 → #3565 → #3566 → #3567. The stack's conflicts with current main are ours; do not rebase.

  • Synthena

@ashhart ashhart added kind:feature Classified by Synthena as feature addition synthena:needs-changes Reviewed by Synthena; changes requested labels Dec 3, 2026
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Needs changes (kind:feature)

Adds split-KV-pool shard export for DeepSeek-V4.1 CUDA hand-off (each rank exports its own pool pages, rank 0 also rings/carries/drafter rows) plus the #1594 step 2b remote-prefix pull/keep plumbing across lanes, prompt cache, and fabric. Large stacked diff with new fabric modules, a new HTTP hand-off route, and cross-machine state transfer.

  • Branch currently has merge conflicts against base.

Findings:

  • [BLOCKER] zig/src/fabric/prefill_source.zig: The new guard rejects upto == prompt.len, but the very next line slices prompt[0..@intCast(o.upto + 1)], so a request whose prefix equals the whole prompt is now refused even though the original contract (manifest.first_token == 0, commit at o.upto) supported full-prompt prefixes. Suggested fix: Only reject o.upto + 1 > prompt.len (or clamp the extra token) so a full-length prefix still works, and add a test for upto == prompt.len - 1 and upto == prompt.len.
  • [BLOCKER] zig/src/families/deepseek_v41/forward_follow.zig: For op_export/op_export_fail the follower silently returns false when no exporter exists, which the caller treats as 'not for me' and falls through to the default f.ext handler (or error.BadPlan), so a leader's export op can be misrouted to the generic plan-link handler on ranks that legitimately have no exporter. Suggested fix: Return a distinct 'handled, ignored' outcome (or an explicit error) for op_export/op_export_fail when export_shard is null, so the op is never re-dispatched to f.ext.
  • [WARNING] zig/src/core/lane_host_fetch.zig: readKey switches to the resumable (cut-bounded) key only when at + 1 >= prompt.len; for a handoff whose cut sits earlier in the prompt the read-ahead still prefetches the whole-prompt key, so the disk state below the cut is never warmed and the admission path can stall on a cold read. Suggested fix: Compute the cut position from q.handoff and use exports.resumable(q) whenever the cut is below the prompt end, matching how lane_stream.open looks the handoff up.
  • [WARNING] zig/src/core/prompt_cache_remote.zig: retireTwins scans all entries and marks twins expired, but twins compares o.tokens/o.at without checking the cache salt or prompt-cache key, so two remote entries for different salts that happen to share tokens/spans/images can be retired even though they serve different requests. Suggested fix: Include the salt (and any key fields find/index.find compare) in twins so only entries that would collide in a lookup are retired.
  • [WARNING] zig/src/core/checkpoint.zig: openModelBound verifies each shard's stamped bytes but never checks bound.referenced() failure paths between the two calls; if the second referenced() fails after files were opened, errdefer ck.close() runs while bound may already hold a reference taken by the first call, leaking or double-releasing the bound descriptor. Suggested fix: Balance the two referenced() calls with a matching release on the error path (or take the second reference only after all fallible work succeeds).
  • [WARNING] zig/src/core/lane_host_warm.zig: The warm path now keeps at prompt.len unconditionally for kept-end jobs, but the previous call also passed chunks/spans/images/frame; if Job.keep derives those from the stream this is fine, otherwise remote states can be kept without their spans/images and later serve lookups they should not. Suggested fix: Confirm Job.keep reconstructs chunks/spans/images from the stream and request; if not, pass them explicitly as before.
  • Synthena

…n keeps its salt

- fabric_handoff.zig: the remote prefill source sends the producer the prefix and one token past it,
  takes a prefix ending one short of the prompt, and refuses a prefix of the whole prompt with
  PrefixTooLong before triggering anything (without the guard that slice panics past the prompt).
- prompt_cache_remote.zig: an exact keep retires only remote twins of its own salt; a lookup under
  another salt never finds it, so that salt's remote state stays (lane_remote_keep_test.zig).
@BlivionIaG

Copy link
Copy Markdown
Contributor Author

New head 93a7bec4d5: a merge of #3566 (a676630843).

2 Dec items:

  1. Codec: through deepseek_v41 handoff: Metal packers, importer, protocol 2 adapter and landing sink #3564.
  2. Empty follower keeps protocol 2 (7548e26482). The Export.recurrent flag is set by cx.build, so a follower shard with zero layers still answers protocol 2. Test: "a two-token TP2 prompt preserves protocol 2 on the empty follower shard over dump and link", plus a producer unit test. With the if (e.recurrent) line removed, test-dsv41-handoff gives 102/103 (expected 2, found 1).
  3. Split dump identity. The dump and the GET reply already write p.opts.shard/p.opts.shards (cuda_export_serve.zig, since fb2c54b3bb). Rank 0 opens with .shard = 0, .shards = world, and a follower with m.rank()/world. 7548e26482 added "a KV_SPLIT pair's producers each dump their shard with rank identity", which checks tp_rank/tp_size of both dumped shards. I did not run a fail-before for this one.
  4. Reader race: through deepseek_v41 on CUDA: --mcdma-produce exports a hand-off request's prompt state, and GET /v1/handoff/<id> serves it #3565.
  5. Identity and 6. Representation: through deepseek_v41 handoff: CUDA record codecs, FP4 packers and the part plan #3563 and deepseek_v41 handoff: Metal packers, importer, protocol 2 adapter and landing sink #3564.

Synthena lead on forward_follow op_export orelse return false: not a defect. followOp returns true only for stop; false means "handled, keep following".

Checks:

Not run: TP2 split export on real CUDA ranks (no device here).

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

kind:feature Classified by Synthena as feature addition synthena:needs-changes Reviewed by Synthena; changes requested

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants