diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md
new file mode 100644
index 0000000000..c267c91d93
--- /dev/null
+++ b/changelog.d/cluster-pair-serving-epoch.md
@@ -0,0 +1,16 @@
+### Two-Mac pairs recover after losing a rank during a stop
+
+- A two-Mac pair no longer stays unable to serve when it loses a rank while
+ its slot is stopping. Until the provider restarted, its leader refused every
+ later start, and `darkbloom cluster stop` left that Mac's part still
+ releasing.
+- Fixed a deadlock in the pair's request engine. Stopping the pair slot
+ cancelled a request's stream while the engine was telling that request the
+ pair had lost a rank. The stream's cancellation waited for the engine, and the
+ engine waited for the cancellation to finish, so the slot never stopped.
+ Cancellation and stream termination now never wait for the engine.
+- The leader also releases a committed start as soon as its session ends,
+ instead of after the old slot has fully stopped, so a slow stop can no longer
+ make it refuse later starts with "a committed start is already served". The
+ release receipt still waits, bounded, for the slot to retire, and a pair still
+ never serves two slots at once.
diff --git a/changelog.d/gemma-byte-fallback-flush.md b/changelog.d/gemma-byte-fallback-flush.md
new file mode 100644
index 0000000000..3f22c7588c
--- /dev/null
+++ b/changelog.d/gemma-byte-fallback-flush.md
@@ -0,0 +1,6 @@
+### Gemma 4 replies keep characters outside its vocabulary
+
+- A Gemma 4 reply that ended in characters its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost all of them: `all zipped up π` came back as `all zipped up `, and a reply made only of such characters came back empty. A long reply could also corrupt such a character when streaming restarted its decode inside its bytes.
+- The Swift tokenizer library releases byte tokens only when a later token arrives. The provider's tokenizer bridge now releases a trailing run itself. `/detokenize` keeps it too.
+- Token IDs, numeric logprobs, sampling and cache keys do not change, with one exception: a stop string that a trailing run completes now matches when the run completes, one token sooner, so `completion_tokens` can fall by one.
+- A streamed reply's `logprobs` gains the entries of those tokens, which it used to drop. A byte token's `logprobs` text and `bytes` are U+FFFD or its ASCII character instead of empty, not the real byte. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it.
diff --git a/changelog.d/gemma-decode-command-buffers.md b/changelog.d/gemma-decode-command-buffers.md
new file mode 100644
index 0000000000..49963036d1
--- /dev/null
+++ b/changelog.d/gemma-decode-command-buffers.md
@@ -0,0 +1,3 @@
+### Gemma 4 plain decode commits by operation count
+
+- Plain decode steps of Gemma 4, the rows served without its assistant, commit a Metal command buffer every 100 operations instead of many times per step. Outputs are bitwise identical. Prefill and assistant rounds keep MLX's defaults.
diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md
new file mode 100644
index 0000000000..171b5279d8
--- /dev/null
+++ b/changelog.d/gemma-pipeline-speed.md
@@ -0,0 +1,5 @@
+### Faster Gemma 4 pipeline pairs
+
+- Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 370 ms to about 31 ms; pair throughput is not yet measured.
+- A Gemma 4 pipeline pair whose setup prefills serially, coordinator-registered pairs included, now serves four requests at once. Each lane is admitted against live memory on both Macs. A pair planned with the one-chunk lookahead keeps serving one request at a time.
+- The planner's hardware prior counts 8 of Gemma 4's 128 experts per token instead of every expert byte.
diff --git a/changelog.d/mimo-pipeline-decode-buffers.md b/changelog.d/mimo-pipeline-decode-buffers.md
new file mode 100644
index 0000000000..7f38c5d844
--- /dev/null
+++ b/changelog.d/mimo-pipeline-decode-buffers.md
@@ -0,0 +1,15 @@
+### MiMo pipeline decode command buffers and expert routing
+
+- MiMo V2.6 Flash pairs encode decode steps, lane steps and speculative rounds
+ in Metal command buffers of up to 100 operations with no input-size bound, as
+ GLM and Qwen tensor parallel already do. Prefill keeps the rank's limits.
+ Tokens, logits and caches are byte-identical on synthetic stages. The speed
+ effect on the registered model has not been measured yet.
+- A MiMo request's memory charge now prices every full-attention layer's decode
+ score rows at once, which the larger command buffers can keep alive together.
+ The LOAD quote is unchanged. Only requests whose prompt frames are shorter
+ than a stage's full-attention layers times the decode rows (32 tokens at most)
+ are charged slightly more.
+- The planner's hardware prior now counts MiMo's routed experts at the 8 of 256
+ a token uses: 10.77 GB read per decode step instead of 166.6 GB. The prior
+ prices only tensor parallel, so MiMo's pipeline plans are unchanged.
diff --git a/changelog.d/pipeline-decode-buffers.md b/changelog.d/pipeline-decode-buffers.md
new file mode 100644
index 0000000000..05582151fa
--- /dev/null
+++ b/changelog.d/pipeline-decode-buffers.md
@@ -0,0 +1,15 @@
+### Pipeline decode command buffers for the remaining cluster models
+
+- Cluster pairs of the Qwen and Bonsai rows, Nemotron 3.5 Lightning, Gemma 4,
+ GPT-OSS 20B and GLM-5.3-Flash encode decode steps (pipeline and phase split),
+ lane steps and speculative rounds in Metal command buffers of up to 100
+ operations with no input-size bound, as GLM and Qwen tensor parallel already
+ do. Prefill keeps the rank's limits. Tokens, logits and caches are
+ byte-identical on synthetic stages. The speed effect on registered models has
+ not been measured yet, and each family keeps the change only if a pair A/B
+ shows a gain.
+- A request's memory charge on those pairs, other than GLM's, now prices every
+ attending layer's decode rows at once, which the larger command buffers can
+ keep alive together. The LOAD quotes are unchanged. Only requests whose prompt
+ frames are shorter than their decode rows (at most 80) are charged more, and
+ only on a rank that decodes.
diff --git a/changelog.d/qwen27-tp-decode-control.md b/changelog.d/qwen27-tp-decode-control.md
new file mode 100644
index 0000000000..28d8a95e36
--- /dev/null
+++ b/changelog.d/qwen27-tp-decode-control.md
@@ -0,0 +1,22 @@
+### Qwen tensor-parallel decode control in the selection sum
+
+- A Qwen tensor-parallel pair's plain decode step now carries the next step's
+ plan and report in its own sealed selection sum, so the step pays one sealed
+ sum and one host read fewer than before. Tokens, logits and native state are
+ unchanged; assisted (MTP) rows, prompt steps and idle steps keep their own
+ exchange.
+- Owner answers, cancellations and joins now apply one step later while plain
+ rows decode. A row decodes its next token once the owner answered the token
+ before it, so an answer that arrives while a step computes no longer leaves
+ the row idle for a step. Rank 0 still publishes a token only after the
+ owner's answer to the one before it. A token selected before a stop answer is
+ never published, so streamed text, usage and logprobs are unchanged.
+- A clean stop the owner asks for (a stop string, for example) can cost one
+ more forward, which is discarded. On a one-lane pair every such stop after a
+ request's first token does (assisted rows excepted), and that request's
+ finish arrives one decode step later than before.
+- Both ranks of a pair must run this build: the load agreement binds the new
+ control wire (`qwen-tp-independent-history-batch-v2-folded-control`).
+- `darkbloom-cluster-tp-check qwen-decode` times the batch driver's decode on
+ two ranks over the loopback ring, with the control exchanged or folded, and
+ checks that both retire the same tokens.
diff --git a/changelog.d/qwen27-tp-default-lanes.md b/changelog.d/qwen27-tp-default-lanes.md
new file mode 100644
index 0000000000..beaec56878
--- /dev/null
+++ b/changelog.d/qwen27-tp-default-lanes.md
@@ -0,0 +1,20 @@
+### Qwen tensor-parallel pairs serve up to 8 requests at once, sized to memory
+
+- `darkbloom cluster` now sets how many requests a Qwen tensor-parallel pair
+ serves at once: 8, 6, 4 or 2, the most that both Macs' memory holds now with
+ the full load reservation for that many. The pair serves them from its first
+ load. Before, it served one at a time: a local pair widened only after a
+ burst, through a reload the burst waited for, and a pair serving Darkbloom
+ traffic never widened.
+- On two idle Macs, Qwen3.8-27B serves 8 at once from 64 GB a Mac without the
+ speculative assistant (4 at 48 GB, 2 at 32 or 36 GB), and 8 from 96 GB a Mac
+ with it (local clusters only); smaller Macs serve fewer. Two M5 Ultras serve 8 either
+ way. When not even 2 fit, the pair serves one request at a time, as before.
+- Memory safety is unchanged: both Macs reserve that many requests' full memory
+ when the model loads and admit each request alone. A local pair set up
+ narrower still widens when requests queue; a pair set up for 8 is never
+ reloaded for it.
+- Existing setups keep serving one request at a time until they are planned
+ again, as after an update. A pair serving Darkbloom traffic keeps its width
+ beside its approval; no approval, registration or committed-start digest
+ changes.
diff --git a/changelog.d/qwen27-tp-prefill.md b/changelog.d/qwen27-tp-prefill.md
new file mode 100644
index 0000000000..2f113dafb5
--- /dev/null
+++ b/changelog.d/qwen27-tp-prefill.md
@@ -0,0 +1,17 @@
+### Qwen tensor-parallel prompt wavefront
+
+- A Qwen tensor-parallel pair now prefills a text prompt faster, in steps of up
+ to eight consecutive 512-token frames built as one graph, layer by layer:
+ while one frame's sealed sum crosses the link, the next frame computes. Every frame
+ keeps its own shapes and kernels, so logits, KV, recurrent state, prefix
+ captures and tokens are unchanged. Steps run two frames while another lane
+ decodes and end at the prompt-cache capture point. Media prompts, assisted
+ (MTP) prompts, packed KV and routed-expert models keep one frame a step.
+- The merged step's frames in flight are charged in LOAD, the placement quote
+ and each request's charge: a Qwen3.8-27B tensor-parallel rank needs about
+ 367 MB more at any width.
+- `darkbloom-cluster-tp-check qwen-prefill --wavefronts 1,8` and
+ `darkbloom-cluster-tp-check qwen-wavefront` measure the merged steps on one
+ rank and on two ranks over the loopback ring.
+ `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` restores one frame a step for
+ diagnosis; both ranks must agree.
diff --git a/changelog.d/reasoning-stop-outside-reasoning.md b/changelog.d/reasoning-stop-outside-reasoning.md
new file mode 100644
index 0000000000..ce6d54f182
--- /dev/null
+++ b/changelog.d/reasoning-stop-outside-reasoning.md
@@ -0,0 +1,18 @@
+### Stop sequences no longer match Gemma 4 or `` reasoning
+
+- A client `stop` sequence on Gemma 4 models such as `gemma-4-26b-qat-4bit`,
+ and on models that reason in `` blocks (Qwen 3.5, 3.6 and 3.8,
+ among others), now matches only the text returned as `content`. With
+ reasoning on, it used to match the reasoning too, so a sequence that
+ appeared while the model reasoned (for example `"."` or `"\n\n"`) ended the
+ request before any answer: `finish_reason` `stop`, reasoning only, empty
+ content.
+- With tools declared, tool-call frames are not cut either, except a frame
+ whose arguments quote its own closing tag, or a bare `` frame
+ written without its wrapper. When a request has no tool handler (no declared
+ tools, or a media request on a family without native media tools), a literal
+ tool tag in an answer is text the client receives, and stops still apply to it.
+ Whitespace before the answer's first character (the blank line after
+ ``) cannot complete a stop sequence on its own.
+- A stop sequence that names a marker no longer fires on it: ``, or
+ `` with tools declared.
diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md
index 4a3146d8b8..2de1e19f36 100644
--- a/docs/architecture/hardware-support.md
+++ b/docs/architecture/hardware-support.md
@@ -1,6 +1,6 @@
# Hardware support and the provider memory model
-> Last updated: 2026-11-01
+> Last updated: 2026-11-02
What hardware the provider runs on and how it decides, in bytes, whether a
model may load and how much KV cache each resident model may use. Read this to
@@ -54,6 +54,21 @@ not waive LOAD or live-memory checks. See
`GPTOSSRequestStateBudget.estimate` in
`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift`.
+Pipeline decode steps of the Qwen catalog, Nemotron, Gemma 4 and GPT-OSS
+encode under decode command buffers that can keep a whole stage step's
+temporaries alive at once, so each request charge prices every attending
+layer's decode rows together (one a layer, or a verify window's `depth + 1`;
+every layer on a phase split's decoding rank, none on its other rank), and
+never less than one prompt frame's attention transient
+(`QwenResidentPrefillTransient`, `Gemma4PrefillTransient`,
+`GPTOSSRequestStateBudget`). The LOAD quotes and activation floors are
+unchanged; only requests whose prompt frames are shorter than their decode rows
+are charged more. GLM's request charge already prices three copies of twice its
+context on every DSA layer of a stage, well above what a decode step keeps and
+reads on every layer at once. Attention-kernel partials beyond the priced rows are
+not charged separately; see
+[pipeline decode command buffers](inference.md#pipeline-decode-command-buffers).
+
Optional Qwen plain-pipeline batch cancellation retains a lane's memory charge
until all its active and tentatively restored native sessions close. It then
releases only that lane, without changing other lanes' reservations or the
@@ -1050,6 +1065,10 @@ attention views and sliding repack storage. Keys and values are priced with
their distinct registered widths. Host prompt/selected-token histories and
shared native decode workspace remain additional. Both MTP target ranks price
the larger of the prompt chunk and the admitted `depth + 1` verification window.
+Every MiMo rank's workspace charge also prices each of its full-attention
+layers' score rows for the decode rows at once, because decode command buffers
+can keep a whole step in flight (`MiMoRequestStateBudget`, `decodeRows`;
+[MiMo pipeline decode command buffers](inference.md#mimo-pipeline-decode-command-buffers)).
The trained assistant preserves its whole previous allocation envelope and adds
separately rounded resident and working pages. Phase rank 1 prices every target
layer; both ranks retain the moving-state allowance during transfer. Image
@@ -1082,6 +1101,16 @@ full-artifact memory fit, numerical parity or throughput; those require
paired hardware qualification. The restore mechanism is described in
[inference](inference.md#gemma-paged-prefix-restoration).
+A serial-prefill Gemma 4 pipeline's default width
+(`DistributedInstalledPlan.gemma4PipelineBatchLanes`,
+[Gemma pipeline lanes](inference.md#gemma-pipeline-lanes)) adds no load-time
+allocation: the paged pool's capacity is a ceiling, and pages are reserved per
+request (`CBv2StageKVHost`). Each lane is charged its whole request state on
+every rank and admitted against live memory (`QwenResidentRuntime.reserveLane`);
+a lane the host cannot hold is refused alone, retryably. The measured
+activation floor still applies: prompt frames run one per step and decode rows
+add only M=1 work.
+
## Bonsai packed projection arithmetic
Bonsai 27B uses the [packed FP32 row path](inference.md#bonsai-27b-packed-fp32-rows)
@@ -1149,9 +1178,19 @@ projection constants and the transient batch conversion bank are charged
separately, including unequal shards. Paged backing charges each lane its own
BF16 page bank and partial-page replacement, and one full-history gather bank
once for the owner: decode steps and verify windows attend pages in place, and
-the driver runs at most one prompt frame per step, so only a prompt frame
-gathers a history (`QwenTensorParallelBatchMemoryTests.fullHistoryGatherIsOnePromptFramesTransient`
-measures both). Segment slack and allocator overhead stay charged. Collective scratch prices complete
+the driver runs one lane's prompt step at a time, so only a prompt step's frames
+gather a history (`QwenTensorParallelBatchMemoryTests.fullHistoryGatherIsOnePromptFramesTransient`
+measures both). A prompt step that merges frames
+([prompt wavefront](inference.md#qwen-tensor-parallel-prompt-wavefront)) adds
+its further frames in flight once to the shared maximum
+(`QwenTensorParallelPromptWavefront.inFlightBytes`: 367,001,600 bytes on a 27B
+rank at 512-token frames) and keeps at most
+`QwenTensorParallelPromptWavefront.sumsInFlight` sums unfinished. Over the
+loopback ring (`darkbloom-cluster-tp-check qwen-wavefront`, 4-layer shards at
+the 27B's per-rank widths, 11,264-token prompts and a 65,536-token context) a
+merged step's peak rose at most 314 MB a rank above one frame's; without that
+bound it rose 0.5-1.5 GB. `QwenTensorParallelPromptWavefrontTests.mergedStepTemporariesStayWithinTheirCharge`
+checks the term in one process, whose sums complete as they are built. Segment slack and allocator overhead stay charged. Collective scratch prices complete
sealed frames, including authentication overhead, through the existing request
allowance. Media and assistant charges are not hidden in this text quote.
@@ -1193,7 +1232,10 @@ a rank reserves it ([native context](inference.md#qwen27-tensor-parallel-native-
the shard, two whole host tensors, aligned-read scratch and loading headroom.
The placement and shard assessment add it to the LOAD peak and allocator ask;
resident and request phases are not substitutes for that simultaneous peak.
-No native gate or headroom threshold is reduced. Both ranks must fit current
+No native gate or headroom threshold is reduced. Initial placement saves the
+widest of these widths at which both ranks fit current observations, with
+nothing credited ([saved width](inference.md#qwen-tensor-parallel-saved-width)).
+Both ranks must fit current
observations before replacement is proposed (crediting at most the running
owner's resident weights on that Mac, and only for a replacement with the same
split) and again after previous ownership releases, with nothing credited. Source-bound metadata and child-launch checks establish budget and
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index 9d40490161..bf47946298 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -1,6 +1,6 @@
# Provider inference engine
-> Last updated: 2026-11-01
+> Last updated: 2026-11-03
How a chat-completion request is served inside the `darkbloom` provider
process: one in-process engine (`mlx-swift-lm`
@@ -57,6 +57,20 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/DistributedR
`provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledSession.swift`,
and `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation+PairServing.swift`.
+The cluster request engine owns one serial queue. Every stream `yield` and its
+retirement latch resume their tasks from it, and resuming a task needs that
+task's status lock. Task cancellation holds the same lock while its handlers
+run. So the engine never waits for its queue from a cancellation path: a
+request stream's `onTermination` and the admission cancellation hop onto the
+queue without waiting, or run in place when already on it. The retirement task
+never blocks a cooperative thread. Waiting there deadlocked a pair slot's
+retirement: `EngineV2Bridge.shutdown` cancelled a pump while the queue
+published that request's peer loss. Lease events, the owner's invalidation and
+the public calls keep their synchronous queue order. Source:
+`provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift`
+(`onQueueWithoutWaiting`) and
+`provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift`.
+
The cluster setup liveness probe uses the same request validation as ordinary
chat completions. `ClusterSetupProbeRequest` sends no family-specific thinking
override, so each modelβs prompt policy remains authoritative.
@@ -77,7 +91,10 @@ assistant media remain unsupported; legacy model ingestion is unchanged. Sources
## Automatic local cluster batching
-`DistributedAutomaticBatchFactory` keeps the initial singleton placement. A
+`DistributedAutomaticBatchFactory` keeps the initial placement and its saved
+width; a Qwen TP placement already saves the widest width both Macs admit
+([saved width](#qwen-tensor-parallel-saved-width)), so it proposes only a
+wider one (`DistributedAutomaticBatchFactory.replacementWidths`). A
managed cluster API with queued demand may propose a wider plain pipeline for
Qwen dense/routed experts, Bonsai, Nemotron Lightning, Gemma, GPT-OSS or the
MiMo text plain-pipeline owner. Every Qwen TP row (the 9B and 27B dense rows,
@@ -123,7 +140,10 @@ never negative), `rankN_weights_bytes`, `rankN_fit` and `rankN_device`.
Existing per-request
admission and LOAD safeguards remain authoritative. GLM, private-image and
coordinator-installed native-member sessions do not use this
-automatic policy. Explicit diagnostic mode or lane settings retain their choice.
+automatic policy. A serial-prefill Gemma 4 pipeline, coordinator-installed or
+local, starts at its installed default width
+([Gemma pipeline lanes](#gemma-pipeline-lanes)); on a local pair this policy
+can still widen it. Explicit diagnostic mode or lane settings retain their choice.
Automatic replacement reads the installed plan helper's device profile and the
current pair's recorded keyed-link costs and served-request history. It uses
@@ -1086,7 +1106,7 @@ threadgroup per page, with no zero fill, and a selection read copies each row
with one SIMD-group (`GLM5NextPagedTransfers`). Plain decode steps (every row
one token) and MTP rounds whose rows are all decode or verification rows (at
most 8 tokens) commit a Metal command buffer every 100 operations with no
-input-size bound, as Nemotron Super and Flint do for plain decode
+input-size bound, as Nemotron Super, Flint and Gemma 4 do for plain decode
(`GLM5NextDecodeCommandBuffers`); prefill chunks keep MLX's defaults. A longer
row whose selection rows would read at least
its history instead reads its whole latent plane once per layer through
@@ -1558,6 +1578,15 @@ submits the frame. `SendHandle` and `ChunkSender` persist across reconnects,
so an old request's frame processed after a replacement sink binds still
passes this check; it does not enforce request-to-session identity.
+Decoded text keeps a character the tokenizer writes as `<0xHH>` tokens wherever it
+falls. swift-transformers' `ByteFallbackDecoder` releases those tokens only when a
+later token arrives, so a decode ending in them drops them and shows nothing pending.
+Gemma 4 writes characters outside its vocabulary this way, so `LocalTokenizerBridge.decode`
+(`provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift`)
+releases a trailing run itself. A partial run reads as U+FFFD, which `DetokenizerV2`
+holds back, so its segment restart cannot land inside a character. A decoder that
+spells or releases these tokens turns this off.
+
The chat template is rendered on every request. When caching is enabled for
the request, `LocalTokenizerBridge` encodes the rendered prompt through
`PromptTokenCache` (`provider-swift/Sources/ProviderCore/Inference/Prompting/PromptTokenCache.swift`):
@@ -2142,7 +2171,7 @@ disabled for this hybrid model.
| `logit_bias` | `logitBias` β string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` |
| `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` |
| `max_tokens` | `maxTokens = max_tokens ?? 4096` | 4096 |
-| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match; the reported sequence replays the same scope (`EngineV2Bridge+StopSequence.swift`) | `[]` |
+| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning spans per request instead, starting inside reasoning when the prompt opened a think block, and their tool-call spans when the request parses tool calls (`ReasoningStopScope`). Otherwise a literal tool tag in an answer is text the client receives, so stops still apply to it. The native block engine (diffusion Gemma) matches the whole output, so its requests carry no scope. The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` |
| `min_p` | `minP`, forwarded by `EngineV2Bridge.submitTokenized` after translation | `0` |
| `priority` | **Ignored**: always `0` | β |
| `n`, `best_of` | **Not represented**: one alternative | β |
@@ -3076,7 +3105,8 @@ step boundaries; a lane without its answer cannot run another forward. The
leader still exchanges headers and replies when no lane can advance, with
`role.none` and no model work. This lets the follower admit a joining request
while the provider's synchronous reservation is holding the queue needed to
-answer an older token. The installed lane default stays one; multi-lane
+answer an older token. The installed lane default stays one, except for a
+serial-prefill Gemma 4 pipeline ([Gemma pipeline lanes](#gemma-pipeline-lanes)); multi-lane
sampling, joining and native output equivalence require separate qualification
(`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Batch/QwenBatchDecisionProgress.swift`,
`QwenResidentRuntime.leadBatch`).
@@ -3127,7 +3157,8 @@ the worker's pending acknowledgment
Native, installed-owner and qualification gates enable independent retirement
only for the existing Qwen-family lane adapters in plain pipeline with 2...8
-lanes (installed image candidates are excluded). The default stays one. Other
+lanes (installed image candidates are excluded). The default stays one, except
+for a serial-prefill Gemma 4 pipeline ([Gemma pipeline lanes](#gemma-pipeline-lanes)). Other
modes retain their existing failure policy, and GLM tensor-parallel retirement
and its eight-lane default are unchanged. A cancellation racing an already
finishing lane retains the existing clean-finish linearization: native state
@@ -4145,6 +4176,84 @@ The GLM finite-calibration adapter samples each Mac locally and reuses `GLM5Next
The installed run command recomputes the decision from both snapshots, binds it to the unchanged local template, and then invokes the existing signed quotation/owner path with the chosen cut. Local and peer quotes must still agree, and current-device/load/reserve/start checks retain authority. Public endpoint activation, automated calibration scheduling and a MiMo adapter for this exact-quote seam are separate integrations.
+## Pipeline decode command buffers
+
+The pipeline stages of the Qwen catalog (dense, routed-expert and Prism rows),
+Nemotron, Gemma 4, GPT-OSS and GLM encode decode work as GLM's and Qwen's
+tensor-parallel decode do: up to 100 operations a Metal command buffer with no
+input-size bound (`QwenLayerStageSession.decodeCommandBuffers`), on the thread
+that encodes it. The rank's own limits are the worker's 16-operation guard
+(`ClusterWorkerEnvironmentGuards`) and MLX's per-chip size bound, which counts
+the distinct input elements of a buffer: a routed-expert launch takes a whole
+expert bank as input, and banks above the bound (the 35B A3B rows, Nemotron,
+Gemma 4 and GLM) commit a buffer at every launch. Prefill frames keep the
+rank's limits. MiMo's pipeline is not covered here.
+
+| Work | Where the limits apply |
+|---|---|
+| Plain and compact decode frames, phase-split and alone-route decode (Qwen catalog, Nemotron, Gemma 4) | `QwenLayerStageSession.decode` |
+| Lane steps | `QwenLayerStageSession.decodeBatch` |
+| `pipeline_mtp_v1` rounds: drafts, verify windows on both ranks, settlement | `QwenPipelineMTPGeneration.runProducer`, `QwenPipelineMTPGeneration.runConsumer` |
+| `phase_split_mtp_v1` rounds on the decoding rank | `QwenMTPDecoder.step` |
+| GPT-OSS decode frames and lane steps | `GPTOSSLayerStageSession.decode`, `GPTOSSLayerStageSession.decodeBatch` |
+| GLM decode frames | `GLM5NextStageSession.forward`, decode phase only |
+
+Only the commit points move: every kernel, input and rounded value is the same,
+so load agreements and arithmetic contracts are unchanged.
+`PipelineDecodeCommandBufferTests` compares every output row, verify window and
+cache or state array byte for byte under each family's guard and under the
+decode limits, on synthetic stages.
+
+MLX keeps up to ten command buffers in flight (`MLX_MAX_ACTIVE_TASKS`) and frees
+a buffer's temporaries when it completes, so under the decode limits a whole
+stage step's temporaries can be alive at once. Each request charge therefore
+prices every attending layer's decode rows together, and never less than one
+prompt frame's:
+
+| Family | Charge | Decode rows priced together |
+|---|---|---|
+| Qwen catalog, Nemotron | `QwenResidentPrefillTransient.bytes` (`decodeRows`), from `QwenResidentRequestAllowance.derive` | One a layer, or the verify window's `depth + 1` (`LayerStageDecodeShape`), on the rank's stage; on every layer on a phase split's decoding rank; none on its other rank, which hands its prompt state over |
+| Gemma 4 | `Gemma4PrefillTransient.bytes` (`decodeRows`, `decodeLayers`) | One on each layer of the stage, sliding layers over their window |
+| GPT-OSS | `GPTOSSRequestStateBudget` workspace | One a full-attention layer |
+| GLM | Unchanged (`GLM5NextRequestStateBudget.estimate`): every DSA layer of the stage is charged three float32 copies of twice the context the request is charged for, and every request the conservative 5.5 GiB workspace | None added: a step's pages and reads on every layer at once stay well inside that charge (below) |
+
+The LOAD quotes are unchanged: they are computed at the largest prompt chunk,
+512 rows, and a decode step prices at most 80 rows (5 on each of 16 attending
+layers; one on each of Gemma's 30). Only requests whose prompt frames are
+shorter than their decode rows are charged more, and only on a rank that
+decodes. The rows are priced as float32 score rows over the whole context.
+The Qwen, Nemotron and Gemma 4 stages keep their keys and values in the paged
+stage KV (`CBv2StageKVHost`). There, decode steps, lane steps and verify
+windows (one decode row a window column, `CBv2OwnedRequestState.buildingWindow`)
+attend through the paged decode kernel (`PagedAttentionKernel.decode` in
+`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionKernel.swift`).
+Its float32 partials take `heads Γ ceil(keys / 256) Γ (head width + 2) Γ 4`
+bytes a row: about one score row at head width 256, two on Gemma's full layers
+(width 512) and half on Nemotron's (width 128, whose charge prices only the
+output). GPT-OSS attends through MLX's attention, whose vector kernel on Max
+and Ultra GPUs at 1,024 keys or more keeps float32 partials that exceed a score
+row by at most about 4 MiB a layer (`sdpa_vector_2pass` in
+`libs/mlx-swift/Source/Cmlx/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp`).
+The excess over the priced rows is not charged; [INFERENCE] it is at most tens
+of MiB a request, times the lanes.
+
+GLM needs no decode term. Each DSA layer of a GLM stage is already charged
+three float32 copies of twice its context
+(`GLM5NextRequestStateBudget.HistoryBound.geometric`: 18,438 bytes a token at
+the registered widths). A decode step keeps that layer's history in bfloat16
+pages (1,537 bytes a token) and reads at most one gathered copy of it, only the
+index planes (513 bytes a token) once the history passes 4,102 tokens, so every
+layer's reads alive at once stay well inside the term at any context. The rest
+of a step, mostly each linear-attention layer's next 4.4 MB state, is inside the
+conservative 5.5 GiB workspace every request is charged
+(`GLM5NextServingResources.workspaceNativeBytes`). On a synthetic stage at the
+registered widths (three DSA and three linear-attention layers, bfloat16
+pages), a decode step held 16 MB above its baseline at a 20-token context and
+136 MB at 65,520 tokens of history, the same under these limits as with the
+whole step in one buffer (131 MB under the rank's guard), against 6.0 and
+11.1 GB charged at those contexts. The decode speed effect and peak memory on
+registered models are not measured yet.
+
## GLM cluster prefill bounds
The registered NVFP4 GLM cluster candidate admits a maximum prefill chunk of
@@ -4575,7 +4684,9 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Meta
one-token requests. Ordinary affine 4/8-bit group-64 projections retain native
matmul `M=1` through leading weight views; custom and floating modules retain
their original per-request forward method. The unscaled value RMS reduction
-and each routed expert operation retain singleton request shapes as well.
+retains singleton request shapes. The rows' routed experts share one call
+that keeps each row's singleton bytes
+([Gemma prompt projection reductions](#gemma-prompt-projection-reductions)).
The scope owns no cache, changes no shared MLX dispatcher, and is disabled for
singletons, prefill and speculative rectangles.
@@ -4596,6 +4707,40 @@ and leaving/rejoining rows. Their CPU checks require identical native logits
and all live KV values. This is not full-artifact GPU, pair or throughput
qualification; those checks remain required.
+### Gemma pipeline lanes
+
+A Gemma 4 pipeline whose saved setup prefills serially serves
+`DistributedInstalledPlan.gemma4PipelineBatchLanes` (4) requests at once,
+coordinator-registered pairs included. Every other pipeline lane adapter keeps
+the default of one (`DistributedInstalledPlan.defaultBatchLanes`). A saved
+width or the owner's `DARKBLOOM_CLUSTER_BATCH_LANES` still overrides the
+default.
+
+| Property | Basis |
+|---|---|
+| A lane costs no request its own tokens | Decode rows keep their one-request arithmetic ([batch decode](#gemma-ordinary-batch-decode-arithmetic)); each prompt frame runs alone on its request's own chunk grid (`QwenBatchSettings`) |
+| Memory | No load-time allocation; each lane is admitted against live memory and the activation floor is unchanged ([Gemma paged cluster lanes](hardware-support.md#gemma-paged-cluster-lanes)) |
+| Cancellation | A cancelled lane retires alone (`DistributedInstalledPlan.lanesRetireAlone`) |
+| One-chunk lookahead | Lanes prefill serially, so a setup that saved `one_chunk_lookahead_v1` keeps its schedule and one lane, as a planned batch width requires serial prefill (`ClusterConfiguration`) |
+
+Both owners derive the width from the same saved setup and bind it into the
+load agreement (`Gemma4BatchArithmeticAgreement`). The width is not qualified
+on hardware: multi-lane joining, cancellation and output agreement on the
+real pair remain separate checks, as for every pipeline lane adapter.
+
+### Gemma routed-expert prior
+
+`Gemma4PlacementFamily` states that every layer routes a token to 8 of its 128
+experts (`expertRouting`, from `Gemma4StageGeometry`) and names the
+`experts.switch_glu` banks as routed experts (`isRoutedExpert`). Gemma layouts
+therefore carry `routedExperts`: 12,846,366,720 bytes for the QAT 4-bit
+artifact and 24,265,359,360 bytes for the 8-bit one. The hardware prior
+(`ClusterHardwarePrior.decodeBytesPerToken`) counts 2,424,219,708 weight bytes
+per QAT 4-bit token instead of every layer byte. The golden pipeline plans
+keep their cuts and modes; the prior feeds the device-index and
+tensor-parallel share estimates (`ClusterHardwarePrior.absolute`,
+`ClusterDecodeSplit`).
+
### Qualification records for identical catalog files
The plain `gemma-4-26b` and `gemma-4-26b-8bit` catalog entries have identical
@@ -4901,6 +5046,53 @@ a rewind reserve or another layout. Code: `libs/darkbloom-cluster/Sources/Darkbl
`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Prefix/MiMoStagePrefixSnapshot.swift`
and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoWindowRollback.swift`.
+### MiMo pipeline decode command buffers
+
+MiMo stage decode encodes its Metal command buffers as GLM's and Qwen's
+tensor-parallel decode do: up to 100 operations a buffer with no input-size
+bound (`MiMoLayerStageSession.decodeCommandBuffers`), on the thread that encodes
+the step. The rank's own limits are the worker's 16-operation guard
+(`ClusterWorkerEnvironmentGuards`) and MLX's per-chip size bound, and each
+routed layer's expert launch takes a whole 1 GiB expert bank as input, so under
+those limits a decode step commits a buffer every few launches. Prefill frames
+keep the rank's limits.
+
+| Work | Where the limits apply |
+|---|---|
+| Plain and compact decode frames, phase-split and alone-route decode | `MiMoLayerStageSession.decode` |
+| Lane steps of independent histories | `MiMoLayerStageSession.decodeBatch` |
+| Speculative rounds of `pipeline_mtp_v1`: drafts, verify windows, settlement | `MiMoMTPGeneration.runProducer`, `MiMoMTPGeneration.runConsumer` |
+
+Only the commit points move: every kernel, input and rounded value is the
+same. `MiMoDecodeCommandBufferTests` compares residuals, logits rows and every
+cache and page array byte for byte under both limits on synthetic stages.
+
+MLX keeps up to ten command buffers in flight (`MLX_MAX_ACTIVE_TASKS`) and frees
+a buffer's temporaries when it completes, so under the decode limits a whole
+stage step's temporaries can be alive at once. A request's workspace charge
+therefore prices every full-attention layer's float32 score rows for its decode
+rows together (`MiMoRequestStateBudget.estimate`, `decodeRows`: one row, or the
+verify window's `depth + 1`), and never less than one prompt frame's scores on
+one layer. Gathered page views are already charged for every layer
+(`MiMoPagedKVAllowance.pages`). A verify window of three or four rows takes
+MLX's unfused path, which builds those scores in bfloat16. One or two rows take
+its fused vector attention instead, whose
+float32 partials on Max and Ultra GPUs (`sdpa_vector_2pass` in
+`libs/mlx-swift/Source/Cmlx/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp`)
+can exceed a score row and are not priced separately. The decode speed effect
+and peak memory on the registered model are not measured yet.
+
+### MiMo routed experts in placement
+
+`MiMoPlacementFamily` states MiMo's routing: each of the 47 routed layers sends
+a token to 8 of its 256 experts (`expertRouting`). Its routed-expert tensors are
+each layer's `mlp.switch_mlp` banks and their block scales (`isRoutedExpert`).
+The router and its score correction are read on every step. The layout then
+carries `routedExperts`, and the hardware prior
+(`ClusterHardwarePrior.decodeBytesPerToken`) counts 10,767,036,288 bytes for one
+decode step instead of every expert's 166,600,109,952. The prior prices tensor
+parallel only, so MiMo's pipeline plans are unchanged.
+
### Gemma paged prefix restoration
Installed plain Gemma pipelines retain the paged KV default at every supported
@@ -4994,17 +5186,33 @@ packed weights; it adds no persistent weight copy. Query/key/value, output,
shared MLP and router projections use their existing model call sites. Norms,
the vocabulary head, independent decode lanes and singleton frames retain
their existing operations.
-The same explicit prompt scope invokes each BF16 token's complete expert block
-with its unchanged selected indices and weights. This preserves singleton
-GeGLU and weighted reduction rather than entering a wide sorted expert graph;
-ordinary SDK prompts and speculative verification keep their existing paths. Custom modules, other dtypes/packing, and ordinary
-SDK callers retain the original forward method.
+The same explicit prompt scope keeps each BF16 token's complete expert block
+at one token: its unchanged selected indices and weights, an M=1 gathered
+product per selected expert, singleton GeGLU and its own top-K weighted
+reduction, rather than a wide sorted expert graph. All tokens of a frame share
+one call (`SwitchGLU.callAndWeightedReduceRows`). It groups their assignments
+by expert for weight locality but does not give the gathers the sorted hint, so
+every pair keeps the unsorted M=1 route. MLX picks `gather_qmv` and its variant
+from the quantization, dtype and the N and K widths, never from the row count.
+The rows return to token order before
+the top-8 reduction, whose `col_reduce_small` thread layout depends only on the
+hidden width. Each token's bytes therefore equal those of its own one-token
+call. The tokens share one dispatch per operation instead of about six per
+token per layer. Independent decode rows use the same call
+([Gemma ordinary batch decode arithmetic](#gemma-ordinary-batch-decode-arithmetic)).
+Ordinary SDK prompts and speculative verification keep their existing paths.
+Custom modules, other dtypes/packing, and ordinary SDK callers retain the
+original forward method.
The exact Gemma arithmetic receipt binds both prompt projection and expert
reduction policies before LOAD, separating prior rectangular-projection cache and plan identities. The
stable family policy identifier and required environment flags remain the same.
+The shared expert dispatch changes no byte, so the receipt and the cache
+identities it separates are unchanged.
Component byte equality is separate from full-model two-chip numerical
-qualification, and the M=1 prompt graph requires its own throughput measurement.
+qualification. The M=1 prompt graph still needs a pair throughput measurement;
+the synthetic component timings are in
+[Gemma pipeline prompt experts](../reports/2026-11-01-gemma-pipeline-prompt-experts.md).
The SDK helper is
`libs/mlx-swift-lm/Libraries/MLXLLM/Models/Gemma4PrefillProjection.swift`;
stage activation and receipt binding are in
@@ -5134,8 +5342,9 @@ prerequisite does not advertise media support or activate a native model path.
Every registered Qwen TP row (the 9B and 27B dense rows, the Qwen3.5 and Qwen3.6
35B A3B routed-expert rows) serves request-owned lanes on main's paged KV host
-(`CBv2StageKVHost`) at every capacity, one through eight; the default remains
-one, and one lane is the same path one lane wide (the singleton wire adapts to
+(`CBv2StageKVHost`) at every capacity, one through eight; a setup saved without
+a width serves one ([saved width](#qwen-tensor-parallel-saved-width)), and one
+lane is the same path one lane wide (the singleton wire adapts to
the shared driver, `QwenTensorParallelSingletonHost`). The former single-lane
owner (request-local caches on its own page pool and the
`DARKBLOOM_CLUSTER_QWEN_TP_PAGED_KV` switch, with its own prefix cache) is
@@ -5160,9 +5369,10 @@ A decode step is submitted while it is built. `QwenTensorParallelBatchSession`
decodes under `Qwen35LayerSubmission` with a stride of one layer
(`decodeLayerStride`): after each decoder layer the forward submits what it has
built (`asyncEval`), so that layer's kernels and collectives run while the host
-builds the next. The driver plans a step only after the previous step's tokens
-are known, so the request-owned path cannot build one step ahead as the retired
-single-lane loop did; submitting by layer hides the graph build instead.
+builds the next. The driver builds a step only after the previous step's tokens
+are read (a plain step's plan is made before them, below), so the request-owned
+path does not build one step ahead as the retired single-lane loop did;
+submitting by layer hides the graph build instead.
Speculative verify windows are evaluated whole instead
(`QwenTensorParallelTargetWindow.submitsByLayer` off): with the main-merged MLX
core, an `asyncEval` after every layer of a window cost a solo 27B request on two
@@ -5214,8 +5424,9 @@ them; an installed worker always uses the defaults), and
microseconds). `darkbloom-cluster-tp-check qwen-prefill` measures one rank's
prompt frames, layers and projections with no peer.
-The driver coordinates join, one prefill frame and a decode cohort on both
-ranks. A held token credit blocks only its request. When some decode rows are
+The driver coordinates join, one prompt step (one frame, or several merged:
+[Qwen tensor-parallel prompt wavefront](#qwen-tensor-parallel-prompt-wavefront))
+and a decode cohort on both ranks. A held token credit blocks only its request. When some decode rows are
ready and others await nearby owner acknowledgments, the driver reuses
`QwenBatchDecodeCoalescing`'s absolute 2,000,000-nanosecond window. It keeps
exchanging no-work steps and servicing control; new joins, prefills and retirement
@@ -5242,10 +5453,53 @@ another length. The decode step pays no separate finiteness read
(`QwenTensorParallelBatchSession.validateLogits` checks shape and dtype), and
every selected token is unchanged.
+A plain decode step carries the next step's control in its selection sum
+(`QwenTensorParallelBatchDriver.serve`). When every row of the rectangle selects
+plainly (`QwenTensorParallelBatchLane.plainSelection`: no assistant) and no
+prompt step follows it in the step, rank 0 makes the next plan and rank 1 its
+report once the forward committed (the executor's `decode` `control` closure),
+and both ride the selection's own sealed sum: after a greedy cohort's six words
+a row, or after a sampled cohort's choices (its gathered rows keep their own
+sum). Such a step pays one sealed sum and one host read instead of an exchange
+and a selection. A step after a prompt, idle or assisted step exchanges its
+plan as before, and so does every step of an executor whose selection sum
+carries no control words (`carriesSelectionControl` false, the protocol's
+default; the Qwen native executor's is true). The plan is made before the step's tokens are known, so:
+
+- A row that decodes on the token being selected names
+ `QwenTensorParallelBatchWire.carriedToken`. Both ranks take the token from the
+ same sum, and both drop that decode when the token ended its request (a stop
+ token or the output count).
+- Host events (owner answers, credits, cancellations, joins) apply one step
+ later: rank 0 polls them while it makes the next plan, after the forward and
+ before the tokens are read. A row may decode on its newest token once the
+ owner answered "go on" to the token before it, and rank 0 publishes a token
+ only after that answer: at its selection, or at the poll that brings the
+ answer (a row holds at most one unpublished token).
+- A stop answer that arrives after the row selected one more token keeps the
+ tokens the owner saw. Rank 0 never publishes that token, both ranks drop it
+ (the leaving slot carries the kept count), and the native finish counts one
+ discarded forward (`QwenTensorParallelNativeBatchExecutor.retire`). The
+ one-lane wire answers each token as it is published, after the next forward
+ was planned, so there a client stop to any token a plain decode step selected
+ runs one discarded forward, and the request's finish follows that forward.
+ Usage and logprobs cover the kept tokens only; prefix captures and SSD
+ records hold prompt states, which no decode forward changes.
+
+The load agreement binds the wire version
+(`qwen-tp-independent-history-batch-v2-folded-control`), so a rank of an
+earlier build refuses to load. Tokens, logits and native state are unchanged:
+the control limbs are exact in FP32, each element of the sum is added alone,
+and the collective payload quote covers the longer frame
+(`QwenTensorParallelBatchBudget`). `darkbloom-cluster-tp-check qwen-decode`
+(`QwenTensorParallelDecodeBench`) times the driver's decode on two ranks over
+the loopback ring with the control exchanged or folded and checks that both
+retire the same tokens.
+
The batch path can restore mutually held original-grid prefix snapshots into
fresh request-owned state. TP speculative rounds remain a separate integration. Installed owners propagate a priced
-saved width or explicit diagnostic width for every Qwen TP row; automatic placement
-uses the separate full native TP quote described above. A row that may also run
+saved width or explicit diagnostic width for every Qwen TP row; placement and automatic
+replacement use the separate full native TP quote described above. A row that may also run
the pipeline prices tensor parallel with its singleton quote and keeps the
pipeline modes as candidates (`ClusterPlacementTensorBatchQuote.applySingletonCandidate`);
the 27B, whose features keep it in tensor parallel, and an assistant quote bind the
@@ -5301,12 +5555,193 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Ten
`libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift`
(`QwenRowsCheck`),
`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift`
-(`serve`, `makePlan`, `join`, `leave`),
+(`serve`, `makePlan`, `resolve`, `publishHeld`, `join`, `leave`),
+`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift`
+(`QwenTensorParallelBatchWire`),
+`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift`
+(`decode`, `select`, `retire`),
+`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift`
+(`QwenTensorParallelDecodeBench`),
+`libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift`
+(`QwenDecodeCheck`),
`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Batch/QwenBatchDecodeCoalescing.swift`
(`shouldDefer`), and
`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift`
(`serveBatch`, `prepareBatch`).
+### Qwen tensor-parallel saved width
+
+Guided placement saves each Qwen TP pair's width (`batchLanes`), so the pair
+serves concurrent requests from its first load. Before, such a setup saved no
+width and served one request at a time: a local pair widened only through a
+drained replacement, which the first burst waited for, and a pair saved for
+coordinator pairing never widened.
+
+1. The guided setup (`ClusterSetupWizardLiveOperations`, which the onboarding
+ and the six-step wizard share) reads the owner's complete quote at widths 2,
+ 4, 6 and 8 (`ClusterPlacementTensorAssistantSelection.readAutomatic` with
+ `lanes`), each for the singleton quote's own request envelope and assistant.
+2. The placement is chosen as before, from the singleton quote: mode, leader,
+ split and reference request (`ClusterPlacementFlow.decide`).
+3. `ClusterPlacementTensorWidth.widest` prices that placement, leader and split
+ unchanged, at 8, 6, 4 and 2 in turn, with each width's quote in place of the
+ singleton's (`ClusterPlacementTensorBatchQuote.applyWidth`), and saves the
+ first that both Macs admit now. The predicate is the one an automatic
+ replacement is held to (`ClusterPlacementCandidate.admitted`): possible,
+ inside the GPU working set, and every rank within what its Mac admits now.
+ The plan then reports that width's memory and keeps the reasons its mode was
+ chosen for one request, including a row's comparison with the pipeline
+ where the pipeline stays a candidate. When no width fits, the setup saves
+ none and serves one request at a time, as before.
+4. LOAD quotes, measured floors and live admission are unchanged. Both ranks
+ reserve the saved width's complete quote at LOAD and admit each request
+ alone.
+
+A typed assistant policy (the developer wizard) and `darkbloom cluster plan`
+read no width quotes and save no width.
+
+A pair saved for coordinator pairing keeps its width for the life of the
+setup. The width is a field of each Mac's saved setup only. The approval, the
+roster registration, the committed native start and the release's runtime
+facts name no width, so no approval digest changes. The approval is saved
+beside the width unchanged (`ClusterApprovalAttachment`), and both workers bind
+the width in their sealed load agreement. Automatic replacement never plans for
+an approved setup (`DistributedAutomaticBatchPlanner.snapshot`). A re-plan,
+after an update or a refused load, sizes the width again on the memory then.
+
+On a local pair, queued demand still proposes a width wider than the saved one
+through a drained replacement: the fallback for Macs that admitted a narrower
+width when planned. A pair saved at eight is never drained.
+
+The widths the registered Qwen3.8 27B saves on idle pairs (its retained
+headers and LOAD's own quotes, the vision tower's resident bytes aside as in
+the served layout; `ClusterPlacementTensorWidthRegisteredTests`):
+
+| Each Mac | Without the assistant (served through Darkbloom) | With the depth-3 assistant (local) |
+|---|---|---|
+| 32 GiB | 2 | 1 |
+| 36 GiB | 2 | 1 |
+| 48 GiB | 4 | 2 |
+| 64 GiB | 8 | 4 |
+| 96 GiB and larger | 8 | 8 |
+
+At eight lanes, each rank of an equal split reserves 40,911,618,048 bytes at
+LOAD without the assistant and 60,734,767,104 bytes with it, each lane's
+prompt-prefix capture ([prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership))
+and the shared 367,001,600-byte prompt wavefront term
+([prompt wavefront](#qwen-tensor-parallel-prompt-wavefront)) included; with its
+weights and loading headroom it needs 54,441,306,624 and 77,998,565,888 bytes.
+Every
+registered Qwen TP row is sized the same way from its own quotes. GLM keeps its
+eight lanes and other families keep their defaults.
+
+Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift`
+(`ClusterPlacementTensorWidth`),
+`provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift` (`decide`) and
+`libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift` (`applyWidth`).
+
+### Qwen tensor-parallel prompt wavefront
+
+A Qwen TP prompt frame of 512 rows used to compute, then wait for its own
+sealed FP32 sums: two per layer, each read by the next residual norm, so the
+GPU and the link took turns. On the pair at 11K tokens a 27B frame computes for
+about 165 ms and its 128 sums take about 186 ms, so prefill ran at 0.75x one Mac
+[INFERENCE: split from `qwen27-tp-speed-plan` measurements, not traced]. A plain
+text lane now prefills up to eight consecutive frames as one graph, built layer
+by layer as GLM's micro-batches are (`GLM5NextTextStage.microBatchedLayer`): a
+frame's mixer through its row-parallel output projection, that sum submitted at
+once, the next frame's mixer while it crosses; then each frame's MLP the same
+way.
+
+```mermaid
+flowchart LR
+ subgraph Layer["layer L of a step of frames f0..f7"]
+ M0["f0 mixer partial"] --> S0(["f0 sealed sum"])
+ M0 --> M1["f1 mixer partial
(reads f0's KV and
conv/SSM state at L)"]
+ M1 --> S1(["f1 sealed sum"])
+ M1 --> Mn["... f7 mixer"]
+ S0 --> F0["f0 residual + MLP partial"] --> T0(["f0 sealed sum"])
+ S1 --> F1["f1 residual + MLP partial"]
+ end
+```
+
+- **Planning.** The leader plans one prompt step a driver step: up to
+ `QwenTensorParallelPromptWavefront.maximumFrames` (8) frames, or
+ `framesBesideDecoding` (2) while another lane decodes, ending at the prompt's
+ end or at the lane's capture frontier (`QwenTensorParallelBatchSession.promptFrames`).
+ The plan carries the step's offset, tokens and final flag; each rank runs it
+ only as a prefix of its own frames (`promptStep(tokens:)`), so both ranks run
+ the same frames.
+- **Graph.** One `CBv2OwnedRequestState.run` covers the step.
+ `Qwen35PromptWavefront.prefill` builds each layer for every frame in two
+ phases (`Qwen35DecoderLayer.promptMixer`, `promptFeedForward`). A frame reads
+ the attention rows the frame before it wrote at that layer (the cache's
+ advanced offsets, the prefill mirror or the page gather) and its recurrent
+ state (`Qwen35GatedDeltaNet.cbv2Recurrent`); the last frame's state is staged
+ into the run's evaluation. The prompt's last frame takes `cbv2Forward`'s fused
+ residual norms and whole-frame head, as alone. After each phase the raw sums
+ the row-parallel projections issued (`QwenTensorParallelRowLinear.issuedSums`)
+ are submitted (`asyncEval`), and building waits while more than
+ `QwenTensorParallelPromptWavefront.sumsInFlight` (4) are unfinished. Without
+ that bound MLX encodes, and allocates, the independent frames' phases up to
+ `MLX_MAX_ACTIVE_TASKS` tasks ahead of the link.
+- **Commit.** The run validates the step's frontier and commits once; the
+ session then commits each frame on its schedule and takes a prefix capture
+ when the step reaches the frontier, as after a lone frame.
+
+Invariants:
+1. Every frame runs the operations it runs alone, at its own 512-row shapes;
+ only submission order changes. Logits, attention rows, conv and SSM states
+ and prefix captures are the per-frame bytes
+ (`QwenTensorParallelPromptWavefrontTests.mergedFramesKeepEveryBit`: both
+ ranks, paged with the mirror and with page gathers, contiguous, a prompt
+ ending mid-frame, a capture frontier inside the prompt, a lane decoding
+ beside it).
+2. Each rank issues the sums frames alone issue, two a layer a frame, in the
+ same order on both ranks. They stay sealed FP32 all-sums: no BF16 partial,
+ no TF32 change.
+3. Only text lanes of dense models on native KV rows merge
+ (`QwenTensorParallelPromptWavefront.merges`). Assisted (MTP) lanes, media
+ lanes, packed KV and routed-expert models run one frame a step.
+4. A step's further frames in flight are charged:
+ `QwenTensorParallelPromptWavefront.inFlightBytes` (per further frame, five
+ frames' FP32 collective payload: two partials, two sums and the BF16
+ residual rows) joins the shared prompt workspace of
+ `QwenTensorParallelBatchBudget`, so LOAD, the placement quote and every
+ request's charge (`QwenTensorParallelRequestCharge`) include it. Its value
+ and measurements are in the
+ [TP batch admission boundary](hardware-support.md#qwen27-tp-batch-admission-boundary).
+5. The load agreement binds `qwen-tensor-parallel-prompt-wavefront-v1` and the
+ frame limits; `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` (diagnosis only, both
+ ranks) restores one frame a step.
+
+Failure modes: a planned step a rank cannot run as a prefix of its frames fails
+the driver step on that rank, as a changed frame did; a merged step that fails
+fails the lane as a frame does. A lane decoding beside a long prompt waits for a
+two-frame step instead of one frame.
+
+`darkbloom-cluster-tp-check qwen-prefill --wavefronts 1,8` times one rank's
+steps with no peer; `darkbloom-cluster-tp-check qwen-wavefront` runs a prompt on
+two ranks over the loopback ring at each frame limit, logs each run's peak
+memory (`peak_mb`) and checks that every run leaves both ranks the same bytes.
+Loopback timings show the overlap, never a pair's rate: on one M5 Ultra, 4-layer
+shards at the 27B's per-rank widths (`qwen-rows synthesize`) prefilled 11,264
+tokens over the sealed ring in 848-961 ms in steps of two or eight frames,
+against 1,517-1,522 ms one frame a step, every run with the same bytes on both
+ranks.
+
+Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift`
+(`QwenTensorParallelPromptWavefront`),
+`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift`
+(`promptFrames`, `prefill(step:check:)`),
+`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift`
+(`issuedSums`),
+`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift`
+(`derive`),
+`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift`
+(`pair`), and `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Qwen35PromptWavefront.swift`
+(`Qwen35PromptWavefront`).
+
### Qwen27 tensor-parallel native context
The registered Qwen3.8 27B row advertises the limits the single-Mac product
@@ -5442,6 +5877,19 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Requests/Dis
`provider-swift/Sources/ProviderCore/Inference/Distributed/Requests/DistributedQwenMediaLifetime.swift`, and
`provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedEngineFactory.swift`.
+## Gemma decode command buffers
+
+Gemma 4's plain decode steps (every row one token) commit a Metal command buffer
+every 100 operations with no input-size bound (`Gemma4DecodeCommandBuffers`,
+through `CBv2DecodeCommandBufferLimitsProviding`), as Nemotron Super, Flint and
+GLM do. MLX's defaults commit every 40 to 50 operations or 40 to 50 M distinct
+input elements. A step's inputs include the weights and each 64 MiB KV segment
+its history reads, so decode committed many times per step, reached MLX's limit
+of ten command buffers in flight, and waited inside evaluation instead of
+encoding ahead of the GPU. Results do not depend on the partitioning. Prefill
+chunks and assistant rounds keep MLX's defaults, so a row served with the
+assistant does not gain from this.
+
## Qwen27 feature-preserving mode selection
The exact registered Qwen3.8 27B dense adapter/profile requires images, video and committed-token logprobs on its installed cluster route. `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModelFeaturePolicy.swift` restricts that row to the advertised tensor-parallel mode before the ordinary placement cost ranking. Initial onboarding and automatic batch replacement share this intersection in `ClusterPlacementFlow.swift`; an incumbent pipeline cannot override it. Other registrations, GLM, measured rates, qualification shape exclusions and native memory gates keep their existing behavior. This policy is a restriction on existing metadata, not a new model catalog or capability grant. It does not prove tensor parallel is faster.
diff --git a/docs/developer/test.md b/docs/developer/test.md
index f34dd96624..94e1791500 100644
--- a/docs/developer/test.md
+++ b/docs/developer/test.md
@@ -25,7 +25,12 @@ not native model capabilities, numerical parity or hardware qualification.
The placement checks also cover exact family request scopes, completion-heavy
and long-prompt helper plans, overflow refusal, conservative memory refusal and
-unchanged GLM adapter bounds. Run `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh`
+unchanged GLM adapter bounds. `GemmaRoutedExpertChecks.swift` builds the Gemma
+QAT 4-bit layout from the retained real headers in
+`libs/darkbloom-cluster/Tests/StageMetadataChecks/Inputs`, requires it to equal
+its golden layout with `routedExperts` included, and requires the per-token
+read of the [routed-expert prior](../architecture/inference.md#gemma-routed-expert-prior).
+Run `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh`
and `provider-swift/Tests/ClusterPlacementChecks/run.sh`; then run
`provider-swift/Tests/ClusterPlacementChecks/run-flow.sh` for the real child-process
provider path with a fake installed helper. These checks use recorded metadata
@@ -567,6 +572,17 @@ first, and a request for the loading model when a second copy would not fit.
and the body decode on the CPU with only the tokenizer loaded and the background
comparisons off; it exits 2 if any token ID or decoded field differs.
+```bash
+swift test --skip-build --filter 'LocalTokenizerByteFallbackTests'
+```
+
+`LocalTokenizerByteFallbackTests` loads a synthetic tokenizer with Gemma 4's decoder
+sequence through the production `LocalTokenizerLoader` and requires characters
+written as `<0xHH>` tokens to survive a whole decode, a stream, a segment restart
+inside the run and a trailing special token, a run cut inside a character to end in
+one U+FFFD, and the unknown token not to read as a byte. A literal `<0x41>` token on
+another decoder keeps its spelling.
+
## Desktop Control And Frontend
`make desktop-test` exercises the frontend journeys and bridge validation.
@@ -1908,6 +1924,36 @@ preserving conservative memory charges. These tests do not load the registered
weight payload or establish hardware numerical qualification. See the
[native dtype contract](../architecture/inference.md#gpt-oss-native-residual-dtype).
+## Pipeline decode command buffer checks
+
+`PipelineDecodeCommandBufferTests` drives random synthetic stages of each
+layer-stage family as its stage session does: the prompt under the rank's
+16-operation guard, then decode once under a guard and once under
+`QwenLayerStageSession.decodeCommandBuffers`. Every output row, verify window
+and cache or state array must be byte-equal. The cases are a dense and a
+routed-expert Qwen 3.5 on a paged stage KV host (decode steps, a captured verify
+window kept to two rows, and two lanes), two Nemotron stages, a Gemma 4 decoder
+(one request and two lanes), two GPT-OSS stages (decode and lanes) and the
+verified GLM fixture's two stages. The reference run keeps the rank's guard,
+except routed Qwen and Gemma, which use `bankGuard`: their expert banks of 2 Mi
+elements each commit a buffer, as registered banks do. The Nemotron and GLM
+fixtures are too small for any size bound, so every family also runs with a
+buffer every second dispatch (`everyOperation`), a finer partition than one
+buffer per bank. Build and stage the runtime tests as described for the cluster
+runtime tests above, then, with the same build flags:
+
+```bash
+swift test --package-path libs/darkbloom-cluster -c release --skip-build --no-parallel \
+ --filter 'PipelineDecodeCommandBufferTests|ContextAdmissionTests|ResidentAdmissionNemotronTests|GPTOSSResidentAdmissionTests|ResidentAdmissionGemma4Tests'
+```
+
+The admission suites check each family's decode-row charge. These are synthetic
+GPU checks: not registered weights, pair runs, speed or peak memory. Served
+Qwen, Nemotron and Gemma 4 stages all attend through the paged stage KV, but
+only the Qwen cases use it here; the Nemotron and Gemma 4 cases keep
+request-owned KV. See
+[pipeline decode command buffers](../architecture/inference.md#pipeline-decode-command-buffers).
+
## Qwen batch projection arithmetic
`libs/mlx-swift-lm/Tests/MLXLMTests/Integration/Qwen/Qwen35BatchDecodeProjectionTests.swift`
@@ -1934,8 +1980,12 @@ with the fixed owner arguments and checks its exact environment, supported
lane widths, out-of-range rejection, malformed-override parity even with an
eight-lane family default, admission/owner/native parity, unsupported
mode and image gates, and both member ranks. No model, GPU or real service is
-started. The checks preserve the singleton and GLM tensor-parallel defaults;
-actual multi-lane output, encrypted transport and retirement still require
+started. The checks preserve the singleton and GLM tensor-parallel defaults
+and the serial-prefill Gemma 4 pipeline's default lanes
+(`DistributedInstalledPlan.gemma4PipelineBatchLanes`), which reach the rank,
+while a Gemma setup saved with the one-chunk lookahead keeps one lane;
+`DistributedInstalledLanesTests` covers the same rules for every adapter and
+schedule. Actual multi-lane output, encrypted transport and retirement still require
qualification on both Macs. The same real-child checks pass canonical local
`MLX_METAL_FAST_SYNCH=0|1` choices through the owner and final native launch,
reject free-text spellings from forwarding, preserve unrelated native guards,
@@ -2250,6 +2300,36 @@ salt's digest); a repeat under another tenant must report no reused tokens.
These are synthetic checks: tenant isolation on a real model and pair, and GLM
bit-identity with no partition, are hardware gates.
+## MiMo pipeline decode command buffers
+
+`MiMoDecodeCommandBufferTests` (cluster runtime, GPU) drives two random MiMo
+stages as `MiMoLayerStageSession` drives them. The prompt runs under the rank's
+16-operation guard. Decode steps, a verify window rolled back to two rows and
+lane steps then run twice: once under the guard and once under
+`MiMoLayerStageSession.decodeCommandBuffers`. Every residual crossing the cut,
+every logits row and every cache or page array must be byte-equal. The tests
+cover a tiny BF16 model and one quantized like the registered row (MXFP4
+experts, affine 8-bit projections, key width 192, value width 128), each on
+ordinary caches and on request-owned pages. The quantized model's guard scales
+MLX's size bound to its small expert banks (`bankGuard`), so each expert launch
+commits a buffer, as each registered bank does. Build and stage the runtime
+tests as described for the cluster runtime tests above, then, with the same
+build flags:
+
+```bash
+swift test --package-path libs/darkbloom-cluster -c release --skip-build --no-parallel \
+ --filter 'MiMoDecodeCommandBufferTests|MiMoResidentAdmissionTests|MiMoPagedAdmissionTests'
+bash libs/darkbloom-cluster/Tests/PlacementChecks/run.sh
+```
+
+The admission tests check that every full-attention layer's decode-row scores
+are charged at once (`MiMoRequestStateBudget`). The placement run includes
+`MiMoRoutedExpertChecks`: the MiMo layout built from the registered headers
+names 282 routed-expert tensors (160,859,947,008 bytes). The hardware prior
+reads 10,767,036,288 bytes for one decode step, and the golden plans change only
+by the layout they echo. These are synthetic and metadata checks. They run no
+registered weights and measure no speed.
+
## MiMo paged speculative and phase checks
Run `MiMoV26MTPPagedHistoryTests` and `MiMoV26IndependentHistoryTests` in the
@@ -2281,13 +2361,24 @@ prompt projections with actual singleton calls at chunk boundaries, checks
explicit scope restoration and unsupported/custom fallbacks, and verifies the
unchanged tied head. `Gemma4PrefillExpertTests` executes the actual Gemma decoder, router,
shared MLP and sparse expert block with the attention output isolated to zero;
-it assembles an independent projection/expert oracle while preserving the
-original rectangular normalization and elementwise operations, and compares
-selected routes across prompt boundaries. A separate expert-only composition
+it assembles an independent projection/expert oracle from one-token expert
+calls while preserving the original rectangular normalization and elementwise
+operations. It requires one expert call, never hinted as sorted, carrying every
+token's routes (grouped by expert from 64 assignments), with the oracle's
+bytes, at 7 to 512 tokens. A separate expert-only composition
check compares complete singleton calls with the shared branch isolated to
-zero. Ordinary and verification paths remain covered. These checks do not
+zero, and a decode check requires 2, 3 and 8 independent rows to share one
+call with each row's one-row bytes. A direct check compares the shared call
+with one-row calls for a single row and for rows that all route to the same
+experts. Ordinary and verification paths
+remain covered, and the original rectangular call still sorts. These checks do not
claim whole-layer singleton equivalence: existing normalization can depend on
-rectangle shape on CPU.
+rectangle shape on CPU. With `GEMMA4_EXPERT_ROWS_GPU=1` the suite also
+compares the shared call with one-row calls on the GPU for 1 to 2,048 rows,
+tied routes included, at
+a geometry with the production kernel classes; `=production` adds hidden 2,816,
+expert width 704 and 128 experts. Run the GPU case alone, in an exclusive
+hardware window.
`GemmaPrefillArithmeticTests` in the runtime target verifies that both exact
policies change the receipt while the family environment and chunk policy
remain bound. These CPU checks do not establish full-model cross-chip qualification
diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md
index ec48574988..b2c887bb08 100644
--- a/docs/provider/two-mac-cluster.md
+++ b/docs/provider/two-mac-cluster.md
@@ -156,6 +156,9 @@ pair's model and split; a release's cluster runtime facts carry them for
GLM-5.3-Flash and Qwen3.8-27B
([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)).
A tensor-parallel pair registers like a pipeline one; its plan names no cut.
+A Gemma 4 pipeline pair whose plan prefills serially takes several requests at
+once; one planned with the one-chunk lookahead takes one at a time
+([Gemma pipeline lanes](../architecture/inference.md#gemma-pipeline-lanes)).
1. Run `darkbloom cluster` and choose a model, as in [the steps](#the-steps-once).
After the Test stage passes, the leader reads the approvals the coordinator
diff --git a/docs/reference/cluster-control-protocol.md b/docs/reference/cluster-control-protocol.md
index 7331c8e124..6c5ad44d4f 100644
--- a/docs/reference/cluster-control-protocol.md
+++ b/docs/reference/cluster-control-protocol.md
@@ -1,6 +1,6 @@
# Experimental cluster control protocol
-> Last updated: 2026-10-29
+> Last updated: 2026-11-01
Exact member-role and native-pair public-control shapes on the provider
WebSocket, as staged in draft pull requests: the provider side in this
@@ -204,6 +204,7 @@ policy bytes the control requires in a prepare frame
| Prepare | The payload's policy must equal the installed policy byte for byte, the start must name this rank, and the frame must leave at most 30 seconds to prepare by this Mac's clock. The member then verifies its installed owner, native executable, metallib and resource library under the device gate and answers `native_pair_prepared` | `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift`, `init` / `runOwned` |
| Committed start | `native_pair_owner_start` launches this Mac's installed owner; the owner's native child drives `native_pair_hello` and `native_pair_confirmation`, and `native_pair_owner_released` is sent only after native cleanup, the owner's lease release and the owner's exit were all observed | `runOwned` / `exchange` |
| Cancel or expiry | Requests native cleanup at once, independently of signing or the socket. An uncommitted session is dropped and the member can prepare again; a committed one that cannot deliver its release stays quarantined in the control, which then refuses every later attachment | `cancel`; `NativePairMemberControl.finished` |
+| Serving on the leader | The leader serves one committed start at a time, from its serve until its session's stop. The stop releases the start at once, then waits for the pair slot to retire before the receipt. So after a lost rank or a fence, the next committed start is accepted even if a serve or the old slot's drain outlasts the session's bounded wait, and its slot cannot publish until the old slot has retired. A start whose session already stopped is never served. The slot's engine cannot deadlock that retirement ([provider inference engine](../architecture/inference.md)) | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift`, `onQueueWithoutWaiting` |
**What a real member does in this build.** The installed owner
(`darkbloom cluster worker-owner --stdio`) admits a start the coordinator
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index 1768e155e3..fa2ca6bfeb 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -788,13 +788,14 @@ solo serving is unchanged and the whole surface stays default-off.
| Field | Meaning and bounds | Source |
|---|---|---|
-| `batchLanes` | Optional integer 2, 4 or 8, or 6 for a Qwen TP row in `tensor_parallel_v1`; omitted in existing setups. Only registered text batch adapters in plain pipeline with serial prefill accept it. It is a requested width, never a capacity grant. | `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`validate`) |
+| `batchLanes` | Optional integer 2, 4 or 8, or 6 for a Qwen TP row in `tensor_parallel_v1`; omitted in existing setups. Only registered text batch adapters in plain pipeline with serial prefill accept it. It is a requested width, never a capacity grant. The guided setup writes it into both Macs' setups for a Qwen TP placement ([saved width](../architecture/inference.md#qwen-tensor-parallel-saved-width)), and a setup saved for coordinator pairing keeps it beside its approval. | `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`validate`), `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift` (`widest`) |
| `DARKBLOOM_CLUSTER_BATCH_LANES` | An explicit diagnostic setting retains precedence; absent settings use the persisted width, then the existing family default. Malformed explicit values fail closed to one lane. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift` (`batchLanes`) |
The normal cluster API can persist a wider setup after queued demand, conservative
memory planning and full release. No environment setting is needed for that
path. See [automatic local cluster batching](../architecture/inference.md#automatic-local-cluster-batching)
-for exclusions, rollback and the unchanged singleton preference at initial setup.
+for exclusions and rollback, and [the saved width](../architecture/inference.md#qwen-tensor-parallel-saved-width)
+for a Qwen TP placement's width at initial setup.
### Installed tensor-parallel synchronization
@@ -1619,7 +1620,9 @@ other models (`ClusterRuntimeAdapter.qwenTensorParallelRuntimeModelIDs` names th
and inconsistent ledger totals. It reads
registered headers and requires the native allocator metadata bound. Saved
`batchLanes` may select 2, 4, 6 or 8 in a Qwen TP row's `tensor_parallel_v1`; omission
-keeps one. GLM defaults remain unchanged.
+keeps one. The guided setup reads the quote at each of these widths
+([saved width](../architecture/inference.md#qwen-tensor-parallel-saved-width)).
+GLM defaults remain unchanged.
Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift`.
### Qwen27 saved mode compatibility
diff --git a/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md
new file mode 100644
index 0000000000..3753c79107
--- /dev/null
+++ b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md
@@ -0,0 +1,102 @@
+# Gemma pipeline prompt experts: one shared dispatch, the same bytes
+
+> Last updated: 2026-11-01
+
+This record covers the change to the registered Gemma 4 stages' prompt expert
+blocks: they now share one dispatch per operation instead of building
+one subgraph per prompt token. It gives the equality evidence and synthetic
+component timings measured on one Mac. It is not a pair, full-model or
+qualification result, and it contains no prompt, endpoint or machine identifier.
+
+## Context
+
+Since 2026-10-23 (`gemma4-bf16-token-expert-reduction-v1` in the exact Gemma
+arithmetic receipt) a registered Gemma stage computes every prompt token's
+expert block at one token, so that prompt arithmetic is the same on every Apple
+GPU generation. The receipt was added because rectangular expert products
+select chip-specific kernels. The implementation built that per-token
+arithmetic as one subgraph per token: about six launches per token per layer,
+or about 180,000 launches for a 2,048-token frame on a 15-layer stage. No
+prompt throughput had been measured for it.
+
+## Change
+
+`SwitchGLU.callAndWeightedReduceRows` (mlx-swift-lm) projects all rows of a
+frame in one call:
+
+- it groups 64 or more assignments by expert for weight locality, but does
+ not give the gathers the sorted hint;
+- every (row, expert) pair is therefore still an M=1 gathered product. MLX
+ picks `gather_qmv` and its variant from the quantization, dtype and the N
+ and K widths, never from the row count, and its grid gives each pair its own
+ threadgroups;
+- the rows return to their order before the top-8 weighted reduction, which
+ keeps its one-row `col_reduce_small` thread layout. That layout depends
+ only on the hidden width.
+
+Each row therefore keeps the bytes of its own one-row call, and the receipt is
+unchanged. Gemma's batch-decode rows (`Gemma4BatchDecodeScope`) use the same
+call.
+
+## Equality evidence
+
+| Check | Device | Result |
+|---|---|---|
+| `Gemma4PrefillExpertTests`: whole-layer composition against a one-token expert oracle, 7 to 512 tokens, 4 and 8 bits | CPU | bytes equal; one expert call, never hinted as sorted |
+| Same suite: expert branch against per-token layer calls; decode rows 2, 3 and 8 | CPU | bytes equal |
+| `GEMMA4_EXPERT_ROWS_GPU=1`: hidden 768, width 192, 16 experts (the production kernel classes), 1 to 2,048 rows, 4 and 8 bits | M5 Ultra GPU | bytes equal; values finite and nonzero |
+| `GEMMA4_EXPERT_ROWS_GPU=production`: hidden 2,816, width 704, 128 experts, 1 to 513 rows | M5 Ultra GPU | bytes equal |
+| Every row routed to the same 8 experts (every sort key tied), and a single row: `expertRowsMatchOneRowCallsWithTiedRoutes`, and the GPU check at 9 and 513 tied rows at both geometries | CPU; M5 Ultra GPU | bytes equal |
+| Sensitivity: the shared call against the earlier sorted rectangular call at 512 and 2,048 rows | M5 Ultra GPU | bytes differ, as expected |
+| `Gemma4StagePagedSyntheticTests`: two synthetic stages, lanes joining and leaving | M5 Ultra GPU | each request decodes its tokens alone |
+
+The suites ran in a debug build of `libs/darkbloom-cluster` with the SDK test
+file linked in and a source-matched `mlx.metallib` (SHA-256
+`5b97893cc20e6e9651edf3284d970488af9a9bdd64820231e95fee760eec70ac`, MLX
+`72dffa2d`). Other GPU generations were not run. [INFERENCE] The selection
+above should hold on them too: on this route `gather_qmv` takes no architecture
+input, and the reduction's threadgroup is 32 by 8 on any GPU whose kernels
+hold 256 threads per threadgroup.
+
+## Synthetic timings
+
+One layer with random packed weights at the registered geometry: experts at
+4 bits, dense MLP and router at 8 bits. Median of five warm runs, debug Swift
+build, on an M5 Ultra that was also serving other GPU work, so the figures
+carry contention noise.
+
+One run timed every expert-block variant at the production geometry:
+
+| Expert block, 4-bit | 512 tokens | 2,048 tokens |
+|---|---:|---:|
+| Per-token subgraphs (before) | 89.5 ms | 414.3 ms |
+| Shared dispatch, token order | 9.8 ms | 37.2 ms |
+| Shared dispatch, grouped by expert (after) | 8.2 ms | 30.8 ms |
+| Sorted rectangle (the prompt path before 2026-10-23) | 1.9 ms | 3.8 ms |
+
+A rerun of the final code measured 8.2 and 30.6 ms against 79.5 and 369.5 ms
+for the per-token graph. Every shared-dispatch variant equalled the per-token
+bytes.
+
+| Dense projections of one sliding layer (q, k, v, o, MLP, router) | 512 tokens | 2,048 tokens |
+|---|---:|---:|
+| M=1 rows (the registered prompt policy, unchanged) | 12.8 ms | 27.7 ms |
+| Rectangle | 3.7 ms | 3.7 ms |
+
+[INFERENCE] For a 15-layer stage and a 2,048-token frame, the projections took
+about 5.7 to 6.6 s before and take about 0.9 s after, ignoring attention and
+norms. That would lift the stage's projection-bound prompt rate from about 310
+to 360 tokens per second to about 2,300. The M=1 policy still costs about 8x
+the rectangle. Closing that gap needs a multi-row `qmv` kernel that keeps qmv's
+per-row reduction order.
+
+## Not established
+
+- Pair prompt or decode throughput, both schedules, both rank orders.
+- Full-artifact numerical agreement on any chip pair.
+- Other GPU generations (M1 to M4) and the release build.
+
+Code: `libs/mlx-swift-lm/Libraries/MLXLMCommon/SwitchLayers.swift`
+(`SwitchGLU.callAndWeightedReduceRows`) and
+`libs/mlx-swift-lm/Libraries/MLXLLM/Models/Gemma4Text.swift` (`Gemma4Experts`).
+Mechanism: [Gemma prompt projection reductions](../architecture/inference.md#gemma-prompt-projection-reductions).
diff --git a/docs/reports/README.md b/docs/reports/README.md
index 96e0b79cef..5200bb7ed9 100644
--- a/docs/reports/README.md
+++ b/docs/reports/README.md
@@ -1,9 +1,10 @@
# Provider And Native Evidence
-> Last updated: 2026-10-31
+> Last updated: 2026-11-01
Dated records and raw native evidence retain their original content, revisions and limitations. A record is not a fresh test result or proof of private platform compatibility.
+- [Gemma pipeline prompt experts](2026-11-01-gemma-pipeline-prompt-experts.md) - the registered Gemma stages' prompt expert blocks in one shared dispatch with the same bytes: CPU and M5 Ultra GPU equality evidence and synthetic one-layer timings; no pair or qualification result.
- [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash and Qwen3.8-27B for public cluster traffic in pipeline and tensor parallel, the checks it rests on and why releases carry pair-serving grants; the evidence document of `ClusterPublicModels`.
- [Mixed-step prefill geometry](2026-10-21-mixed-step-prefill-geometry.md) - load, engine, inter-token latency and KV-subtracted activation measurements behind Gemma 4's 2,048 / 4,096 prompt geometry, its media ceiling and the GPT-OSS and dense Qwen opt-in.
- [GLM-5.3-Flash single-Mac qualification record](2026-10-21-glm53-flash-single-mac-qualification.md)
diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift
new file mode 100644
index 0000000000..8fea759d74
--- /dev/null
+++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift
@@ -0,0 +1,69 @@
+import DarkbloomClusterRuntime
+import Foundation
+import MLX
+
+// The batch driver's plain decode on two ranks of one Mac (`QwenTensorParallelDecodeBench`):
+// MLX_RANK=0|1 MLX_HOSTFILE=hosts.json darkbloom-cluster-tp-check qwen-decode --model-dir /DIR \
+// [--backend ring|socket] [--reduction native|sealed-bench] [--width 1] [--prompt-tokens 32] \
+// [--output-tokens 64] [--sampled 0|1] [--control exchanged,folded] [--repeats 3] [--answer-delay-us 0]
+// Each rank logs every run's decode step time and token digest; both agree
+// that every run retired the same tokens. Loopback timings show a step's host
+// work and synchronization, never a pair's.
+enum QwenDecodeCheck {
+ static func run(_ arguments: [String]) throws {
+ var options: [String: String] = [:]
+ var index = 0
+ while index < arguments.count {
+ guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else {
+ throw Failure("qwen-decode: expected --name value pairs")
+ }
+ options[String(arguments[index].dropFirst(2))] = arguments[index + 1]
+ index += 2
+ }
+ guard let directory = options["model-dir"], directory.hasPrefix("/") else {
+ throw Failure("qwen-decode needs --model-dir /DIR")
+ }
+ guard let backend = QwenTensorParallelGroup.Backend(rawValue: options["backend"] ?? "ring"), backend != .jaccl else {
+ throw Failure("qwen-decode runs on the loopback ring or socket only")
+ }
+ let reduction = options["reduction"] ?? "sealed-bench"
+ guard ["native", "sealed-bench"].contains(reduction) else { throw Failure("--reduction takes native or sealed-bench") }
+ let controls = (options["control"] ?? "exchanged,folded").split(separator: ",").map(String.init)
+ guard let width = Int(options["width"] ?? "1"), (1...8).contains(width),
+ let prompt = Int(options["prompt-tokens"] ?? "32"), prompt > 0,
+ let output = Int(options["output-tokens"] ?? "64"), output > 1,
+ let repeats = Int(options["repeats"] ?? "3"), repeats > 0,
+ let delay = Int(options["answer-delay-us"] ?? "0"), delay >= 0,
+ let sampled = Int(options["sampled"] ?? "0"), [0, 1].contains(sampled),
+ !controls.isEmpty, controls.allSatisfy({ ["exchanged", "folded"].contains($0) }) else {
+ throw Failure("--width 1-8, positive --prompt-tokens, --output-tokens > 1, --repeats, --answer-delay-us >= 0,"
+ + " --sampled 0|1, --control exchanged,folded")
+ }
+ let url = URL(fileURLWithPath: directory)
+ let configuration = try Data(contentsOf: url.appendingPathComponent("config.json"))
+ let group = try QwenTensorParallelGroup(backend: backend)
+ let work = "\(reduction)|\(width)|\(prompt)|\(output)|\(sampled)|\(controls)|\(repeats)|\(delay)"
+ guard try group.digestsEqual(fnv(sha256Hex(configuration) + "|" + work)) else {
+ throw Failure("the ranks disagree on the checkpoint or the runs")
+ }
+ if reduction == "sealed-bench" {
+ let codec = try QwenTensorParallelSealCodec.bench(group: group,
+ scope: Data(("darkbloom-tp-qwen-decode-v1|" + sha256Hex(configuration)).utf8))
+ try codec.install()
+ group.sealed = codec
+ }
+ note("rank \(group.rank) of \(group.size) over \(backend.rawValue), \(reduction) sums")
+ let same = try Device.withDefaultDevice(.gpu) { () throws -> Bool in
+ let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2),
+ reduction: group)
+ return try QwenTensorParallelDecodeBench.pair(model: model, configuration: configuration, group: group,
+ width: width, promptTokens: prompt, outputTokens: output, sampled: sampled == 1,
+ folds: controls.map { $0 == "folded" }, repeats: repeats, answerDelayMicroseconds: delay) { line in
+ FileHandle.standardOutput.write(Data((line + "\n").utf8))
+ }
+ }
+ let both = try group.exchangeIntegers([same ? 1 : 0]) == [2]
+ note("both ranks retired the same tokens in every run: \(both)")
+ guard both else { throw Failure("folded control changed a retired token") }
+ }
+}
diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenPrefillBench.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenPrefillBench.swift
index 75b6229735..2daf626642 100644
--- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenPrefillBench.swift
+++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenPrefillBench.swift
@@ -3,7 +3,7 @@ import Foundation
import MLX
// darkbloom-cluster-tp-check qwen-prefill --model-dir /ABS [--rank R] [--shares A:B] [--prompt-tokens N]
-// [--chunks 512,1024] [--ops 0,16,100] [--strides 0,1] [--modes local,cpu-hop] [--repeats N]
+// [--chunks 512,1024] [--ops 0,16,100] [--strides 0,1] [--wavefronts 1,8] [--modes local,cpu-hop] [--repeats N]
// [--layers yes|no] [--gemm yes|no] [--gemm-rows 512,1024]
// One Qwen tensor-parallel rank's prompt prefill on this Mac with no peer
// (QwenTensorParallelPrefillBench): the product's request-owned prefill
@@ -20,7 +20,7 @@ enum QwenPrefillBench {
fields[arguments[index]] = arguments[index + 1]; index += 2
}
guard let directory = fields["--model-dir"], directory.hasPrefix("/") else {
- throw Failure("usage: qwen-prefill --model-dir /ABS [--rank R] [--shares A:B] [--prompt-tokens N] [--chunks 512,1024] [--ops 0,16,100] [--strides 0,1] [--modes local,cpu-hop] [--repeats N] [--layers yes|no] [--gemm yes|no] [--gemm-rows 512]")
+ throw Failure("usage: qwen-prefill --model-dir /ABS [--rank R] [--shares A:B] [--prompt-tokens N] [--chunks 512,1024] [--ops 0,16,100] [--strides 0,1] [--wavefronts 1,8] [--modes local,cpu-hop] [--repeats N] [--layers yes|no] [--gemm yes|no] [--gemm-rows 512]")
}
func list(_ name: String, _ fallback: [Int]) throws -> [Int] {
guard let text = fields[name] else { return fallback }
@@ -39,6 +39,7 @@ enum QwenPrefillBench {
options.chunks = try list("--chunks", [512])
options.operations = try list("--ops", [0])
options.strides = try list("--strides", [0])
+ options.wavefronts = try list("--wavefronts", [1])
options.modes = try (fields["--modes"] ?? "local").split(separator: ",").map {
guard let mode = QwenTensorParallelPrefillBench.Mode(rawValue: String($0)) else { throw Failure("--modes takes local,cpu-hop") }
return mode
diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift
new file mode 100644
index 0000000000..e5c5eecab0
--- /dev/null
+++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift
@@ -0,0 +1,65 @@
+import DarkbloomClusterRuntime
+import Foundation
+import MLX
+
+// A Qwen tensor-parallel prompt on two ranks of one Mac, one frame a step and
+// in merged wavefront steps (`QwenTensorParallelPrefillBench.pair`):
+// MLX_RANK=0|1 MLX_HOSTFILE=hosts.json darkbloom-cluster-tp-check qwen-wavefront --model-dir /DIR \
+// [--backend ring|socket] [--reduction native|sealed-bench] [--prompt-tokens 4096] [--chunk 512] \
+// [--output-tokens 8] [--wavefronts 1,2,8] [--repeats 1]
+// Each rank logs every run's step times, peak memory and digests; both agree
+// that every run left the same bytes. Loopback timings show the overlap, never
+// a pair's. `--output-tokens` sets the request's context past the prompt.
+enum QwenWavefrontCheck {
+ static func run(_ arguments: [String]) throws {
+ var options: [String: String] = [:]
+ var index = 0
+ while index < arguments.count {
+ guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else {
+ throw Failure("qwen-wavefront: expected --name value pairs")
+ }
+ options[String(arguments[index].dropFirst(2))] = arguments[index + 1]
+ index += 2
+ }
+ guard let directory = options["model-dir"], directory.hasPrefix("/") else {
+ throw Failure("qwen-wavefront needs --model-dir /DIR")
+ }
+ guard let backend = QwenTensorParallelGroup.Backend(rawValue: options["backend"] ?? "ring"), backend != .jaccl else {
+ throw Failure("qwen-wavefront runs on the loopback ring or socket only")
+ }
+ let reduction = options["reduction"] ?? "sealed-bench"
+ guard ["native", "sealed-bench"].contains(reduction) else { throw Failure("--reduction takes native or sealed-bench") }
+ let wavefronts = (options["wavefronts"] ?? "1,2,8").split(separator: ",").compactMap { Int($0) }
+ guard let prompt = Int(options["prompt-tokens"] ?? "4096"), prompt > 0,
+ let chunk = Int(options["chunk"] ?? "512"), chunk > 0, let repeats = Int(options["repeats"] ?? "1"),
+ let output = Int(options["output-tokens"] ?? "8"), output > 0,
+ !wavefronts.isEmpty, wavefronts.allSatisfy({ (1...8).contains($0) }) else {
+ throw Failure("--prompt-tokens, --chunk, --output-tokens and --repeats take positive integers, --wavefronts 1 to 8")
+ }
+ let url = URL(fileURLWithPath: directory)
+ let configuration = try Data(contentsOf: url.appendingPathComponent("config.json"))
+ let group = try QwenTensorParallelGroup(backend: backend)
+ let work = "\(reduction)|\(prompt)|\(chunk)|\(output)|\(wavefronts)|\(repeats)"
+ guard try group.digestsEqual(fnv(sha256Hex(configuration) + "|" + work)) else {
+ throw Failure("the ranks disagree on the checkpoint or the runs")
+ }
+ if reduction == "sealed-bench" {
+ let codec = try QwenTensorParallelSealCodec.bench(group: group,
+ scope: Data(("darkbloom-tp-qwen-wavefront-v1|" + sha256Hex(configuration)).utf8))
+ try codec.install()
+ group.sealed = codec
+ }
+ note("rank \(group.rank) of \(group.size) over \(backend.rawValue), \(reduction) sums")
+ let same = try Device.withDefaultDevice(.gpu) { () throws -> Bool in
+ let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2),
+ reduction: group)
+ return try QwenTensorParallelPrefillBench.pair(model: model, configuration: configuration,
+ promptTokens: prompt, chunk: chunk, outputTokens: output, wavefronts: wavefronts, repeats: repeats) { line in
+ FileHandle.standardOutput.write(Data((line + "\n").utf8))
+ }
+ }
+ let both = try group.exchangeIntegers([same ? 1 : 0]) == [2]
+ note("both ranks left the same bytes in every run: \(both)")
+ guard both else { throw Failure("a merged prompt left other bytes than one frame a step") }
+ }
+}
diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift
index 927254686a..967355f838 100644
--- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift
+++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift
@@ -25,6 +25,10 @@ import MLX
// darkbloom-cluster-tp-check qwen-rows synthesize|run|layers ... (27B batch rows at the registered per-rank
// widths: each row against itself alone and in verify windows over the loopback ring, or the first layer
// that differs; `QwenRowsCheck`)
+// darkbloom-cluster-tp-check qwen-wavefront --model-dir /DIR ... (a prompt one frame a step and in merged
+// wavefront steps over the loopback ring: step times and digests; `QwenWavefrontCheck`)
+// darkbloom-cluster-tp-check qwen-decode --model-dir /DIR ... (the batch driver's decode over the loopback
+// ring, control exchanged a step or folded into the selection sum: step times and tokens; `QwenDecodeCheck`)
//
// `full` is the unsharded model on one Mac (this code path's single-Mac
// reference); `simulated` is the single-process tensor-parallel oracle (the
@@ -528,6 +532,14 @@ enum CompareCommand {
try QwenRowsCheck.run(Array(CommandLine.arguments.dropFirst(2)))
return
}
+ if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "qwen-wavefront" {
+ try QwenWavefrontCheck.run(Array(CommandLine.arguments.dropFirst(2)))
+ return
+ }
+ if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "qwen-decode" {
+ try QwenDecodeCheck.run(Array(CommandLine.arguments.dropFirst(2)))
+ return
+ }
let options = try Options(Array(CommandLine.arguments.dropFirst()))
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys, .prettyPrinted]
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift
index 7dd8bc82ef..9a0b063f84 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift
@@ -130,6 +130,23 @@ public struct ClusterPlacementTensorBatchQuote: Codable, Equatable, Sendable {
policy.tensorParallelBatchQuote = self
}
+ /// Initial placement at a saved width (`batchLanes`): this owner's
+ /// complete quote at `lanes` takes the place of the singleton quote the
+ /// placement was chosen with (same request envelope, chunk and assistant).
+ /// The envelope covers the planned or served reference, so only memory is
+ /// priced at this width; the prediction stays a single request's.
+ public func applyWidth(to policy: inout ClusterPlacementPolicy, layout: ClusterModelLayout) throws {
+ try validate(layout: layout)
+ guard lanes > 1, let singleton = policy.tensorParallelBatchQuote, singleton.lanes == 1,
+ singleton.request == request, singleton.chunkTokens == chunkTokens,
+ singleton.assistant?.policy == assistant?.policy else {
+ throw ClusterPlacementError("A saved tensor width needs the same owner's singleton quote")
+ }
+ try request.applyCovering(to: &policy, layout: layout)
+ policy.tensorParallelBatchQuote = self
+ policy.tensorParallelWideningQuote = nil
+ }
+
public func requireAssistant(_ expected: ClusterQwenTensorAssistantPolicy?) throws {
guard assistant?.policy == expected else {
throw ClusterPlacementError("Tensor quotation changed the saved assistant policy")
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Generation/GLM5NextStageSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Generation/GLM5NextStageSession.swift
index 560a2a2bd5..c2d250037b 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Generation/GLM5NextStageSession.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Generation/GLM5NextStageSession.swift
@@ -107,8 +107,8 @@ final class GLM5NextStageSession {
}
inOperation = true
defer { inOperation = false }
- do {
- return try MLX.withError { error in
+ func run() throws -> QwenLayerStageOutput {
+ try MLX.withError { error in
func checked() throws {
try error.check(); try check()
guard !isFailed else { throw ProbeError("GLM stage request was invalidated") }
@@ -210,6 +210,12 @@ final class GLM5NextStageSession {
}
return result!
}
+ }
+ do {
+ // A decode frame encodes under the pipeline decode limits
+ // (`QwenLayerStageSession.decodeCommandBuffers`); prefill keeps the rank's.
+ guard frame.phase == .decode else { return try run() }
+ return try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers, run)
} catch {
isFailed = true
throw error
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSLayerStageSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSLayerStageSession.swift
index 794bea380a..465cc6abeb 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSLayerStageSession.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSLayerStageSession.swift
@@ -97,12 +97,15 @@ final class GPTOSSLayerStageSession {
} catch { try fail(error) }
}
+ /// Encodes under the pipeline decode limits (`QwenLayerStageSession.decodeCommandBuffers`).
func decode(_ token: Int, offset: Int, incoming: QwenLayerStageBoundary? = nil,
check: () throws -> Void) throws -> QwenLayerStageOutput {
do {
try requireOpen()
let frame = try schedule.admitDecode(offset: offset)
- return try perform(tokens: [token], frame: frame, incoming: incoming, check: check)
+ return try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) {
+ try perform(tokens: [token], frame: frame, incoming: incoming, check: check)
+ }
} catch { try fail(error) }
}
@@ -291,10 +294,12 @@ extension GPTOSSLayerStageSession {
histories.append(pages)
}
let frontiers = sessions.map { $0.schedule.committedTokens }
- let output = try GPTOSSBatchForward.decode(model: first.stage.model, head: first.stage.head,
- stageIndex: first.stage.stageIndex, hiddenSize: first.hiddenSize,
- vocabularySize: first.stage.vocabularySize, dtype: first.stage.residualDType,
- tokens: tokens, residual: residual, histories: histories, check: check)
+ let output = try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) {
+ try GPTOSSBatchForward.decode(model: first.stage.model, head: first.stage.head,
+ stageIndex: first.stage.stageIndex, hiddenSize: first.hiddenSize,
+ vocabularySize: first.stage.vocabularySize, dtype: first.stage.residualDType,
+ tokens: tokens, residual: residual, histories: histories, check: check)
+ }
for (session, frontier) in zip(sessions, frontiers) { try session.requireFrontier(after: frontier + 1) }
for (session, frame) in zip(sessions, frames) { try session.schedule.commit(frame) }
if first.stage.stageIndex == 0 {
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift
index 68910cb4d8..6fcd9c41f4 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift
@@ -15,7 +15,10 @@ import Foundation
/// is no recurrent state. A stage also holds one residual chunk coming or
/// going, and stage 1 one vocabulary row. The workspace term is the largest
/// transient a forward is known to build: one full-attention layer's score
-/// matrix for a chunk against the whole history, in float32.
+/// matrix for a chunk against the whole history, in float32, and never less
+/// than every full-attention layer's scores for its one decode row at once (a
+/// decode step's command buffers can keep the whole step in flight,
+/// `QwenLayerStageSession.decodeCommandBuffers`).
struct GPTOSSRequestStateBudget: Encodable, Equatable {
static let activationBytes = 4, growthStep = 256
let fullAttentionLayers: Int, slidingLayers: Int
@@ -61,7 +64,9 @@ struct GPTOSSRequestStateBudget: Encodable, Equatable {
let slidingState = try product([slidingPerLayer, sliding])
let boundary = try allowance(try product([chunkSize, spec.hidden, activationBytes]), 2)
let row = rank == 1 ? try allowance(try product([spec.vocabulary, 4]), 2) : 0
- let workspace = full == 0 ? 0 : try allowance(try product([spec.queryHeads, chunkSize, capacity, 4]), 1)
+ // GPT-OSS decodes one row a request (no verify window): one per full-attention layer.
+ let scoreRows = max(chunkSize, full)
+ let workspace = full == 0 ? 0 : try allowance(try product([spec.queryHeads, scoreRows, capacity, 4]), 1)
return .init(fullAttentionLayers: full, slidingLayers: sliding, fullAttentionStateBytes: fullState,
slidingStateBytes: slidingState, boundaryBytes: boundary, rowBytes: row, workspaceBytes: workspace,
reservedBytes: try sum([fullState, slidingState, boundary, row, workspace]))
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift
index ac6b0d5249..0f4c189cfb 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift
@@ -85,6 +85,16 @@ struct Gemma4PlacementFamily: ClusterPlacementFamily {
func layerKind(_ layer: Int) -> String { Gemma4StageGeometry.kind(globalLayerIndex: layer) }
+ /// A decode step reads 8 of every layer's 128 expert banks; the router and
+ /// the dense MLP beside them are read whole.
+ var expertRouting: ClusterExpertRouting? {
+ ClusterExpertRouting(selected: Gemma4StageGeometry.expertsPerToken, experts: Gemma4StageGeometry.routedExperts)
+ }
+
+ func isRoutedExpert(storedTensor name: String) -> Bool {
+ layer(ofStoredTensor: name) != nil && name.contains(".experts.switch_glu.")
+ }
+
/// Keys and values in bfloat16: per token on a full-attention layer; on a
/// sliding layer a ring of the window, allocated whole, and the view one
/// frame attends over (`Gemma4StateBudget`).
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift
index 5b395130b3..e448671c42 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift
@@ -10,6 +10,8 @@ enum Gemma4StageGeometry {
static let slidingWindow = 1024
static let slidingKVHeads = 8, slidingHeadDimension = 256
static let fullKVHeads = 2, fullHeadDimension = 512
+ /// Every layer routes each token to 8 of its 128 experts.
+ static let routedExperts = 128, expertsPerToken = 8
/// Five sliding-window layers, then one full-attention layer, five times.
static let fullAttentionInterval = 6
static let slidingKind = "sliding_attention", fullKind = "full_attention"
@@ -44,7 +46,8 @@ enum Gemma4StageGeometry {
throw ProbeError("Gemma stage metadata requires the original text wrapper")
}
let integers = ["num_hidden_layers": layerCount, "hidden_size": hiddenSize, "vocab_size": vocabularySize,
- "intermediate_size": 2112, "moe_intermediate_size": 704, "num_experts": 128, "top_k_experts": 8,
+ "intermediate_size": 2112, "moe_intermediate_size": 704, "num_experts": routedExperts,
+ "top_k_experts": expertsPerToken,
"sliding_window": slidingWindow, "num_attention_heads": queryHeads,
"num_key_value_heads": slidingKVHeads, "num_global_key_value_heads": fullKVHeads,
"head_dim": slidingHeadDimension, "global_head_dim": fullHeadDimension,
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentFamily.swift
index fdd057af55..6aeed4461a 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentFamily.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentFamily.swift
@@ -47,6 +47,7 @@ extension Gemma4ResidentLoadedStage: LayerStageResidentStage {
}
func requestAllowance(plan: QwenLayerStagePlan, rank: Int, maximumTokens: Int, chunkSize: Int,
+ decode: LayerStageDecodeShape,
bound: (Int) throws -> Int) throws -> QwenResidentRequestAllowance {
guard plan.stages.count == 2, (0...1).contains(rank), loaded.plan.fingerprint == plan.fingerprint else {
throw ProbeError("Resident request allowance requires this stage's admitted two-stage Plan")
@@ -58,13 +59,15 @@ extension Gemma4ResidentLoadedStage: LayerStageResidentStage {
}
let state = try budget.allowance(bound: bound)
// One prefill frame's attention transient at this context, as the
- // dense allowance adds it, so a context the gate admits is one a frame runs in.
+ // dense allowance adds it, so a context the gate admits is one a frame
+ // runs in; or a decode step's on every layer it runs, when larger.
let logical = try Gemma4PrefillTransient.bytes(layers: plan.stages[rank].layers, chunkTokens: chunkSize,
- contextTokens: maximumTokens)
+ contextTokens: maximumTokens, decodeRows: decode.rows,
+ decodeLayers: decode.stages(of: plan, rank: rank).flatMap(\.layers))
let transient = logical == 0 ? 0 : try bound(logical)
return .init(stateBytes: state.stateBytes, fusionBytes: state.fusionBytes,
reservedBytes: try QwenLongPrefillCheckedBytes.sum([state.reservedBytes, transient]),
- transientBytes: transient, contextTokens: maximumTokens)
+ transientBytes: transient, contextTokens: maximumTokens, decode: decode)
}
func diagnosticResources(plan: QwenLayerStagePlan, request: QwenLayerStageGenerationRequest, rank: Int,
@@ -84,7 +87,7 @@ extension Gemma4ResidentLoadedStage: LayerStageResidentStage {
// A byte-only allowance is not a permit: rederive the exact request with
// the actual allocator, then require the owner's reservation to match.
let actual = try self.requestAllowance(plan: plan, rank: rank, maximumTokens: request.maximumTokens,
- chunkSize: min(request.chunkSize, request.promptCount),
+ chunkSize: min(request.chunkSize, request.promptCount), decode: requestAllowance.decode,
bound: QwenResidentResourceEnvironment.allocationBound)
guard actual.stateBytes == requestAllowance.stateBytes, actual.fusionBytes == requestAllowance.fusionBytes,
actual.reservedBytes == requestAllowance.reservedBytes else {
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4StateBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4StateBudget.swift
index bf1d66e25c..86ae4154dc 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4StateBudget.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4StateBudget.swift
@@ -86,21 +86,28 @@ struct Gemma4ResidentResourceCeilings: Equatable {
/// planner prices it beside the KV, oMLX U#3651). Both head dimensions (512 on
/// a full layer, 256 on a sliding one) take MLX's unfused path, so a frame
/// materializes float32 scores beside a float32 output: over the whole context
-/// on a full layer, over the window and the frame on a sliding one. Layers run
-/// one after another, so the stage's transient is its largest layer's.
+/// on a full layer, over the window and the frame on a sliding one. Prefill
+/// layers run one after another under the rank's command-buffer limits, so the
+/// frame's transient is its largest layer's. A decode step's command buffers
+/// (`QwenLayerStageSession.decodeCommandBuffers`) can keep every layer's
+/// temporaries alive at once: `decodeRows` a layer over each of `decodeLayers`,
+/// added up, priced the same way, and the larger of the two is charged.
enum Gemma4PrefillTransient {
- static func bytes(layers: [QwenLayerStagePlan.Layer], chunkTokens: Int, contextTokens: Int) throws -> Int {
+ static func bytes(layers: [QwenLayerStagePlan.Layer], chunkTokens: Int, contextTokens: Int,
+ decodeRows: Int = 0, decodeLayers: [QwenLayerStagePlan.Layer] = []) throws -> Int {
typealias G = Gemma4StageGeometry
let product = QwenLongPrefillCheckedBytes.product, sum = QwenLongPrefillCheckedBytes.sum
- let queries = min(chunkTokens, contextTokens)
- var largest = 0
- for layer in layers {
+ func transient(_ layer: QwenLayerStagePlan.Layer, queries: Int) throws -> Int {
let full = layer.kind == G.fullKind
let width = full ? G.fullHeadDimension : G.slidingHeadDimension
- let keys = full ? contextTokens : min(contextTokens, G.slidingWindow - 1 + chunkTokens)
- let value = try sum([product([G.queryHeads, queries, keys, 4]), product([G.queryHeads, queries, width, 4])])
- largest = max(largest, value)
+ let keys = full ? contextTokens : min(contextTokens, G.slidingWindow - 1 + queries)
+ return try sum([product([G.queryHeads, queries, keys, 4]), product([G.queryHeads, queries, width, 4])])
}
- return largest
+ let queries = min(chunkTokens, contextTokens)
+ var largest = 0
+ for layer in layers { largest = max(largest, try transient(layer, queries: queries)) }
+ guard decodeRows > 0 else { return largest }
+ let decode = try sum(decodeLayers.map { try transient($0, queries: decodeRows) })
+ return max(largest, decode)
}
}
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/LayerStageResident.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/LayerStageResident.swift
index 095b73185b..e3c5e33c37 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/LayerStageResident.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/LayerStageResident.swift
@@ -55,13 +55,43 @@ extension LayerStageResidentAdmission {
}
}
+/// What one decode forward of a request runs on a rank. Under the decode
+/// command buffers (`QwenLayerStageSession.decodeCommandBuffers`) the
+/// temporaries of every layer it runs can be alive at once: `rows` a layer (1,
+/// or a verify window's `depth + 1`), over the rank's own stage or, on the
+/// decoding rank of a phase split, which runs both stages, over every layer.
+/// The other rank of a phase split hands its prompt state over and decodes
+/// nothing: 0 rows.
+struct LayerStageDecodeShape: Equatable {
+ var rows = 1
+ var wholeModel = false
+
+ static let plain = Self()
+
+ init(rows: Int = 1, wholeModel: Bool = false) {
+ self.rows = rows; self.wholeModel = wholeModel
+ }
+
+ init(mode: QwenResidentGenerationMode, rank: Int, speculativeTerms: QwenMTPTerms?) {
+ let rows = mode.usesSpeculativeHead ? (speculativeTerms?.depth ?? 0) + 1 : 1
+ self.init(rows: mode.isPhaseSplit && rank == 0 ? 0 : rows, wholeModel: mode.isPhaseSplit && rank == 1)
+ }
+
+ /// The stages of `plan` whose layers one decode forward on `rank` runs.
+ func stages(of plan: QwenLayerStagePlan, rank: Int) -> [QwenLayerStagePlan.Stage] {
+ wholeModel ? plan.stages : [plan.stages[rank]]
+ }
+}
+
/// One rank's loaded stage and what its family knows about a request's storage.
protocol LayerStageResidentStage {
var loaded: LoadedQwenLayerStage { get }
/// The registered model's own ceiling for one request's named state.
func namedStateByteCeiling() throws -> Int
- /// This rank's named request storage, each array at the allocator's bound.
+ /// This rank's named request storage, each array at the allocator's bound,
+ /// for a request whose decode forwards run `decode`.
func requestAllowance(plan: QwenLayerStagePlan, rank: Int, maximumTokens: Int, chunkSize: Int,
+ decode: LayerStageDecodeShape,
bound: (Int) throws -> Int) throws -> QwenResidentRequestAllowance
/// A recording capture's live gate, bound to this loaded source and to the
/// allowance the owner reserved.
@@ -72,6 +102,15 @@ protocol LayerStageResidentStage {
var handoffGeometry: QwenLongPrefillBudgetGeometry? { get }
}
+extension LayerStageResidentStage {
+ /// A request that decodes one row a step on this rank's stage.
+ func requestAllowance(plan: QwenLayerStagePlan, rank: Int, maximumTokens: Int, chunkSize: Int,
+ bound: (Int) throws -> Int) throws -> QwenResidentRequestAllowance {
+ try requestAllowance(plan: plan, rank: rank, maximumTokens: maximumTokens, chunkSize: chunkSize,
+ decode: .plain, bound: bound)
+ }
+}
+
/// Admits one rank's load through the registered family its identity names.
/// Every family's catalog is closed; a model ID in none of them is refused.
enum LayerStageResidentFamily {
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift
index f3b1ecc887..86d6163aed 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift
@@ -16,6 +16,19 @@ import MLXLMCommon
/// sliding-window layer. Positions come from each cache's own offset, which
/// both stages advance by the same token counts.
final class MiMoLayerStageSession {
+ /// Command-buffer commit limits of a decode step, a lane step and a
+ /// speculative round on the thread that encodes them, as GLM's and Qwen's
+ /// tensor-parallel decode keep them
+ /// (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`). Under
+ /// the rank's 16-operation guard (`ClusterWorkerEnvironmentGuards`) and
+ /// MLX's per-chip input-size bound, which each routed layer's expert
+ /// launch passes alone (it takes a whole expert bank), a decode step
+ /// commits a buffer every few launches, each a GPU gap. Prefill keeps the
+ /// rank's limits. Synchronization only: results never depend on the
+ /// partitioning. MLX keeps up to ten buffers in flight, so a step's
+ /// in-flight work spans the stage's layers (`MiMoRequestStateBudget`).
+ static let decodeCommandBuffers = GPU.CommandBufferLimits(operations: 100, megabytes: 1 << 20)
+
let identity: QwenLayerStageSessionIdentity
let request: QwenLayerStageGenerationRequest
private let stage: LoadedMiMoLayerStage
@@ -178,7 +191,9 @@ final class MiMoLayerStageSession {
do {
try requireOpen()
let frame = try schedule.admitDecode(offset: offset)
- return try perform(tokens: [token], frame: frame, incoming: incoming, check: check)
+ return try GPU.withCommandBufferLimits(Self.decodeCommandBuffers) {
+ try perform(tokens: [token], frame: frame, incoming: incoming, check: check)
+ }
} catch { try fail(error) }
}
@@ -611,7 +626,7 @@ extension MiMoLayerStageSession: IndependentHistoryBatchSession {
frames.append(try session.schedule.admitDecode(offset: session.committedTokens))
histories.append(pages)
}
- return try MLX.withError { error in
+ return try GPU.withCommandBufferLimits(decodeCommandBuffers) { try MLX.withError { error in
func checked() throws { try error.check(); try check() }
try checked()
let last = first.stage.layerCount - 1
@@ -636,7 +651,7 @@ extension MiMoLayerStageSession: IndependentHistoryBatchSession {
}
if rank == 0 { Stream.gpu.synchronize(); try checked() }
return output
- }
+ } }
} catch {
var failure: Error = error
for session in sessions {
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift
index da00e26b35..8b61c79125 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift
@@ -232,9 +232,30 @@ enum MiMoMTPGeneration {
}
/// Rank 0: run each window rank 1 asks for, check what it keeps, publish.
+ /// Every round encodes as a decode step does (`MiMoLayerStageSession.decodeCommandBuffers`).
static func runProducer(session: MiMoLayerStageSession, control: QwenLayerStageGenerationControl,
terms: MiMoMTPTerms, collective: Collective,
onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome {
+ try GPU.withCommandBufferLimits(MiMoLayerStageSession.decodeCommandBuffers) {
+ try producerRounds(session: session, control: control, terms: terms, collective: collective,
+ onCommittedToken: onCommittedToken, check: check)
+ }
+ }
+
+ /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank
+ /// 0's publication. Every round, drafts included, encodes as a decode
+ /// step does (`MiMoLayerStageSession.decodeCommandBuffers`).
+ static func runConsumer(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder,
+ control: QwenLayerStageGenerationControl, collective: Collective,
+ check: () throws -> Void) throws -> Outcome {
+ try GPU.withCommandBufferLimits(MiMoLayerStageSession.decodeCommandBuffers) {
+ try consumerRounds(session: session, decoder: decoder, control: control, collective: collective, check: check)
+ }
+ }
+
+ private static func producerRounds(session: MiMoLayerStageSession, control: QwenLayerStageGenerationControl,
+ terms: MiMoMTPTerms, collective: Collective,
+ onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome {
let agreement = control.agreement
guard collective.rank == 0 else { throw ProbeError("Only rank 0 runs the producer side of a speculative round") }
var selected: [Int] = [], discarded = 0
@@ -295,11 +316,9 @@ enum MiMoMTPGeneration {
return .init(selected: selected, finalDecision: finalDecision, discardedDecodeForwards: discarded, statistics: nil)
}
- /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank
- /// 0's publication.
- static func runConsumer(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder,
- control: QwenLayerStageGenerationControl, collective: Collective,
- check: () throws -> Void) throws -> Outcome {
+ private static func consumerRounds(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder,
+ control: QwenLayerStageGenerationControl, collective: Collective,
+ check: () throws -> Void) throws -> Outcome {
let agreement = control.agreement, request = agreement.request
guard collective.rank == 1 else { throw ProbeError("Only rank 1 runs the consumer side of a speculative round") }
let stopTokens = Set(request.stopTokenIDs)
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift
index 848ce31596..7aac45eddd 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift
@@ -105,6 +105,17 @@ struct MiMoPlacementFamily: ClusterPlacementFamily {
name.hasPrefix(MiMoLayerStagePlan.sourceNamespace + "model.mtp.")
}
+ /// Each routed layer sends a token to `expertsPerToken` of its `experts`.
+ var expertRouting: ClusterExpertRouting? {
+ ClusterExpertRouting(selected: specification.expertsPerToken, experts: specification.experts)
+ }
+
+ /// A routed layer's packed expert banks and their block scales; its router
+ /// and score correction are read on every step.
+ func isRoutedExpert(storedTensor name: String) -> Bool {
+ layer(ofStoredTensor: name) != nil && name.contains(".mlp.switch_mlp.")
+ }
+
/// The text tensors (every indexed tensor no stage excludes) are the
/// registered inventory.
func requireRegisteredInventory(_ tensors: [ClusterPlacementStoredTensor]) throws {
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift
index 59ef8e4ac0..98f4a40c4b 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift
@@ -11,7 +11,10 @@ import Foundation
/// plus the chunk just appended, the same way. A stage also holds one residual
/// chunk coming or going, and stage 1 one vocabulary row. The workspace term
/// is the largest transient a forward is known to build: one full-attention
-/// layer's score matrix for a chunk against the whole history, in float32.
+/// layer's score matrix for a chunk against the whole history, in float32,
+/// and never less than every full-attention layer's scores for the decode
+/// rows at once (a decode step's command buffers keep the whole step in
+/// flight, `MiMoLayerStageSession.decodeCommandBuffers`).
struct MiMoRequestStateBudget: Encodable, Equatable {
static let activationBytes = 2, growthStep = 256
let fullAttentionLayers: Int, slidingLayers: Int
@@ -39,12 +42,16 @@ struct MiMoRequestStateBudget: Encodable, Equatable {
reservedBytes: try QwenLongPrefillCheckedBytes.sum([reservedBytes, extra]))
}
+ /// `decodeRows`: the most rows one decode forward runs (1, or a verify
+ /// window's `depth + 1`).
static func estimate(specification spec: MiMoRegisteredSpecification, layers: Range, rank: Int,
- maximumTokens: Int, chunkSize: Int, bound: (Int) throws -> Int) throws -> Self {
+ maximumTokens: Int, chunkSize: Int, decodeRows: Int = 1,
+ bound: (Int) throws -> Int) throws -> Self {
let limits = try spec.contextLimits()
guard (0...1).contains(rank), !layers.isEmpty, layers.lowerBound >= 0, layers.upperBound <= spec.layers,
(1...limits.maximumContextTokens).contains(maximumTokens),
- (1...limits.maximumChunkTokens).contains(chunkSize) else {
+ (1...limits.maximumChunkTokens).contains(chunkSize),
+ (1...limits.maximumChunkTokens).contains(decodeRows) else {
throw MiMoProfileError("MiMo request state is outside the registered request scope")
}
let sum = QwenLongPrefillCheckedBytes.sum, product = QwenLongPrefillCheckedBytes.product
@@ -66,7 +73,8 @@ struct MiMoRequestStateBudget: Encodable, Equatable {
let boundary = try allowance(try product([chunkSize, spec.hidden, activationBytes]), 2)
let row = rank == 1 ? try allowance(try product([spec.vocabulary, 4]), 2) : 0
// 64 query heads; the registered attention geometry fixes it.
- let workspace = full == 0 ? 0 : try allowance(try product([64, chunkSize, capacity, 4]), 1)
+ let scoreRows = max(chunkSize, try product([decodeRows, full]))
+ let workspace = full == 0 ? 0 : try allowance(try product([64, scoreRows, capacity, 4]), 1)
return .init(fullAttentionLayers: full, slidingLayers: sliding, fullAttentionStateBytes: fullState,
slidingStateBytes: slidingState, boundaryBytes: boundary, rowBytes: row, workspaceBytes: workspace,
reservedBytes: try sum([fullState, slidingState, boundary, row, workspace]))
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift
index a5f3a5ef14..981ba65d28 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift
@@ -150,7 +150,7 @@ struct MiMoResidentRequestAllowance {
let forwardTokens = max(chunkSize, verificationTokens)
let layers = phaseSplit && rank == 1 ? 0.. Bool, check: () throws -> Void) throws -> Outcome {
+ try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) {
+ try producerRounds(session: session, control: control, terms: terms, collective: collective,
+ recording: recording, onCommittedToken: onCommittedToken, check: check)
+ }
+ }
+
+ /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank
+ /// 0's publication. Every round, drafts included, encodes as a decode
+ /// step does (`QwenLayerStageSession.decodeCommandBuffers`).
+ static func runConsumer(session: QwenLayerStageSession, decoder: QwenMTPDecoder,
+ control: QwenLayerStageGenerationControl, collective: Collective,
+ recording: QwenGenerationDiagnosticCapture? = nil,
+ check: () throws -> Void) throws -> Outcome {
+ try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) {
+ try consumerRounds(session: session, decoder: decoder, control: control, collective: collective,
+ recording: recording, check: check)
+ }
+ }
+
+ private static func producerRounds(session: QwenLayerStageSession, control: QwenLayerStageGenerationControl,
+ terms: QwenMTPTerms, collective: Collective,
+ recording: QwenGenerationDiagnosticCapture?,
+ onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome {
let agreement = control.agreement, request = agreement.request
guard collective.rank == 0, agreement.speculativeRoundsFraming == terms.pipelineDecodeFraming else {
throw ProbeError("Only rank 0 of an agreed speculative pipeline runs the producer side of a round")
@@ -155,12 +179,10 @@ enum QwenPipelineMTPGeneration {
return .init(selected: selected, finalDecision: finalDecision, discardedDecodeForwards: discarded, statistics: nil)
}
- /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank
- /// 0's publication.
- static func runConsumer(session: QwenLayerStageSession, decoder: QwenMTPDecoder,
- control: QwenLayerStageGenerationControl, collective: Collective,
- recording: QwenGenerationDiagnosticCapture? = nil,
- check: () throws -> Void) throws -> Outcome {
+ private static func consumerRounds(session: QwenLayerStageSession, decoder: QwenMTPDecoder,
+ control: QwenLayerStageGenerationControl, collective: Collective,
+ recording: QwenGenerationDiagnosticCapture?,
+ check: () throws -> Void) throws -> Outcome {
let agreement = control.agreement, request = agreement.request
guard collective.rank == 1, agreement.speculativeRoundsFraming == decoder.terms.pipelineDecodeFraming else {
throw ProbeError("Only rank 1 of an agreed speculative pipeline runs the consumer side of a round")
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentFamily.swift
index 1c1775d7e4..62856ff22f 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentFamily.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentFamily.swift
@@ -22,9 +22,10 @@ extension QwenResidentLoadedStage: LayerStageResidentStage {
}
func requestAllowance(plan: QwenLayerStagePlan, rank: Int, maximumTokens: Int, chunkSize: Int,
+ decode: LayerStageDecodeShape,
bound: (Int) throws -> Int) throws -> QwenResidentRequestAllowance {
try QwenResidentRequestAllowance.derive(profile: profile, plan: plan, rank: rank,
- maximumTokens: maximumTokens, chunkSize: chunkSize, bound: bound)
+ maximumTokens: maximumTokens, chunkSize: chunkSize, decode: decode, bound: bound)
}
func diagnosticResources(plan: QwenLayerStagePlan, request: QwenLayerStageGenerationRequest, rank: Int,
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentRuntime.swift
index 85326977cf..f6a8e3f136 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentRuntime.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentRuntime.swift
@@ -281,7 +281,9 @@ public final class QwenResidentRuntime {
let prompt = min(admission.memoryProfile.maximumPromptTokens, context - 1)
let chunk = min(admission.memoryProfile.maximumChunkTokens, prompt)
let allowance = try stage.requestAllowance(plan: admission.plan, rank: rank,
- maximumTokens: context, chunkSize: chunk, bound: QwenResidentResourceEnvironment.allocationBound)
+ maximumTokens: context, chunkSize: chunk,
+ decode: .init(mode: mode, rank: rank, speculativeTerms: speculativeTerms),
+ bound: QwenResidentResourceEnvironment.allocationBound)
let prefill = try QwenResidentPrefillSelection.allowance(policy, rank: rank, promptCount: prompt,
chunkSize: chunk, hiddenSize: admission.profile.hiddenSize,
elementBytes: qwenStageWireElementBytes(admission.profile.activationDType),
@@ -372,7 +374,9 @@ public final class QwenResidentRuntime {
guard let stage else { throw ProbeError("Resident model already released") }
let allowance = try stage.requestAllowance(
plan: admission.plan, rank: collective.rank, maximumTokens: request.maximumTokens,
- chunkSize: min(request.chunkSize, request.promptCount), bound: QwenResidentResourceEnvironment.allocationBound)
+ chunkSize: min(request.chunkSize, request.promptCount),
+ decode: .init(mode: generationMode, rank: collective.rank, speculativeTerms: speculativeTerms),
+ bound: QwenResidentResourceEnvironment.allocationBound)
let prefill = try prefillAllowance(prefillPolicy, promptCount: request.promptCount, chunkSize: request.chunkSize)
let split = try Self.phaseSplitAllowance(generationMode, admission: admission, stage: stage,
rank: collective.rank, promptCount: request.promptCount, speculativeTerms: speculativeTerms)
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentPrefillTransient.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentPrefillTransient.swift
index a281952854..4cd4977998 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentPrefillTransient.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentPrefillTransient.swift
@@ -13,20 +13,25 @@ import Foundation
/// beside a float32 output. Query blocking (`DARKBLOOM_CBV2_ATTN_QUERY_BLOCK`)
/// bounds the matrix per block, but blocks of one frame may be evaluated
/// together, so the whole frame is priced: an upper bound, not a measurement.
-/// Layers run one after another, so one layer's transient is the stage's.
+/// Prefill layers run one after another under the rank's command-buffer
+/// limits, so one layer's transient is the frame's. A decode step's command
+/// buffers (`QwenLayerStageSession.decodeCommandBuffers`) can keep every
+/// attending layer's temporaries alive at once: `decodeRows` is the number of
+/// such rows, each layer's decode rows added up, priced as score rows over
+/// the whole context, and the larger of the two is charged.
enum QwenResidentPrefillTransient {
static let fusedHeadDimensions: Set = [64, 72, 80, 96, 128]
static let scoreElementBytes = 4
static let outputElementBytes = 4
static func bytes(geometry g: QwenLongPrefillBudgetGeometry, stageHasAttention: Bool,
- chunkTokens: Int, contextTokens: Int) throws -> Int {
- guard chunkTokens > 0, contextTokens > 0 else {
+ chunkTokens: Int, contextTokens: Int, decodeRows: Int = 0) throws -> Int {
+ guard chunkTokens > 0, contextTokens > 0, decodeRows >= 0 else {
throw QwenLongPrefillBudgetError.invalid("Attention transient needs a positive frame and context")
}
- guard stageHasAttention else { return 0 }
let product = QwenLongPrefillCheckedBytes.product
- let queries = min(chunkTokens, contextTokens)
+ let queries = max(stageHasAttention ? min(chunkTokens, contextTokens) : 0, decodeRows)
+ guard queries > 0 else { return 0 }
let output = try product([g.queryHeads, queries, g.headDimension, outputElementBytes])
if fusedHeadDimensions.contains(g.headDimension) { return output }
let scores = try product([g.queryHeads, queries, contextTokens, scoreElementBytes])
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentRequestResources.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentRequestResources.swift
index e5b19d7a0a..894c4e33bb 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentRequestResources.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentRequestResources.swift
@@ -6,11 +6,14 @@ struct QwenResidentRequestAllowance {
let stateBytes: Int
let fusionBytes: Int
let reservedBytes: Int
- /// One prefill frame's attention transient at this request's context
+ /// One prefill frame's attention transient at this request's context, or
+ /// its decode step's on every layer it runs when larger
/// (`QwenResidentPrefillTransient`), included in `reservedBytes`.
var transientBytes = 0
/// Prompt plus output tokens this allowance was derived for; 0 when unknown.
var contextTokens = 0
+ /// What this request's decode forwards run, as derived.
+ var decode = LayerStageDecodeShape.plain
/// This request's record at the host memory gate, and its first sample.
let watch = QwenDenseStageLoadWatch("Resident request")
@@ -22,7 +25,7 @@ struct QwenResidentRequestAllowance {
/// them, and `fusionBytes` is the allowance for those copies.
/// This named ledger excludes unknown workspace/whole-process peak claims.
static func derive(profile: QwenRegisteredDenseModelProfile, plan: QwenLayerStagePlan,
- rank: Int, maximumTokens: Int, chunkSize: Int,
+ rank: Int, maximumTokens: Int, chunkSize: Int, decode: LayerStageDecodeShape = .plain,
bound: (Int) throws -> Int) throws -> Self {
guard plan.stages.count == 2, (0...1).contains(rank) else {
throw ProbeError("Resident request allowance requires an admitted two-stage Plan")
@@ -87,12 +90,15 @@ struct QwenResidentRequestAllowance {
// U#3651), so a context the gate admits is one the frame can run in.
// From the stage's own layer kinds: a Plan without an interval (Nemotron,
// interval 0) names its attention blocks `attention`.
- let stageHasAttention = plan.stages[rank].layers.contains { ["full_attention", "attention"].contains($0.kind) }
+ func attends(_ layer: QwenLayerStagePlan.Layer) -> Bool { ["full_attention", "attention"].contains(layer.kind) }
+ let stageHasAttention = plan.stages[rank].layers.contains(where: attends)
+ // A decode step's rows on every attending layer it runs, alive at once.
+ let decodeLayers = decode.stages(of: plan, rank: rank).flatMap(\.layers).filter(attends).count
let transientLogical = try QwenResidentPrefillTransient.bytes(geometry: g, stageHasAttention: stageHasAttention,
- chunkTokens: chunkSize, contextTokens: maximumTokens)
+ chunkTokens: chunkSize, contextTokens: maximumTokens, decodeRows: try product([decode.rows, decodeLayers]))
let transient = transientLogical == 0 ? 0 : try allowance(transientLogical, 1)
return .init(stateBytes: state, fusionBytes: fusion, reservedBytes: try sum([state, fusion, transient]),
- transientBytes: transient, contextTokens: maximumTokens)
+ transientBytes: transient, contextTokens: maximumTokens, decode: decode)
}
/// `onLoadedStage`: a request's reservation on a stage that is already loaded. It asks for what the request
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift
index c209fcf26d..1b60334fb5 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift
@@ -15,7 +15,7 @@ struct QwenTensorParallelBatchBudget {
let sharedBytesExcludingCollectives: Int
let batchProjectionConstantBytes: Int
let pagedPoolSlackBytes: Int
- /// Paged: one full-history gather bank, shared (one prompt frame per step).
+ /// Paged: one full-history gather bank, shared (one prompt step at a time).
let promptGatherBytes: Int
let prefix: QwenTensorParallelBatchPrefixBudget
let allowance: ClusterTensorParallelRequestAllowance
@@ -43,7 +43,7 @@ struct QwenTensorParallelBatchBudget {
// The full-history gather bank is a prompt frame's transient: decode
// and verify windows attend the pages in place (the fused paged
// decode kernel, one query column at a time), and the batch driver
- // runs at most one prompt frame per step, so one bank serves every
+ // runs one lane's prompt step at a time, so one bank serves every
// lane (`QwenTensorParallelBatchSessionTests.fullHistoryGatherIsOne
// PromptFramesTransient` measures both). The scalar floor's F32 KV
// term (two BF16 banks) is replaced by the lane's own BF16 page
@@ -90,14 +90,18 @@ struct QwenTensorParallelBatchBudget {
bound(product([plan.expertsPerToken, plan.hiddenSize, 4]), count: lanes),
bound(product([plan.hiddenSize, 4]), count: lanes),
]) : 0)
+ // A merged prompt step's further frames in flight (one prompt step at a time, shared).
+ let wavefront = try QwenTensorParallelPromptWavefront.inFlightBytes(plan: plan, chunkTokens: chunkSize,
+ allocationBound: allocationBound)
let shared = try sum([scalar.fusionBytes, transient, logits,
- scalar.projectionConstantBytes, batchConstants, poolSlack, packing, promptGather])
+ scalar.projectionConstantBytes, batchConstants, poolSlack, packing, promptGather, wavefront])
// A one-token batch can gather more bytes than a short prompt frame.
- // Control limbs and retirement votes also travel in the sealed codec.
+ // Control limbs and retirement votes also travel in the sealed codec,
+ // the next step's limbs after a greedy selection's six words a row.
let payload = max(scalar.allowance.maximumCollectivePayloadBytes,
try product([lanes, plan.maximumPartialBytesPerToken]),
try product([lanes, plan.vocabularySize, 4]),
- try product([QwenTensorParallelBatchWire.words, 4]))
+ try product([QwenTensorParallelBatchWire.words + 6 * lanes, 4]))
let frame = try sum([payload, QwenTensorParallelSealCodec.frameOverhead])
let allowance = try ClusterTensorParallelRequestAllowance(maximumContextTokens: maximumTokens,
maximumChunkTokens: chunkSize,
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift
index 72dbcb7ea8..7b762ec90a 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift
@@ -14,12 +14,22 @@ protocol QwenTensorParallelBatchLane: AnyObject {
var reusedPrefixTokens: Int { get }
var storedPrefixFrontiers: [Int] { get }
var canSelectNext: Bool { get }
+ /// The lane's decode selects through the plain selection sum (no
+ /// assistant round or accepted queue), which can carry control words.
+ var plainSelection: Bool { get }
+ func promptStep(frames: Int) -> QwenLayerStageFrame?
+ func promptStep(tokens: Int) -> QwenLayerStageFrame?
}
extension QwenTensorParallelBatchLane {
var reusedPrefixTokens: Int { 0 }
var storedPrefixFrontiers: [Int] { [] }
var canSelectNext: Bool { nextFrame?.phase == .decode }
+ var plainSelection: Bool { true }
+ /// The prompt step of up to `frames` consecutive frames (`QwenTensorParallelPromptWavefront`).
+ func promptStep(frames: Int) -> QwenLayerStageFrame? { nextFrame }
+ /// The planned prompt step of `tokens`, if it is one this lane may run.
+ func promptStep(tokens: Int) -> QwenLayerStageFrame? { nextFrame.flatMap { $0.tokenCount == tokens ? $0 : nil } }
}
/// Both ranks run every forward. Selection returns the same token to both;
@@ -32,20 +42,47 @@ protocol QwenTensorParallelBatchExecutor: AnyObject {
func discard(_ reservation: Reservation) throws
func open(_ reservation: Reservation, check: () throws -> Void) throws -> Lane
func prefill(_ lane: Lane, frame: QwenLayerStageFrame, check: () throws -> Void) throws -> Int?
+ /// Whether this executor's selection sum can carry control words; the
+ /// driver folds only for one that can.
+ var carriesSelectionControl: Bool { get }
+ /// One decode rectangle whose selection sum carries no control words.
func decode(_ lanes: [Lane], tokens: [Int], check: () throws -> Void) throws -> [Int]
+ /// One decode rectangle. `control` runs once the forward committed and
+ /// before selection; words it returns (plain lanes only) ride the
+ /// selection's sealed sum, and both ranks' summed words come back.
+ func decode(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?,
+ check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?)
func retire(_ lane: Lane, reason: QwenLayerStageGenerationFinishReason?, selected: Int, last: Int?) throws
func takeLogprobs(_ lane: Lane) throws -> ClusterWorkerTokenLogprobs?
func confirmedRetirement(_ lane: Lane, clean: Bool) throws
}
extension QwenTensorParallelBatchExecutor {
+ var carriesSelectionControl: Bool { false }
func confirmedRetirement(_ lane: Lane, clean: Bool) throws {}
+
+ /// An executor whose selection sum carries no control words: the driver
+ /// never folds for it, so `control` is always empty.
+ func decode(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?,
+ check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) {
+ let selected = try decode(lanes, tokens: tokens, check: check)
+ guard try control() == nil else { throw ProbeError("This TP executor's selection sum carries no control words") }
+ return (selected, nil)
+ }
}
-/// One prefill frame on its original grid and one real decode rectangle per
+/// One prompt step (consecutive frames on the original grid) and one real decode rectangle per
/// step. Every active request owns its native history. A slow client holds
/// only its own token credit. Successful retirement is published only after
/// both ranks have drained, including cancellation and deadline departures.
+///
+/// A step whose decode rectangle is plain and runs no prompt folds the next
+/// step's plan and report into its selection sum: one sealed sum and one host
+/// read a step. That plan is made before the step's tokens are known, so
+/// host events (answers, credits, cancellations, joins) apply one step later,
+/// and both ranks drop a carried decode whose token ended its request (EOS or
+/// length). Rank 0 publishes a token only once the owner answered the one
+/// before it; a token selected before a stop answer is never published.
final class QwenTensorParallelBatchDriver {
typealias Reservation = Executor.Reservation
private final class Record {
@@ -53,17 +90,25 @@ final class QwenTensorParallelBatchDriver QwenLayerStageGenerationFinishReason? {
- guard let last = tokens.last else { return nil }
- if reservation.request.stopTokenIDs.contains(last) { return .eos }
- if tokens.count == reservation.request.outputCount { return .length }
+ /// How the request ends at its first `count` tokens, given the owner's answer to the last.
+ func finish(_ proceed: Bool, count: Int) -> QwenLayerStageGenerationFinishReason? {
+ guard count >= 1, count <= tokens.count else { return nil }
+ if reservation.request.stopTokenIDs.contains(tokens[count - 1]) { return .eos }
+ if count == reservation.request.outputCount { return .length }
return proceed ? nil : .clientStop
}
+ /// Its last token ends the request: no further forward.
+ var ended: Bool { finish(true, count: tokens.count) != nil }
}
private let executor: Executor
private let book: ClusterBatchLaneBook
@@ -72,14 +117,17 @@ final class QwenTensorParallelBatchDriver, capacity: Int, vocabulary: Int,
- joinWaitNanoseconds: UInt64 = 30_000_000_000,
+ joinWaitNanoseconds: UInt64 = 30_000_000_000, foldsControl: Bool = true,
now: @escaping () -> UInt64 = { DispatchTime.now().uptimeNanoseconds }) throws {
guard (0...1).contains(executor.rank), (1...8).contains(capacity), vocabulary > 0,
joinWaitNanoseconds > 0 else { throw ProbeError("Qwen TP batch driver has invalid geometry") }
self.executor = executor; self.book = book; self.capacity = capacity; self.vocabulary = vocabulary
- self.joinWaitNanoseconds = joinWaitNanoseconds; self.now = now
+ self.joinWaitNanoseconds = joinWaitNanoseconds; self.foldsControl = foldsControl; self.now = now
}
private func cancelled(_ record: Record) -> Bool {
@@ -95,27 +143,37 @@ final class QwenTensorParallelBatchDriver()
+ /// This step's plan and report, when they rode the last step's selection sum.
+ var carried: (plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply)?
do {
while true {
let stop = try autoreleasepool { () throws -> Bool in
- let answers = executor.rank == 0 ? try decisions.serviceAndPoll(host) : [:]
- if executor.rank == 1 { try host.serviceControl() }
- try check()
- let localPlan = executor.rank == 0
- ? makePlan(step: step, answers: answers, decisions: decisions, peerCancelled: peerCancelled,
- coalescing: &coalescing) : nil
- let localReport = executor.rank == 1 ? report(step: step) : nil
- let sum = try executor.exchange(QwenTensorParallelBatchWire.contribution(
- rank: executor.rank, plan: localPlan, report: localReport), check: check)
- let (plan, peer) = try QwenTensorParallelBatchWire.read(sum, step: step, lanes: capacity)
- if let localPlan, plan != localPlan { throw ProbeError("Qwen TP leader plan changed in transit") }
- if let localReport, peer != localReport { throw ProbeError("Qwen TP follower report changed in transit") }
+ let plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply
+ let wasCarried = carried != nil
+ if let folded = carried {
+ (plan, peer) = folded; carried = nil
+ if executor.rank == 1 { try host.serviceControl() }
+ try check()
+ } else {
+ let answers = executor.rank == 0 ? try decisions.serviceAndPoll(host) : [:]
+ if executor.rank == 1 { try host.serviceControl() }
+ try check()
+ let localPlan = executor.rank == 0
+ ? try makePlan(step: step, answers: answers, decisions: &decisions, host: host,
+ peerCancelled: peerCancelled, coalescing: &coalescing) : nil
+ let localReport = executor.rank == 1 ? report(step: step) : nil
+ let sum = try executor.exchange(QwenTensorParallelBatchWire.contribution(
+ rank: executor.rank, plan: localPlan, report: localReport), check: check)
+ (plan, peer) = try Self.read(sum, step: step, lanes: capacity, plan: localPlan, report: localReport)
+ }
try validate(plan, peer: peer)
peerCancelled = Set((0.. Record in
guard let record = records[slot], let native = record.native,
@@ -124,25 +182,52 @@ final class QwenTensorParallelBatchDriver [Float]? in
+ guard folds else { return nil }
+ if executor.rank == 0 {
+ let answers = try decisions.serviceAndPoll(host)
+ try check()
+ nextPlan = try makePlan(step: step + 1, answers: answers, decisions: &decisions, host: host,
+ peerCancelled: peerCancelled, coalescing: &coalescing, carrying: carrying)
+ } else {
+ try host.serviceControl(); try check()
+ nextReport = report(step: step + 1, carrying: carrying)
+ }
+ return try QwenTensorParallelBatchWire.contribution(rank: executor.rank, plan: nextPlan, report: nextReport)
+ }, check: { try check(); try host.serviceControl() })
+ guard result.tokens.count == lanes.count, (result.control != nil) == folds else {
+ throw ProbeError("Qwen TP decode omitted a lane or its control words")
+ }
+ for (lane, token) in zip(lanes, result.tokens) {
+ try selected(token, lane: lane, decisions: &decisions, host: host, peerCancelled: peerCancelled)
+ }
+ if let words = result.control {
+ let (next, nextPeer) = try Self.read(words, step: step + 1, lanes: capacity, plan: nextPlan, report: nextReport)
+ carried = (try resolve(next, carrying: carrying), nextPeer)
+ }
}
- let prompts = plan.slots.indices.filter { plan.slots[$0].role == .prefill }
- guard prompts.count <= 1 else { throw ProbeError("Qwen TP plan has multiple prefill frames") }
if let slot = prompts.first {
let value = plan.slots[slot]
- guard let lane = records[slot], let native = lane.native, let frame = native.nextFrame,
+ guard let lane = records[slot], let native = lane.native, let frame = native.promptStep(tokens: value.frameCount),
frame.phase == .prefill, frame.tokenOffset == value.frameOffset,
frame.tokenCount == value.frameCount, frame.finalPromptChunk == value.finalChunk else {
throw ProbeError("Qwen TP prefill differs from its original chunk grid")
}
let token = try executor.prefill(native, frame: frame, check: { try check(); try host.serviceControl() })
guard (token != nil) == frame.finalPromptChunk else { throw ProbeError("Qwen TP prefill returned the wrong final-row kind") }
- if let token { try selected(token, lane: lane, decisions: &decisions, host: host, publish: !peerCancelled.contains(lane.slot)) }
+ if let token { try selected(token, lane: lane, decisions: &decisions, host: host, peerCancelled: peerCancelled) }
}
- if decode.isEmpty && prompts.isEmpty && plan.slots.allSatisfy({ $0.state == .active || $0.state == .empty }) {
+ // A carried plan whose decodes ended is idle only by the tokens just read;
+ // the next step exchanges at once.
+ if !wasCarried, decode.isEmpty, prompts.isEmpty,
+ plan.slots.allSatisfy({ $0.state == .active || $0.state == .empty }) {
Thread.sleep(forTimeInterval: 0.0005)
}
return false
@@ -158,19 +243,35 @@ final class QwenTensorParallelBatchDriver, coalescing: inout QwenBatchDecodeCoalescing) -> QwenBatchWire.Header {
+ /// Rank 0's plan for `step`. `carrying`: rows decoding in the step whose
+ /// selection sum carries this plan. Each counts the token it is selecting
+ /// and decodes on it (`carriedToken`) only if the owner already answered
+ /// the token before it; a stop keeps the tokens the owner saw.
+ private func makePlan(step: Int, answers: [UUID: Bool], decisions: inout QwenBatchDecisionProgress,
+ host: QwenBatchServingHost, peerCancelled: Set,
+ coalescing: inout QwenBatchDecodeCoalescing, carrying: Set = []) throws -> QwenBatchWire.Header {
var slots = [QwenBatchWire.Slot](repeating: .init(), count: capacity)
for (slot, record) in records {
+ let selecting = carrying.contains(slot)
var value = QwenBatchWire.Slot(state: .active, requestID: record.id)
value.committedTokens = record.native?.committedTokens ?? 0
- value.selectedTokens = record.tokens.count; value.fingerprintWords = record.fingerprint
- let reason = answers[record.id].flatMap { record.finish($0) }
+ value.selectedTokens = record.tokens.count + (selecting ? 1 : 0); value.fingerprintWords = record.fingerprint
+ // An answer is to the last published token.
+ let reason = answers[record.id].flatMap { record.finish($0, count: record.published) }
if cancelled(record) || peerCancelled.contains(slot) || reason != nil {
value.state = .leaving; value.leaveCancelled = cancelled(record) || peerCancelled.contains(slot)
value.leaveReason = value.leaveCancelled ? nil : reason
- } else if record.native?.canSelectNext == true, decisions.canForward(record.id) {
- value.role = .decode; value.inputToken = record.tokens.last ?? -1
+ if !value.leaveCancelled { value.selectedTokens = record.published }
+ record.leaving = true
+ } else {
+ if answers[record.id] == true {
+ try publishHeld(record, decisions: &decisions, host: host, peerCancelled: peerCancelled)
+ }
+ if record.native?.canSelectNext == true, record.published == record.tokens.count,
+ decisions.canForward(record.id) {
+ value.role = .decode
+ value.inputToken = selecting ? QwenTensorParallelBatchWire.carriedToken : record.tokens.last ?? -1
+ }
}
slots[slot] = value
}
@@ -182,7 +283,9 @@ final class QwenTensorParallelBatchDriver QwenBatchWire.Reply {
+ private func report(step: Int, carrying: Set = []) -> QwenBatchWire.Reply {
let mask = records.values.reduce(0) { $0 | (cancelled($1) ? 1 << $1.slot : 0) }
- return .init(step: step, tokens: (0.. (QwenBatchWire.Header, QwenBatchWire.Reply) {
+ let (received, peer) = try QwenTensorParallelBatchWire.read(sum, step: step, lanes: lanes)
+ if let plan, received != plan { throw ProbeError("Qwen TP leader plan changed in transit") }
+ if let report, peer != report { throw ProbeError("Qwen TP follower report changed in transit") }
+ return (received, peer)
+ }
+
+ /// A carried plan was made before the tokens of the step that carried it.
+ /// A row that decodes on its new token takes it, unless that token ended
+ /// its request (a stop token or its output count): both ranks read it in
+ /// the same sum and drop that decode alike.
+ private func resolve(_ plan: QwenBatchWire.Header, carrying: Set) throws -> QwenBatchWire.Header {
+ var plan = plan
+ for slot in plan.slots.indices where plan.slots[slot].inputToken == QwenTensorParallelBatchWire.carriedToken {
+ guard plan.slots[slot].role == .decode, carrying.contains(slot), let record = records[slot],
+ let token = record.tokens.last else {
+ throw ProbeError("Qwen TP carried decode has no carrying row")
+ }
+ if record.ended { plan.slots[slot].role = .none; plan.slots[slot].inputToken = -1 }
+ else { plan.slots[slot].inputToken = token }
+ }
+ return plan
}
private func validate(_ plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply) throws {
@@ -221,8 +352,12 @@ final class QwenTensorParallelBatchDriver) throws {
guard (0..) throws {
+ guard lane.published == lane.tokens.count - 1, !lane.leaving, decisions.canForward(lane.id),
+ !peerCancelled.contains(lane.slot), !cancelled(lane) else { return }
+ try decisions.published(lane.id)
+ try host.publishToken(requestID: lane.id, ordinal: lane.published, tokenID: lane.tokens[lane.published],
+ committedTokens: lane.reservation.request.promptCount + lane.published, logprobs: lane.heldLogprobs)
+ lane.published += 1; lane.heldLogprobs = nil
}
private func leave(_ plan: QwenBatchWire.Header, host: QwenBatchServingHost,
@@ -285,8 +430,10 @@ final class QwenTensorParallelBatchDriver [QwenLayerStageFrame] {
+ guard !retired else { return [] }
+ let merges = QwenTensorParallelPromptWavefront.merges(model: model, request: request,
+ mediaInputs: inputs != nil, packedStorage: state.packedStorage)
+ return QwenTensorParallelPromptWavefront.frames(request: request, from: schedule.nextSequence,
+ frontiers: prefixCapture?.frontiers ?? [], limit: merges ? limit : 1)
+ }
+
+ /// Runs the planned prompt step `step` (`promptFrames`), its frames as one graph.
+ func prefill(step: QwenLayerStageFrame, check: () throws -> Void) throws -> MLXArray? {
+ let frames = promptFrames(limit: QwenTensorParallelPromptWavefront.maximumFrames)
+ guard let count = (1...max(1, frames.count)).first(where: {
+ QwenTensorParallelPromptWavefront.step(Array(frames.prefix($0))) == step
+ }) else { throw ProbeError("Qwen TP prompt step differs from its frames") }
+ return try prompt(capturingHidden: false, frames: count, check: check).logits
+ }
+
func prefillForMTP(check: () throws -> Void) throws -> QwenTensorParallelMTPPromptResult {
guard inputs == nil, request.qwenMedia == nil else { throw ProbeError("Qwen TP media cannot enter assistant history") }
let result = try prompt(capturingHidden: true, check: check)
@@ -112,13 +132,20 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget {
return .init(hidden: hidden, logits: result.logits)
}
- private func prompt(capturingHidden: Bool, check: () throws -> Void) throws -> (hidden: MLXArray?, logits: MLXArray?) {
+ private func prompt(capturingHidden: Bool, frames count: Int = 1,
+ check: () throws -> Void) throws -> (hidden: MLXArray?, logits: MLXArray?) {
try MLX.withError { error in
func checked() throws { try error.check(); try check() }
- let proposed = try request.frame(sequence: schedule.nextSequence)
- let frame = try schedule.admitPrefill(count: proposed.tokenCount, offset: proposed.tokenOffset,
- final: proposed.finalPromptChunk)
- guard !retired, !failed, window?.isIdle ?? true, frame.phase == .prefill, state.committedTokens == frame.tokenOffset else {
+ // Each frame is admitted on the schedule as the frames before it leave it.
+ var planned = schedule, frames: [QwenLayerStageFrame] = []
+ for _ in 0.. MLXArray in
+ if frames.count > 1 {
+ return QwenTensorParallelPromptWavefront.forward(model: self.model, request: self.request,
+ frames: frames, caches: caches, evaluation: evaluation)
+ }
+ return Qwen35LayerSubmission.$stride.withValue(stride) { () -> MLXArray in
let native = self.model.model
if capturingHidden {
let result = native.cbv2ForwardWithHidden(input,
@@ -187,7 +218,7 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget {
}
eval(hidden); try checked()
}
- try schedule.commit(frame)
+ schedule = planned
try prefixCapture?.capture(state, at: committedTokens, check: checked)
if let timing, case .shard(let rank, _) = model.role {
let clock = promptClock ?? QwenTensorParallelPromptClock()
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift
index afb1470203..2846243a68 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift
@@ -4,10 +4,17 @@ import Foundation
/// rank owns one disjoint region; splitting Int32 into two UInt16 limbs keeps
/// UUIDs, fingerprints and checksums exact in FP32. The load agreement binds
/// this protocol separately from the pipeline protocol it uses for framing.
+///
+/// v2: a plain decode rectangle's selection sum also carries the next step's
+/// plan and report (`QwenTensorParallelBatchDriver.serve`), so such a step
+/// pays one sealed sum and one host read; every other step keeps its own exchange.
enum QwenTensorParallelBatchWire {
- static let agreement = "qwen-tp-independent-history-batch-v1"
+ static let agreement = "qwen-tp-independent-history-batch-v2-folded-control"
static let words = 4 + 2 * (QwenBatchWire.headerWords + QwenBatchWire.replyWords)
private static let magic: Float = 0x515442
+ /// A folded plan's decode input: the token its row selects in the step
+ /// whose selection sum carries the plan (unknown when the plan is made).
+ static let carriedToken = -2
static func contribution(rank: Int, plan: QwenBatchWire.Header?, report: QwenBatchWire.Reply?) throws -> [Float] {
guard (rank == 0 && plan != nil && report == nil) || (rank == 1 && plan == nil && report != nil) else {
@@ -42,6 +49,7 @@ enum QwenTensorParallelBatchWire {
let report = try QwenBatchWire.Reply(words: Array(values.suffix(QwenBatchWire.replyWords)), expectedStep: step, lanes: lanes)
guard report.tokens.allSatisfy({ $0 >= -1 }), report.restored.allSatisfy({ $0 == 0 }),
plan.slots.allSatisfy({ !$0.confirming && $0.offers.isEmpty && $0.reusedPrefix == 0 }),
+ plan.slots.allSatisfy({ $0.inputToken >= carriedToken }),
!plan.stop || plan.slots.allSatisfy({ $0.state == .empty }) else {
throw ProbeError("Qwen TP batch control message requests an unsupported transition")
}
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift
new file mode 100644
index 0000000000..336d5165e6
--- /dev/null
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift
@@ -0,0 +1,112 @@
+import DarkbloomClusterProtocol
+import CryptoKit
+import Foundation
+import MLX
+
+/// Developer bench (`darkbloom-cluster-tp-check qwen-decode`): the batch
+/// driver's plain decode on this rank, through the real driver, native
+/// executor and the rank's group (two ranks of one Mac over the loopback
+/// ring, sealed or not). Each run decodes `width` requests together, with the
+/// next step's control exchanged a step or folded into the selection sum;
+/// the owner answers each token after `answerDelayMicroseconds`. Logs each
+/// run's decode step time and a digest of every request's retired tokens;
+/// returns whether every run retired the same tokens. Loopback timings show
+/// a step's host work and synchronization, never a pair's.
+public enum QwenTensorParallelDecodeBench {
+ struct Reserved: QwenTensorParallelBatchReservation {
+ let request: QwenLayerStageGenerationRequest
+ var deadline: UInt64 { .max }
+ var laneStateBytes: Int { 1 }
+ var joinable: Bool { true }
+ }
+
+ /// Rank 0 publishes; the owner answers "go on" once the delay passed.
+ final class Owner: QwenBatchServingHost {
+ let delay: UInt64
+ private(set) var times: [UUID: [UInt64]] = [:]
+ init(delay: UInt64) { self.delay = delay }
+ func serviceControl() throws {}
+ func publishToken(requestID: UUID, ordinal: Int, tokenID: Int, committedTokens: Int) throws {
+ times[requestID, default: []].append(DispatchTime.now().uptimeNanoseconds)
+ }
+ func publishToken(requestID: UUID, ordinal: Int, tokenID: Int, committedTokens: Int,
+ logprobs: ClusterWorkerTokenLogprobs?) throws {
+ try publishToken(requestID: requestID, ordinal: ordinal, tokenID: tokenID, committedTokens: committedTokens)
+ }
+ func awaitDecisions(_ requestIDs: [UUID]) throws -> [UUID: Bool] { throw ProbeError("The decode bench polls answers") }
+ func publishFinished(requestID: UUID, reason: ClusterWorkerFinishReason) throws {}
+ func publishPromptCache(requestID: UUID, reusedTokens: Int, storedFrontiers: [Int]) throws {}
+ func pollDecision(_ requestID: UUID) throws -> Bool? {
+ guard let last = times[requestID]?.last else { return nil }
+ return DispatchTime.now().uptimeNanoseconds - last >= delay ? true : nil
+ }
+ func publishLeft(requestID: UUID) throws {}
+ }
+
+ public static func pair(model: QwenTensorParallelModel, configuration: Data, group: any QwenTensorParallelReduction,
+ width: Int, promptTokens: Int, outputTokens: Int, sampled: Bool, folds: [Bool],
+ repeats: Int, answerDelayMicroseconds: Int, log: (String) -> Void) throws -> Bool {
+ // Request IDs carry the run's index in one byte.
+ guard case .shard(let rank, _) = model.role, (1...8).contains(width), promptTokens > 0, outputTokens > 1,
+ (1...255).contains(repeats), (1...255).contains(folds.count * repeats) else {
+ throw ProbeError("The decode bench runs a rank shard with 1 to 8 requests of at least two tokens, 255 runs at most")
+ }
+ let vocabulary = model.plan.vocabularySize, chunk = min(512, promptTokens), budget = promptTokens + outputTokens
+ let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-decode-bench", vocabularySize: vocabulary,
+ hiddenSize: model.plan.hiddenSize, activationDType: "bfloat16", maximumPromptTokens: promptTokens,
+ maximumChunkTokens: chunk, maximumOutputTokens: outputTokens, maximumContextTokens: budget)
+ var seen: String?, same = true
+ for (index, fold) in ([folds[0]] + folds.flatMap { Array(repeating: $0, count: repeats) }).enumerated() {
+ Memory.clearCache()
+ let host = try CBv2StageKVHost(model: model.model, kind: .paged, lanes: width,
+ maximumTokensPerRequest: budget, maximumChunkTokens: chunk)
+ let executor = try QwenTensorParallelNativeBatchExecutor(model: model, configuration: configuration,
+ host: host, group: group, prepare: { _, _ in nil }, completedDecode: { _ in }, completedPrefill: {},
+ releaseResources: { _ in })
+ let book = ClusterBatchLaneBook()
+ for row in 0 ..< width {
+ // Both ranks name the same requests: IDs and prompts follow the run and row.
+ let id = UUID(uuid: (UInt8(index), UInt8(row), 0, 0, 0, 0, 0x40, 0, 0x80, 0, 0, 0, 0, 0, 0, 1))
+ let sampling: ClusterWorkerSampling? = sampled ? .init(temperature: 0.7, topP: 0.9, topK: 32, minP: 0.01,
+ repetitionPenalty: 1.1, repetitionContextSize: 12, frequencyPenalty: 0.15, presencePenalty: 0.2,
+ seed: UInt64(77 + row), stream: UInt64(5 * row + 1), logitBias: []) : nil
+ let request = try QwenLayerStageGenerationRequest(profile: profile, requestID: id,
+ promptTokenIDs: (0 ..< promptTokens).map { (row * 7_919 + $0 * 104_729 + 11) % vocabulary },
+ chunkSize: chunk, outputCount: outputTokens, stopTokenIDs: [], sampling: sampling)
+ try book.reserve(id, Reserved(request: request), lanes: width)
+ try book.start(id)
+ }
+ let owner = Owner(delay: UInt64(max(0, answerDelayMicroseconds)) * 1_000)
+ let driver = try QwenTensorParallelBatchDriver(executor: executor, book: book, capacity: width,
+ vocabulary: vocabulary, foldsControl: fold)
+ var retired: [UUID: [Int]] = [:]
+ let started = DispatchTime.now().uptimeNanoseconds
+ try MLX.withError { error in
+ try driver.serve(host: owner, retiredSelection: { id, tokens, _ in retired[id] = tokens },
+ check: { try error.check() })
+ }
+ let total = Double(DispatchTime.now().uptimeNanoseconds - started) / 1e6
+ var hash = SHA256()
+ for id in retired.keys.sorted(by: { $0.uuidString < $1.uuidString }) {
+ hash.update(data: Data(retired[id]!.flatMap { withUnsafeBytes(of: Int32($0).littleEndian, Array.init) }))
+ }
+ let digest = hash.finalize().prefix(8).map { String(format: "%02x", $0) }.joined()
+ guard retired.count == width, retired.values.allSatisfy({ $0.count == outputTokens }) else {
+ throw ProbeError("The decode bench retired another set of tokens")
+ }
+ // The first run warms the kernels; it is checked, never timed.
+ if index == 0 { seen = digest; continue }
+ same = same && seen == digest
+ // Rank 0: each request's decode, from its first token to its last, per token.
+ let steps = owner.times.values.map { Double($0.last! - $0.first!) / 1e6 / Double($0.count - 1) }.sorted()
+ log("qwen-tp-decode-v1 rank=\(rank) control=\(fold ? "folded" : "exchanged") width=\(width)"
+ + " sampled=\(sampled ? 1 : 0) answer_delay_us=\(answerDelayMicroseconds) prompt=\(promptTokens)"
+ + " output=\(outputTokens) total_ms=\(String(format: "%.1f", total))"
+ + (steps.isEmpty ? "" : " step_ms_median=\(String(format: "%.3f", steps[steps.count / 2]))"
+ + " step_ms_min=\(String(format: "%.3f", steps.first!)) step_ms_max=\(String(format: "%.3f", steps.last!))")
+ + " tokens=\(digest)")
+ }
+ log("qwen-tp-decode-v1 rank=\(rank) token-check \(same ? "same-tokens" : "DIFFERENT")")
+ return same
+ }
+}
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift
index 2bf63d24ca..c1ee20d713 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift
@@ -132,8 +132,15 @@ final class QwenTensorParallelRowLinear: QuantizedLinear, Qwen35BatchDecodeProje
eval(partial)
Stream.gpu.synchronize()
}
- return Self.finish(reduction.value.allSum(partial), dtype: x.dtype)
+ let summed = reduction.value.allSum(partial)
+ Self.issuedSums?.sums.append(summed)
+ return Self.finish(summed, dtype: x.dtype)
}
+
+ /// A prompt wavefront's phase (`QwenTensorParallelPromptWavefront`): the
+ /// raw all-sums its projections issue, before rounding, so the phase can
+ /// submit them before the next chunk is built. nil changes nothing.
+ @TaskLocal static var issuedSums: QwenTensorParallelIssuedSums?
}
/// Diagnostic only: a rank's shard with no peer. `allSum` returns this rank's
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift
index 899110aa57..88d20f86b4 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift
@@ -9,6 +9,7 @@ final class QwenTensorParallelNativeBatchLane: QwenTensorParallelBatchLane {
var accepted = QwenTensorParallelAcceptedSelections()
var selectedCount = 0
var canSelectNext: Bool { !accepted.isEmpty || nextFrame?.phase == .decode }
+ var plainSelection: Bool { assistant == nil }
/// The keys of the boundaries this request captures, by boundary.
var prefixKeys: [Int: String] = [:]
/// This request's scope on the SSD tier, kept for its persist after a
@@ -29,6 +30,15 @@ final class QwenTensorParallelNativeBatchLane: QwenTensorParallelBatchLane {
guard !session.retired else { return nil }
return try? session.request.frame(sequence: session.schedule.nextSequence)
}
+ /// An assisted lane's prompt keeps one frame a step (its history takes each frame's hidden rows).
+ func promptStep(frames: Int) -> QwenLayerStageFrame? {
+ QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: assistant == nil ? frames : 1))
+ }
+ func promptStep(tokens: Int) -> QwenLayerStageFrame? {
+ let frames = session.promptFrames(limit: assistant == nil ? QwenTensorParallelPromptWavefront.maximumFrames : 1)
+ return (1...max(1, frames.count)).lazy.compactMap { QwenTensorParallelPromptWavefront.step(Array(frames.prefix($0))) }
+ .first { $0.tokenCount == tokens }
+ }
var committedTokens: Int { session.committedTokens }
var isClosed: Bool { session.retired && session.state.isClosed && resourcesReleased }
}
@@ -295,21 +305,28 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> Int? {
- guard lane.nextFrame == frame else { throw ProbeError("Qwen TP native prefill frame changed") }
+ guard lane.promptStep(tokens: frame.tokenCount) == frame else { throw ProbeError("Qwen TP native prefill frame changed") }
let output: MLXArray?
if let decoder = lane.assistant { output = try decoder.prefill(check: check) }
- else { output = try lane.session.prefill(check: check) }
+ else { output = try lane.session.prefill(step: frame, check: check) }
completedPrefill()
guard let logits = output else { return nil }
- let token = try select(logits, lanes: [lane], check: check)[0]
+ let token = try select(logits, lanes: [lane], control: nil, check: check).tokens[0]
try lane.assistant?.begin(firstToken: token)
lane.selectedCount = 1
return token
}
+ var carriesSelectionControl: Bool { true }
+
func decode(_ lanes: [Lane], tokens: [Int], check: () throws -> Void) throws -> [Int] {
+ try decode(lanes, tokens: tokens, control: { nil }, check: check).tokens
+ }
+
+ func decode(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?,
+ check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) {
try GPU.withCommandBufferLimits(QwenTensorParallelBatchSession.decodeCommandBuffers) {
- try decodeRound(lanes, tokens: tokens, check: check)
+ try decodeRound(lanes, tokens: tokens, control: control, check: check)
}
}
@@ -338,11 +355,13 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> [Int] {
+ private func decodeRound(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?,
+ check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) {
guard !lanes.isEmpty, lanes.count == tokens.count, lanes.count <= host.lanes,
Set(lanes.map { ObjectIdentifier($0) }).count == lanes.count else {
throw ProbeError("Qwen TP accepted selections require distinct scheduled lanes")
}
+ var summedControl: [Float]?
if let context = assistant, let quote = context.cohortBudget {
let frontiers = cohortFrontiers(lanes, tokens: tokens, depth: context.depth)
let eligible = frontiers.keys.sorted()
@@ -401,7 +420,14 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> [Int] {
+ /// `control`: this rank's words for the selection's own sealed sum (after
+ /// greedy rows' words, or after sampled rows' choices); both ranks' sum
+ /// of them returns. Exact limbs plus zeros leave the selection words' bits.
+ private func select(_ logits: MLXArray, lanes: [Lane], control: [Float]?,
+ check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) {
let width = lanes.count
guard (1...host.lanes).contains(width), logits.shape == [width, model.vocabularyRange.count],
lanes.allSatisfy({ !$0.isClosed && $0.session.model === model }) else {
@@ -429,7 +459,15 @@ final class QwenTensorParallelNativeBatchExecutor MLXArray {
+ guard let control else { return group.allSum(own) }
+ let count = own.size
+ let summed = group.allSum(concatenated([own.reshaped([count]), MLXArray(control)], axis: 0))
+ summedControl = summed[count ..< (count + control.count)]
+ return summed[0 ..< count].reshaped(own.shape)
+ }
let sampled = lanes.contains { $0.session.request.sampling != nil }
if sampled {
// Sampling/logprobs require complete raw rows. Each rank writes
@@ -454,7 +492,7 @@ final class QwenTensorParallelNativeBatchExecutor both[0..., 0], both[0..., 4], both[0..., 1]).asType(.int32)
nonfinite = both[0..., 2] + both[0..., 5]
}
- eval([selected] + (nonfinite.map { [$0] } ?? [])); try check()
+ eval([selected] + (nonfinite.map { [$0] } ?? []) + (summedControl.map { [$0] } ?? [])); try check()
guard nonfinite?.asArray(Float.self).allSatisfy({ $0 == 0 }) ?? true else {
throw ProbeError("Qwen TP selection rows have a non-finite logit")
}
@@ -476,6 +514,10 @@ final class QwenTensorParallelNativeBatchExecutor ClusterWorkerTokenLogprobs? {
@@ -529,10 +571,13 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws {
@@ -117,8 +121,8 @@ public enum QwenTensorParallelPrefillBench {
+ " load_s=\(format(model.loadSeconds)) active_gb=\(String(format: "%.2f", Double(Memory.activeMemory) / 1e9))")
let tokens = prompt(options.promptTokens, vocabulary: model.plan.vocabularySize)
- /// One whole prompt prefilled on a fresh request: per frame timings and the final logits' digest.
- func prefill(chunk: Int, observeLayers: ((Int) -> Bool)? = nil)
+ /// One whole prompt prefilled on a fresh request: per step timings and the final logits' digest.
+ func prefill(chunk: Int, wavefront: Int = 1, observeLayers: ((Int) -> Bool)? = nil)
throws -> (frames: [FrameTiming], digest: String, layerRows: [(frame: Int, offset: Int, times: [(Int, Double)])]) {
let budget = options.promptTokens + 8
let host = try CBv2StageKVHost(model: model.model, kind: .paged, lanes: 1,
@@ -154,14 +158,18 @@ public enum QwenTensorParallelPrefillBench {
layerRecorder.last = now
}) { try session.prefill(check: {}) }
}
- return try session.prefill(check: {})
+ guard wavefront > 1,
+ let step = QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: wavefront)) else {
+ return try session.prefill(check: {})
+ }
+ return try session.prefill(step: step, check: {})
}
let ended = phases.now()
let build = phases.span("graphConstruction.begin", "graphConstruction.end")
let evaluation = phases.span("evaluation.begin", "evaluation.end")
let wall = ms(ended - started)
frames.append(.init(wall: wall, build: build, evaluation: evaluation,
- other: wall - (build.isNaN ? 0 : build) - (evaluation.isNaN ? 0 : evaluation)))
+ other: wall - (build.isNaN ? 0 : build) - (evaluation.isNaN ? 0 : evaluation), offset: offset))
if observing { layerRows.append((index, offset, layerRecorder.layerTimes)) }
if let logits {
eval(logits)
@@ -189,13 +197,15 @@ public enum QwenTensorParallelPrefillBench {
var digests: [Int: Set] = [:]
for chunk in options.chunks {
for operations in options.operations {
- for stride in options.strides {
+ for (stride, wavefront) in options.strides.flatMap({ s in options.wavefronts.map { (s, $0) } }) {
for mode in options.modes {
reduction.mode = mode
for repeatIndex in 0 ..< max(1, options.repeats) {
reduction.reset()
let run = {
- try QwenTensorParallelBatchSession.$prefillStride.withValue(stride) { try prefill(chunk: chunk) }
+ try QwenTensorParallelBatchSession.$prefillStride.withValue(stride) {
+ try prefill(chunk: chunk, wavefront: wavefront)
+ }
}
let result = try (operations > 0
? GPU.withCommandBufferLimits(.init(operations: operations, megabytes: 1 << 20), run)
@@ -205,7 +215,7 @@ public enum QwenTensorParallelPrefillBench {
digests[chunk, default: []].insert(result.digest)
let middle = frames.count > 2 ? Array(frames.dropFirst().dropLast()) : frames
log("\(label) path=prefill chunk=\(chunk) ops=\(operations == 0 ? "process" : String(operations))"
- + " stride=\(stride) mode=\(mode.rawValue) repeat=\(repeatIndex)"
+ + " stride=\(stride) wavefront=\(wavefront) mode=\(mode.rawValue) repeat=\(repeatIndex)"
+ " total_ms=\(format(total)) tok_s=\(format(Double(options.promptTokens) / total * 1000))"
+ " frames=\(frames.count)"
+ " first_ms=\(format(frames.first?.wall ?? .nan)) last_ms=\(format(frames.last?.wall ?? .nan))"
@@ -216,8 +226,8 @@ public enum QwenTensorParallelPrefillBench {
+ " collectives=\(reduction.collectives) collective_mb=\(format(Double(reduction.collectiveBytes) / 1e6))"
+ " digest=\(result.digest)")
let curve = frames.enumerated().filter { $0.offset % max(1, frames.count / 8) == 0 || $0.offset == frames.count - 1 }
- .map { "\($0.offset * chunk):\(format($0.element.wall))" }.joined(separator: ",")
- log("\(label) path=prefill-curve chunk=\(chunk) ops=\(operations == 0 ? "process" : String(operations)) stride=\(stride) mode=\(mode.rawValue) offset_ms=\(curve)")
+ .map { "\($0.element.offset):\(format($0.element.wall))" }.joined(separator: ",")
+ log("\(label) path=prefill-curve chunk=\(chunk) ops=\(operations == 0 ? "process" : String(operations)) stride=\(stride) wavefront=\(wavefront) mode=\(mode.rawValue) offset_ms=\(curve)")
}
Memory.clearCache()
}
@@ -341,6 +351,72 @@ public enum QwenTensorParallelPrefillBench {
var best: Double { ms.values.min() ?? .nan }
}
+ /// A real pair's rank (`model`'s reduction is its group, for example the
+ /// loopback ring with sealed sums): the same prompt prefilled one frame a
+ /// step and in merged steps of up to each of `wavefronts` frames
+ /// (`QwenTensorParallelPromptWavefront`). Logs each run's step times, its
+ /// peak allocation above the memory in use before the prompt (`peak_mb`)
+ /// and the digests of its final logits, attention rows and recurrent
+ /// states; returns whether every run left this rank the same digests.
+ public static func pair(model: QwenTensorParallelModel, configuration: Data, promptTokens: Int, chunk: Int,
+ outputTokens: Int = 8, wavefronts: [Int], repeats: Int,
+ log: (String) -> Void) throws -> Bool {
+ guard case .shard(let rank, _) = model.role else { throw ProbeError("The wavefront pair runs a rank shard") }
+ let tokens = prompt(promptTokens, vocabulary: model.plan.vocabularySize)
+ let budget = promptTokens + outputTokens
+ let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-wavefront-pair",
+ vocabularySize: model.plan.vocabularySize, hiddenSize: model.plan.hiddenSize, activationDType: "bfloat16",
+ maximumPromptTokens: promptTokens, maximumChunkTokens: chunk, maximumOutputTokens: budget - promptTokens,
+ maximumContextTokens: budget)
+ func digest(_ arrays: [MLXArray]) -> String {
+ var hash = SHA256()
+ for array in arrays { eval(array); hash.update(data: array.asData(access: .copy).data) }
+ return hash.finalize().prefix(8).map { String(format: "%02x", $0) }.joined()
+ }
+ var seen: (logits: String, rows: String, recurrent: String)?
+ var same = true
+ try prefillWarmup(model: model, configuration: configuration, chunk: min(chunk, promptTokens))
+ for limit in wavefronts {
+ for repeatIndex in 0 ..< max(1, repeats) {
+ Memory.clearCache()
+ let host = try CBv2StageKVHost(model: model.model, kind: .paged, lanes: 1,
+ maximumTokensPerRequest: budget, maximumChunkTokens: chunk)
+ let request = try QwenLayerStageGenerationRequest(profile: profile, requestID: UUID(),
+ promptTokenIDs: tokens, chunkSize: chunk, outputCount: budget - promptTokens, stopTokenIDs: [])
+ let session = try QwenTensorParallelBatchSession(model: model, configuration: configuration,
+ host: host, request: request)
+ defer { try? session.retire() }
+ var steps: [(tokens: Int, ms: Double)] = []
+ var logits: MLXArray?
+ Stream.gpu.synchronize()
+ let before = Memory.activeMemory
+ Memory.peakMemory = 0
+ while session.schedule.committedPromptTokens < promptTokens {
+ let frames = session.promptFrames(limit: limit)
+ guard let step = QwenTensorParallelPromptWavefront.step(frames) else { throw ProbeError("No prompt step") }
+ let started = DispatchTime.now().uptimeNanoseconds
+ logits = try session.prefill(step: step, check: {}) ?? logits
+ if let logits { eval(logits) }
+ steps.append((step.tokenCount, ms(DispatchTime.now().uptimeNanoseconds - started)))
+ }
+ let peak = max(0, Memory.peakMemory - before)
+ let total = steps.reduce(0) { $0 + $1.ms }
+ let rows = session.state.rows.compactMap { $0?.snapshot() }.flatMap { [$0.keys, $0.values] }
+ let committed = session.state.recurrent.confirmedStateSnapshot() ?? [:]
+ let recurrent = committed.keys.sorted().flatMap { [committed[$0]!.conv!, committed[$0]!.ssm!] }
+ let value = (digest([logits ?? MLXArray(0)]), digest(rows), digest(recurrent))
+ if let seen { same = same && seen == value } else { seen = value }
+ let perFrame = steps.map { $0.ms * Double(chunk) / Double($0.tokens) }
+ log("qwen-tp-wavefront-v1 rank=\(rank) limit=\(limit) repeat=\(repeatIndex) tokens=\(promptTokens)"
+ + " steps=\(steps.count) total_ms=\(format(total)) tok_s=\(format(Double(promptTokens) / total * 1000))"
+ + " per_\(chunk)_median_ms=\(format(median(perFrame))) first_step_ms=\(format(steps.first?.ms ?? .nan))"
+ + " peak_mb=\(format(Double(peak) / 1e6)) logits=\(value.0) rows=\(value.1) recurrent=\(value.2)")
+ }
+ }
+ log("qwen-tp-wavefront-v1 rank=\(rank) digest-check \(same ? "same-bytes" : "DIFFERENT")")
+ return same
+ }
+
static func isFullAttention(model: QwenTensorParallelModel, layer: Int) -> Bool {
(layer + 1) % model.plan.fullAttentionInterval == 0
}
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift
new file mode 100644
index 0000000000..0563a5a2da
--- /dev/null
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift
@@ -0,0 +1,118 @@
+import Foundation
+import MLX
+import MLXLLM
+import MLXLMCommon
+
+/// The raw all-sums the row-parallel projections of one wavefront phase issued
+/// (`QwenTensorParallelRowLinear.issuedSums`). Confined to the thread that
+/// builds the forward, which binds it and drains it after each phase.
+final class QwenTensorParallelIssuedSums: @unchecked Sendable {
+ var sums: [MLXArray] = []
+}
+
+/// Consecutive prompt frames of one plain text lane prefilled as one graph,
+/// layer by layer (`Qwen35PromptWavefront`): a frame's mixer, its sealed sum
+/// submitted at once, the next frame's mixer while that sum crosses the link;
+/// then the MLPs the same way. At each layer a frame reads the attention rows
+/// and the recurrent state the frame before it left, so every kernel sees the
+/// frame's own rows: logits, KV rows, conv and SSM states are the per-frame
+/// prefill's bytes, and each rank issues the same sums (two a layer a frame)
+/// in the same order. Only when the GPU and the link run each piece changes.
+enum QwenTensorParallelPromptWavefront {
+ /// Frames one prompt step runs at most: 8 x 512 = 4,096 tokens a graph.
+ static let maximumFrames = 8
+ /// Frames one prompt step runs while another lane decodes, so a decoding
+ /// lane waits for one merged step about as long as for one frame alone.
+ static let framesBesideDecoding = 2
+ /// Unfinished sums a step keeps submitted: building waits for the oldest
+ /// beyond them. Unbounded, MLX encodes (and allocates) up to
+ /// `MLX_MAX_ACTIVE_TASKS` tasks of independent frames ahead, beyond
+ /// `inFlightBytes`. Evaluation order only: the sums and their order are unchanged.
+ static let sumsInFlight = 4
+ /// Diagnostic only: `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` runs one frame a
+ /// step, as before. Bound into the load agreement (`agreementFields`).
+ static let enabled = ProcessInfo.processInfo.environment["DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT"] != "0"
+ /// A bench or test's own choice (nil: `enabled`).
+ @TaskLocal static var enabledOverride: Bool?
+ static var isEnabled: Bool { enabledOverride ?? enabled }
+
+ /// Both ranks plan and validate merged prompt steps alike, or the pair refuses to load.
+ static var agreementFields: [String] {
+ ["qwen-tensor-parallel-prompt-wavefront-v1",
+ isEnabled ? "frames-\(maximumFrames)-beside-decoding-\(framesBesideDecoding)" : "off"]
+ }
+
+ /// The frames one prompt step runs from frame `sequence`: consecutive
+ /// prompt frames, at most `limit`, ending at the prompt's end or at the
+ /// first capture frontier (`frontiers`, the capture plan's boundaries)
+ /// they reach. Empty when frame `sequence` is not a prompt frame.
+ static func frames(request: QwenLayerStageGenerationRequest, from sequence: Int, frontiers: [Int],
+ limit: Int) -> [QwenLayerStageFrame] {
+ guard let first = try? request.frame(sequence: sequence), first.phase == .prefill else { return [] }
+ var frames = [first]
+ while frames.count < limit, let last = frames.last, !last.finalPromptChunk,
+ !frontiers.contains(last.tokenOffset + last.tokenCount),
+ let next = try? request.frame(sequence: last.sequence + 1), next.phase == .prefill {
+ frames.append(next)
+ }
+ return frames
+ }
+
+ /// What one merged step holds beyond a lone frame, charged with the
+ /// owner's shared prompt workspace (`QwenTensorParallelBatchBudget`): for
+ /// each further frame, its two FP32 partials and two FP32 sums in flight
+ /// and its BF16 residual rows, five times the frame's collective payload,
+ /// allocator-bounded. Zero for routed experts, whose frames never merge.
+ static func inFlightBytes(plan: QwenTensorParallelPlan, chunkTokens: Int,
+ allocationBound: (Int) throws -> Int) throws -> Int {
+ guard !plan.routedExperts else { return 0 }
+ let payload = try QwenLongPrefillCheckedBytes.product([chunkTokens, plan.maximumPartialBytesPerToken])
+ return try QwenLongPrefillCheckedBytes.product([allocationBound(payload), 5, maximumFrames - 1])
+ }
+
+ /// The step the driver plans and both ranks validate for `frames`: the
+ /// first frame's sequence and offset, every frame's tokens, the last's final flag.
+ static func step(_ frames: [QwenLayerStageFrame]) -> QwenLayerStageFrame? {
+ guard let first = frames.first, let last = frames.last else { return nil }
+ return .init(sequence: first.sequence, phase: .prefill, tokenOffset: first.tokenOffset,
+ tokenCount: frames.reduce(0) { $0 + $1.tokenCount }, finalPromptChunk: last.finalPromptChunk)
+ }
+
+ /// Whether a lane's frames merge: text without media inputs, native rows
+ /// (a packed step is checked whole before it runs), a dense model.
+ static func merges(model: QwenTensorParallelModel, request: QwenLayerStageGenerationRequest,
+ mediaInputs: Bool, packedStorage: Bool) -> Bool {
+ isEnabled && !mediaInputs && request.qwenMedia == nil && !packedStorage
+ && Qwen35PromptWavefront.supports(model.model)
+ }
+
+ /// `frames`' forward inside one `CBv2OwnedRequestState.run`: the
+ /// wavefront, each phase's sums submitted as soon as it is built (at most
+ /// `sumsInFlight` unfinished); returns what the last frame's own forward
+ /// returns (its evaluation handle, or the final prompt row's logits from
+ /// the whole frame's head, as `QwenTensorParallelBatchSession.prompt` keeps them).
+ static func forward(model: QwenTensorParallelModel, request: QwenLayerStageGenerationRequest,
+ frames: [QwenLayerStageFrame], caches: [any CBv2AttendingLayerCache],
+ evaluation: CBv2RecurrentStateEvaluation) -> MLXArray {
+ let chunks = frames.map { frame in
+ MLXArray(request.promptTokenIDs[frame.tokenOffset ..< (frame.tokenOffset + frame.tokenCount)]
+ .map(Int32.init)).reshaped([1, frame.tokenCount])
+ }
+ let final = frames.last?.finalPromptChunk ?? false
+ let issued = QwenTensorParallelIssuedSums()
+ var submitted: [MLXArray] = []
+ let outputs = QwenTensorParallelRowLinear.$issuedSums.withValue(issued) {
+ Qwen35PromptWavefront.prefill(model.model, chunks: chunks, finalChunk: final,
+ caches: caches.map { $0 as! any KVCache }, recurrentState: evaluation) {
+ guard !issued.sums.isEmpty else { return }
+ asyncEval(issued.sums)
+ submitted += issued.sums
+ issued.sums.removeAll()
+ while submitted.count > sumsInFlight { eval(submitted.removeFirst()) }
+ }
+ }
+ // Earlier frames' last rows run too, as each frame's own output did; nothing reads them.
+ asyncEval(Array(outputs.dropLast()))
+ return final ? outputs[outputs.count - 1][0..., -1, 0...] : outputs[outputs.count - 1]
+ }
+}
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift
index 992761457b..b21b35b35c 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift
@@ -19,9 +19,10 @@ import MLX
/// history and gathers;
/// - the workspaces every lane shares, at the longest context any held
/// request has and never below LOAD's: the full-history gather bank of one
-/// prompt frame (the batch driver runs at most one a step), the frame's
-/// attention scores and the decode and verify transients grow with the
-/// context; the pool slack, logits and casts do not.
+/// prompt step (the batch driver runs one lane's prompt step at a time), the
+/// frame's attention scores and the decode and verify transients grow with
+/// the context; the pool slack, logits, casts and a merged prompt step's
+/// further frames in flight (`QwenTensorParallelPromptWavefront.inFlightBytes`) do not.
///
/// The pages themselves grow with the request (`CBv2OwnedRequestState.growReservation`);
/// the charge is the whole request's, admitted once at reservation and held
diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift
index 571651c16b..23215453c5 100644
--- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift
+++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift
@@ -197,6 +197,7 @@ public final class QwenTensorParallelResidentRuntime {
+ QwenTensorParallelTargetWindow.agreementFields
+ QwenTensorParallelPlan.arithmeticAgreementFields(routedExperts: admission.specification.routedExperts != nil)
+ QwenTensorParallelBatchSession.decodeAgreementFields
+ + QwenTensorParallelPromptWavefront.agreementFields
+ ["qwen-tensor-parallel-prefix-v2", prefixEnabled ? "on" : "off"]
+ (prefixEnabled ? prefixRecords.loadAgreementFields : [])
+ (mediaEnabled ? [ClusterQwenMedia.contract, Qwen3VLMediaProcessor.policyID] : [])
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ContextAdmissionTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ContextAdmissionTests.swift
index f2a0dfd81f..69228e1d5e 100644
--- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ContextAdmissionTests.swift
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ContextAdmissionTests.swift
@@ -72,6 +72,42 @@ struct ContextAdmissionTests {
}
}
+ /// A decode step's command buffers can keep every attending layer's
+ /// temporaries alive at once (`QwenLayerStageSession.decodeCommandBuffers`):
+ /// the transient prices those rows whenever they outnumber the prompt frame's.
+ @Test func theDecodeStepPricesEveryAttendingLayersRowsAtOnce() throws {
+ let g = try Self.geometry()
+ func bytes(chunk: Int, decodeRows: Int, attention: Bool = true) throws -> Int {
+ try QwenResidentPrefillTransient.bytes(geometry: g, stageHasAttention: attention, chunkTokens: chunk,
+ contextTokens: 30_848, decodeRows: decodeRows)
+ }
+ let row = 24 * 30_848 * 4 + 24 * 256 * 4
+ // A one-token prompt on a stage of eight attending layers decodes eight rows at once.
+ #expect(try bytes(chunk: 1, decodeRows: 8) == 8 * row)
+ // A verify window of four rows on each of them: 32.
+ #expect(try bytes(chunk: 2, decodeRows: 32) == 32 * row)
+ // A 512-row frame already covers them, so the LOAD quote's charge is unchanged.
+ #expect(try bytes(chunk: 512, decodeRows: 32) == (try bytes(chunk: 512, decodeRows: 0)))
+ // The decoding rank of a phase split prices the producer stage's layers too.
+ #expect(try bytes(chunk: 1, decodeRows: 8, attention: false) == 8 * row)
+ #expect(try bytes(chunk: 1, decodeRows: 0, attention: false) == 0)
+ #expect(throws: (any Error).self) { _ = try bytes(chunk: 1, decodeRows: -1) }
+ }
+
+ @Test func eachModeNamesTheRowsAndLayersItsDecodeRuns() {
+ let terms = QwenMTPTerms.standard
+ #expect(LayerStageDecodeShape(mode: .pipeline, rank: 1, speculativeTerms: nil) == .plain)
+ #expect(LayerStageDecodeShape(mode: .pipelineCompactDecode, rank: 0, speculativeTerms: nil) == .plain)
+ #expect(LayerStageDecodeShape(mode: .pipelineMTP, rank: 0, speculativeTerms: terms)
+ == .init(rows: terms.depth + 1))
+ // A phase split's producer rank hands its prompt state over and runs no decode forward.
+ #expect(LayerStageDecodeShape(mode: .phaseSplit, rank: 0, speculativeTerms: nil) == .init(rows: 0))
+ #expect(LayerStageDecodeShape(mode: .phaseSplitMTP, rank: 0, speculativeTerms: terms) == .init(rows: 0))
+ #expect(LayerStageDecodeShape(mode: .phaseSplit, rank: 1, speculativeTerms: nil) == .init(wholeModel: true))
+ #expect(LayerStageDecodeShape(mode: .phaseSplitMTP, rank: 1, speculativeTerms: terms)
+ == .init(rows: terms.depth + 1, wholeModel: true))
+ }
+
@Test func theLargestAdmissibleContextIsFoundByBinarySearch() throws {
var calls = 0
func below(_ limit: Int) -> (Int) throws -> Bool { { calls += 1; return $0 <= limit } }
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSResidentAdmissionTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSResidentAdmissionTests.swift
index dbda882c71..89bb58b1da 100644
--- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSResidentAdmissionTests.swift
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSResidentAdmissionTests.swift
@@ -155,6 +155,25 @@ struct GPTOSSResidentAdmissionTests {
}
}
+ /// A decode step's command buffers can keep the whole step in flight
+ /// (`QwenLayerStageSession.decodeCommandBuffers`), so the workspace prices
+ /// every full-attention layer's decode row at once.
+ @Test func workspacePricesEveryFullAttentionLayersDecodeRow() throws {
+ let admission = try Self.admit(identity: try Self.identity())
+ for rank in 0...1 {
+ func workspace(chunk: Int) throws -> (bytes: Int, layers: Int) {
+ let budget = try GPTOSSRequestStateBudget.estimate(specification: admission.specification,
+ layers: admission.plan.stages[rank].layers, rank: rank, maximumTokens: 8320, chunkSize: chunk,
+ bound: { $0 })
+ return (budget.workspaceBytes, budget.fullAttentionLayers)
+ }
+ let capacity = 8448 + 256, heads = admission.specification.queryHeads
+ let one = try workspace(chunk: 1)
+ #expect(one.layers > 1 && one.bytes == heads * one.layers * capacity * 4)
+ #expect(try workspace(chunk: 512).bytes == heads * 512 * (8448 + 512) * 4)
+ }
+ }
+
@Test func theCapabilityRecordIsThisAdaptersOwn() throws {
let spec = try Self.specification()
let capability = try GPTOSSResidentCapabilityMetadata.describe(configuration: try Self.fixture("configuration"),
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/IndependentHistoryBatchDriverTestSupport.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/IndependentHistoryBatchDriverTestSupport.swift
index 7c22581dea..ee58970eb7 100644
--- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/IndependentHistoryBatchDriverTestSupport.swift
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/IndependentHistoryBatchDriverTestSupport.swift
@@ -102,6 +102,8 @@ final class HistoryBatchTestSession: IndependentHistoryBatchSession {
var frames: [QwenLayerStageFrame] = [], history: [Int] = []
var committedTokens: Int { history.count }
var isClosed = false, isFailed = false, failCleanup = false
+ /// Qwen TP driver tests: false stands for an assisted row, which never folds control.
+ var plainSelection = true
var nextFrame: QwenLayerStageFrame? { try? request.frame(sequence: frames.count) }
init(_ request: QwenLayerStageGenerationRequest) { self.request = request }
static func next(_ history: [Int]) -> Int { (history.reduce(0, +) + history.count * 7) % 64 }
@@ -125,7 +127,16 @@ final class HistoryBatchTestSession: IndependentHistoryBatchSession {
history += tokens; frames.append(frame)
}
func finishGeneration(_ reason: QwenLayerStageGenerationFinishReason, selectedTokenCount: Int, lastTokenID: Int) throws {
- guard lastTokenID == Self.next(history), selectedTokenCount == frames.count - request.prefillFrameCount + 1 else {
+ try finishGeneration(reason, selectedTokenCount: selectedTokenCount, lastTokenID: lastTokenID, discarded: 0)
+ }
+ /// `discarded`: decode forwards whose selection a client stop dropped
+ /// (the last selected token kept is then the input of the forward after it).
+ func finishGeneration(_ reason: QwenLayerStageGenerationFinishReason, selectedTokenCount: Int, lastTokenID: Int,
+ discarded: Int) throws {
+ let decoded = frames.count - request.prefillFrameCount
+ guard discarded == 0 || (reason == .clientStop && discarded == 1),
+ lastTokenID == (discarded == 0 ? Self.next(history) : history[history.count - discarded]),
+ selectedTokenCount == decoded + 1 - discarded else {
throw ProbeError("Test finish differs from committed history")
}
guard !failCleanup else { throw ProbeError("Injected native retirement failure") }
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoDecodeCommandBufferTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoDecodeCommandBufferTests.swift
new file mode 100644
index 0000000000..3413c32ba4
--- /dev/null
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoDecodeCommandBufferTests.swift
@@ -0,0 +1,219 @@
+import Foundation
+import MLX
+import MLXLLM
+import MLXLMCommon
+import MLXNN
+import Testing
+@testable import DarkbloomClusterRuntime
+
+// MiMo stage decode, verify windows and lane steps encode under
+// `MiMoLayerStageSession.decodeCommandBuffers` (100 operations a buffer, no
+// input-size bound) instead of the rank's 16-operation guard. Only where
+// command buffers end may move. Two random MiMo stages are driven as the stage
+// session drives them: the prompt under the guard, then decode once under the
+// guard and once under the decode limits. Every residual that crosses the cut,
+// every logits row and every cache array must be the same bytes, on the
+// ordinary caches and on request-owned pages (one request, and two decoded as
+// lanes). A tiny bfloat16 model, and one shaped and quantized like the
+// registered row (MXFP4 experts, affine 8-bit projections, key width 192 and
+// value width 128), whose guard commits at every expert launch as the
+// registered row's does (`bankGuard`). No artifact, collective or network.
+
+@Suite("MiMo decode command buffers change no byte (random stages)", .serialized)
+struct MiMoDecodeCommandBufferTests {
+ typealias P = MiMoStagePipelineEquivalenceTests
+ /// The rank's own limits as a worker starts it (`ClusterWorkerEnvironmentGuards`):
+ /// 16 operations, MLX's per-chip size bound.
+ static let rankGuard = GPU.CommandBufferLimits(operations: 16, megabytes: 0)
+ /// The guard scaled to the quantized model's banks. MLX's size bound counts
+ /// Mi elements of distinct inputs, so at 1 each 2 Mi-element bank commits a
+ /// buffer, as each registered 256 Mi-element bank does at MLX's own 40-50.
+ static let bankGuard = GPU.CommandBufferLimits(operations: 16, megabytes: 1)
+
+ /// Hidden 1,024, 16 experts of width 1,024 (8 a token), key width 192 and
+ /// value width 128 on four layers (full, sliding, sliding, full).
+ static let kernelShapeConfiguration = Data("""
+ {"model_type":"mimo_v2","architectures":["MiMoV2ForCausalLM"],"hidden_size":1024,"intermediate_size":2048,
+ "moe_intermediate_size":1024,"vocab_size":4096,"num_hidden_layers":4,"max_position_embeddings":4096,
+ "sliding_window":8,"sliding_window_size":8,"num_nextn_predict_layers":0,
+ "hybrid_layer_pattern":[0,1,1,0],"moe_layer_freq":[0,1,1,1],"partial_rotary_factor":0.334,
+ "attention_value_scale":0.707,"layernorm_epsilon":0.000001,"attention_projection_layout":"fused_qkv",
+ "moe_router_dtype":"bfloat16","hidden_act":"silu","dtype":"bfloat16","attention_bias":false,
+ "tie_word_embeddings":false,"attention_dropout":0.0,"scoring_func":"sigmoid","topk_method":"noaux_tc",
+ "n_routed_experts":16,"num_experts_per_tok":8,"n_group":1,"topk_group":1,"norm_topk_prob":true,
+ "num_attention_heads":8,"num_key_value_heads":2,"head_dim":192,"v_head_dim":128,"rope_theta":10000000.0,
+ "add_full_attention_sink_bias":false,"swa_num_attention_heads":8,"swa_num_key_value_heads":4,
+ "swa_head_dim":192,"swa_v_head_dim":128,"swa_rope_theta":10000.0,"add_swa_attention_sink_bias":true,
+ "eos_token_id":[1,2],"pad_token_id":0}
+ """.utf8)
+
+ /// The two stages of `cut` with random bfloat16 weights, quantized like
+ /// the registered row when asked (the router stays bfloat16).
+ static func randomStages(_ data: Data, cut: Int, quantized: Bool) throws -> [MiMoV26TextModel] {
+ let plan = try MiMoLayerStagePlan(configuration: data, cut: cut)
+ return try plan.stages.map { stage in
+ try withRandomState(MLXRandom.RandomState(seed: UInt64(23 + stage.index))) { () throws -> MiMoV26TextModel in
+ let model = try MiMoV26TextModel(plan.productConfiguration(stage: stage.index))
+ let cast = model.parameters().flattened().map { name, value in
+ (name, name.hasSuffix("e_score_correction_bias") ? value : value.asType(.bfloat16))
+ }
+ try model.update(parameters: ModuleParameters.unflattened(cast), verify: [.noUnusedKeys, .shapeMismatch])
+ if quantized {
+ quantize(model: model, filter: { path, _ -> (groupSize: Int, bits: Int, mode: QuantizationMode)? in
+ path.contains("switch_mlp") ? (32, 4, .mxfp4) : (64, 8, .affine)
+ })
+ }
+ eval(model)
+ model.freeze()
+ return model
+ }
+ }
+ }
+
+ static func greedy(_ row: MLXArray) -> Int { Int(argMax(row, axis: -1).item(UInt32.self)) }
+
+ /// One request through both stages: the prompt in frames of four under
+ /// the rank's guard, then five decode steps, a verify window of three
+ /// drafts rolled back to its first two rows on both stages, and four more
+ /// steps, each under `limits`. Every residual that crossed the cut, every
+ /// logits row and, at the end, every cache array, in order, as bytes.
+ static func trace(_ stages: [MiMoV26TextModel], paged: Bool, prompt: [Int],
+ decode limits: GPU.CommandBufferLimits) throws -> [Data] {
+ let pages = try paged ? stages.map { try $0.makeIndependentHistoryCaches() } : []
+ let caches: [[KVCache]] = paged ? pages.map { $0 as [KVCache] } : stages.map { $0.newCache() }
+ let last = stages[0].configuration.numHiddenLayers - 1
+ let vocabulary = stages[1].configuration.vocabularySize
+ var recorded: [Data] = []
+ func forward(_ tokens: [Int], logitsStart: Int) throws -> MLXArray {
+ let input = MLXArray(tokens.map(Int32.init)).reshaped([1, tokens.count])
+ let produced = try paged
+ ? stages[0].forwardIndependentHistory(inputIDs: input, caches: pages[0], captureLayers: [last])
+ : stages[0].forward(inputIDs: input, cache: caches[0], captureLayers: [last])
+ let residual = try #require(produced.layerFeatures[last])
+ eval([residual] + caches[0].flatMap { $0.innerState() })
+ // What crosses the cut is bytes: the consumer gets a copy with no graph behind it.
+ let crossed = MLXArray(residual.asData().data, residual.shape, dtype: residual.dtype)
+ let consumed = try paged
+ ? stages[1].forwardIndependentHistory(embeddings: crossed, caches: pages[1], logitsStart: logitsStart)
+ : stages[1].forward(embeddings: crossed, cache: caches[1], logitsStart: logitsStart)
+ eval([consumed.logits] + caches[1].flatMap { $0.innerState() })
+ recorded += [residual.asData().data, consumed.logits.asData().data]
+ return consumed.logits
+ }
+ var logits = MLXArray(0)
+ try GPU.withCommandBufferLimits(rankGuard) {
+ var offset = 0
+ while offset < prompt.count {
+ let part = Array(prompt[offset.. [Data] {
+ let last = stages[0].configuration.numHiddenLayers - 1
+ let histories = try prompts.map { _ in try stages.map { try $0.makeIndependentHistoryCaches() } }
+ var recorded: [Data] = [], tokens: [Int] = []
+ try GPU.withCommandBufferLimits(rankGuard) {
+ for (request, prompt) in prompts.enumerated() {
+ var offset = 0, logits = MLXArray(0)
+ while offset < prompt.count {
+ let part = Array(prompt[offset.., chunk: Int, rows: Int = 1) throws -> Int {
+ try MiMoRequestStateBudget.estimate(specification: spec, layers: layers, rank: 0, maximumTokens: 8320,
+ chunkSize: chunk, decodeRows: rows, bound: { $0 }).workspaceBytes
+ }
+ // Layers 0..<32 hold six full-attention layers: a one-token prompt still decodes over all six.
+ #expect(try workspace(0..<32, chunk: 1) == 64 * 6 * 8448 * 4)
+ #expect(try workspace(0..<32, chunk: 2, rows: 4) == 64 * 24 * 8448 * 4)
+ // A 512-token prompt frame already covers a four-row window on each of them.
+ #expect(try workspace(0..<32, chunk: 512, rows: 4) == 64 * 512 * 8448 * 4)
+ // Layers without full attention score only their window.
+ #expect(try workspace(1..<5, chunk: 1, rows: 4) == 0)
+ for rows in [0, 513] {
+ #expect(throws: (any Error).self) { _ = try workspace(0..<32, chunk: 1, rows: rows) }
+ }
+ }
+
@Test func admissionTakesTheClosedIdentityOnBothRanksAtEveryCut() throws {
let spec = try Self.specification()
for cut in spec.supportedCuts {
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PipelineDecodeCommandBufferTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PipelineDecodeCommandBufferTests.swift
new file mode 100644
index 0000000000..105e4ea8f2
--- /dev/null
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PipelineDecodeCommandBufferTests.swift
@@ -0,0 +1,483 @@
+import Foundation
+import MLX
+import MLXLLM
+import MLXLMCommon
+import MLXNN
+import Testing
+@testable import DarkbloomClusterRuntime
+
+// Pipeline decode of every remaining layer-stage family encodes under
+// `QwenLayerStageSession.decodeCommandBuffers` (100 operations a buffer, no
+// input-size bound) instead of the rank's 16-operation guard. Only where
+// command buffers end may move. Random synthetic stages run as the stage
+// sessions drive them: the prompt under the rank's guard, then the decode
+// work under a guard and again under the decode limits. Every output row,
+// verify window and cache or state array must be the same bytes.
+//
+// The reference run decodes under the rank's guard, or under `bankGuard` where
+// registered banks exceed MLX's size bound and the synthetic stage can
+// reproduce it: routed Qwen and Gemma, whose expert banks of 2 Mi elements each
+// commit a buffer, as each registered bank does. The Nemotron and GLM fixtures
+// are too small for any size bound, so they, like every family, also run with
+// a buffer every second dispatch (`everyOperation`), a finer partition than one
+// buffer per bank. No artifact, collective or network.
+
+@Suite("Pipeline decode command buffers change no byte (random stages)", .serialized)
+struct PipelineDecodeCommandBufferTests {
+ /// The rank's own limits as a worker starts it (`ClusterWorkerEnvironmentGuards`):
+ /// 16 operations, MLX's per-chip size bound.
+ static let rankGuard = GPU.CommandBufferLimits(operations: 16, megabytes: 0)
+ /// MLX's size bound counts Mi elements of distinct inputs: at 1, every
+ /// bank of 2 Mi elements or more commits a buffer, as a registered bank
+ /// of 60-256 Mi elements does at MLX's own 40-50.
+ static let bankGuard = GPU.CommandBufferLimits(operations: 16, megabytes: 1)
+ /// A buffer ends after every second dispatch: no coarser than one a bank.
+ static let everyOperation = GPU.CommandBufferLimits(operations: 1, megabytes: 1)
+ static let decodeLimits = QwenLayerStageSession.decodeCommandBuffers
+
+ static func requireSameBytes(_ guarded: [Data], _ decoded: [Data], _ label: String) {
+ #expect(guarded.count == decoded.count && !guarded.isEmpty, "\(label): \(guarded.count) against \(decoded.count) arrays")
+ let first = zip(guarded, decoded).enumerated().first { $0.element.0 != $0.element.1 }?.offset
+ #expect(first == nil, "\(label): array \(first ?? -1) of \(guarded.count) differs")
+ }
+
+ static func argmax(_ row: MLXArray) -> Int { Int(argMax(row, axis: -1).item(UInt32.self)) }
+ static func bytes(_ array: MLXArray) -> Data { eval(array); return array.asData(access: .copy).data }
+
+ @Test func everyPipelineTakesTheTensorParallelDecodeLimits() {
+ #expect(QwenLayerStageSession.decodeCommandBuffers == .init(operations: 100, megabytes: 1 << 20))
+ #expect(QwenLayerStageSession.decodeCommandBuffers == GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers)
+ #expect(QwenLayerStageSession.decodeCommandBuffers == QwenTensorParallelBatchSession.decodeCommandBuffers)
+ }
+
+ // MARK: Qwen 3.5 stages (`QwenLayerStageSession`): dense, and routed experts
+
+ static let qwenVocabulary = 320
+
+ /// Four layers (two of full attention, head width 256 with 16 query and 2
+ /// KV heads, as the routed rows), 32 experts of width 512 (8 a token): each
+ /// expert bank holds 2 Mi elements at 4 bits.
+ static func routedConfiguration() throws -> Data {
+ let text: [String: Any] = [
+ "model_type": "qwen3_5_moe_text", "vocab_size": qwenVocabulary, "hidden_size": 1024,
+ "intermediate_size": 1024, "num_hidden_layers": 4, "full_attention_interval": 2, "head_dim": 256,
+ "num_attention_heads": 16, "num_key_value_heads": 2, "linear_conv_kernel_dim": 4,
+ "linear_key_head_dim": 64, "linear_num_key_heads": 4, "linear_num_value_heads": 8, "linear_value_head_dim": 64,
+ "num_experts": 32, "num_experts_per_tok": 8, "moe_intermediate_size": 512,
+ "shared_expert_intermediate_size": 512, "norm_topk_prob": true,
+ "max_position_embeddings": 4096, "rms_norm_eps": 1e-6, "tie_word_embeddings": false,
+ "rope_theta": 10_000_000, "partial_rotary_factor": 0.25, "attention_bias": false,
+ "mtp_num_hidden_layers": 0,
+ ]
+ return try JSONSerialization.data(withJSONObject: ["model_type": "qwen3_5_moe", "text_config": text] as [String: Any],
+ options: [.sortedKeys])
+ }
+
+ /// The routed rows' class (`QwenRoutedExpertStageModel`).
+ static func routedModel() throws -> Qwen35MoEModel {
+ let data = try routedConfiguration()
+ let model = try withRandomState(MLXRandom.RandomState(seed: 29)) { () -> Qwen35MoEModel in
+ let model = Qwen35MoEModel(try JSONDecoder().decode(Qwen35Configuration.self, from: data))
+ var scaled: [String: MLXArray] = [:]
+ for (name, value) in model.parameters().flattened() {
+ scaled[name] = (MLXRandom.normal(value.shape) * 0.05).asType(.bfloat16)
+ }
+ try model.update(parameters: ModuleParameters.unflattened(scaled), verify: [.noUnusedKeys, .shapeMismatch])
+ return model
+ }
+ quantize(model: model, filter: { _, _ -> (groupSize: Int, bits: Int, mode: QuantizationMode)? in (64, 4, .affine) })
+ model.freeze(); eval(model)
+ let banks = model.parameters().flattened().filter { $0.0.contains("switch_mlp") && $0.0.hasSuffix(".weight") }
+ #expect(!banks.isEmpty && banks.allSatisfy { $0.1.size >= 2 << 20 }, "every routed bank holds 2 Mi elements")
+ return model
+ }
+
+ struct QwenStage {
+ let model: any CBv2RecurrentCaptureMTPForwardable & LanguageModel
+ let configuration: Data
+ let layers: Int
+ }
+
+ static func qwenStages() throws -> [(label: String, stage: QwenStage, guarded: GPU.CommandBufferLimits)] {
+ [("dense", QwenStage(model: try CBv2PagedBatchSyntheticTests.model(),
+ configuration: try CBv2PagedBatchSyntheticTests.configuration(), layers: 8), rankGuard),
+ ("routed", QwenStage(model: try routedModel(), configuration: try routedConfiguration(), layers: 4), bankGuard)]
+ }
+
+ static func qwenState(_ stage: QwenStage, host: CBv2StageKVHost, promptCount: Int) throws -> CBv2OwnedRequestState {
+ let geometry = try CBv2RequestGeometry(model: stage.model, family: .qwen35,
+ feedForwardKind: QwenRoutedExpertStageModel.feedForwardKind(stage.model), layerCount: stage.layers,
+ vocabularySize: qwenVocabulary, configurationData: stage.configuration, maximumTokens: 64, host: host)
+ return try CBv2OwnedRequestState(geometry: geometry, promptCount: promptCount, outputCount: 64 - promptCount)
+ }
+
+ static func qwenRows(_ stage: QwenStage, _ tokens: [[Int]], caches: [any CBv2AttendingLayerCache],
+ evaluations: [CBv2RecurrentStateEvaluation]) -> MLXArray {
+ let input = MLXArray(tokens.flatMap { $0.map(Int32.init) }).reshaped([tokens.count, tokens[0].count])
+ return stage.model.cbv2ForwardWithHidden(input, caches: caches.map { $0 as! any KVCache },
+ recurrentState: evaluations, positionIds: nil).logits[0..., -1, 0...]
+ }
+
+ /// The prompt in frames of eight under the rank's guard; the last row.
+ static func qwenPrefill(_ stage: QwenStage, _ state: CBv2OwnedRequestState, _ prompt: [Int]) throws -> MLXArray {
+ try GPU.withCommandBufferLimits(rankGuard) {
+ var offset = 0, last = MLXArray(0)
+ while offset < prompt.count {
+ let part = Array(prompt[offset.. [Data] {
+ let prompt = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4]
+ let host = try CBv2StageKVHost(model: stage.model, kind: .paged, lanes: 1, maximumTokensPerRequest: 64,
+ maximumChunkTokens: 8)
+ let state = try qwenState(stage, host: host, promptCount: prompt.count)
+ var row = try qwenPrefill(stage, state, prompt)
+ var recorded = [bytes(row)]
+ try GPU.withCommandBufferLimits(limits) {
+ var token = argmax(row)
+ func step() throws {
+ let fed = token
+ row = try state.run(tokenCount: 1, check: {}, forward: { caches, evaluation in
+ qwenRows(stage, [[fed]], caches: caches, evaluations: [evaluation])
+ }, validateOutput: { _ in })
+ recorded.append(bytes(row)); token = argmax(row)
+ }
+ for _ in 0..<4 { try step() }
+ let window = [token, (token + 17) % qwenVocabulary, (token + 42) % qwenVocabulary, (token + 7) % qwenVocabulary]
+ let input = MLXArray(window.map(Int32.init)).reshaped([1, window.count])
+ let built = try state.beginWindow(tokenCount: window.count) { caches, evaluation in
+ [stage.model.cbv2ForwardWithHiddenCaptured(input, caches: caches.map { $0 as! any KVCache },
+ recurrentState: [evaluation], positionIds: nil).logits]
+ }
+ eval(built.outputs + built.roots)
+ try state.confirmWindow(check: {})
+ recorded.append(bytes(built.outputs[0]))
+ eval(try state.settleWindow(keeping: 2))
+ try state.confirmSettled(check: {})
+ token = argmax(built.outputs[0][0, 1, 0...])
+ for _ in 0..<3 { try step() }
+ }
+ let snapshot = try state.snapshot(globalLayerIndices: Array(0.. [Data] {
+ let prompts = [[3, 1, 4, 1, 5, 9, 2], [6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8]]
+ let host = try CBv2StageKVHost(model: stage.model, kind: .paged, lanes: 2, maximumTokensPerRequest: 64,
+ maximumChunkTokens: 8)
+ var states: [CBv2OwnedRequestState] = [], tokens: [Int] = []
+ for prompt in prompts {
+ let state = try qwenState(stage, host: host, promptCount: prompt.count)
+ tokens.append(argmax(try qwenPrefill(stage, state, prompt)))
+ states.append(state)
+ }
+ var recorded: [Data] = []
+ try GPU.withCommandBufferLimits(limits) {
+ for _ in 0..<5 {
+ let fed = tokens
+ let rows = try CBv2OwnedRequestState.runBatch(states, tokenCount: 1, check: {},
+ forward: { caches, evaluations in
+ Qwen35BatchDecodeScope.$enabled.withValue(true) {
+ qwenRows(stage, fed.map { [$0] }, caches: caches, evaluations: evaluations)
+ }
+ }, validateOutput: { _ in })
+ recorded.append(bytes(rows))
+ tokens = (0.. [Data] {
+ typealias N = NemotronStageSyntheticTests
+ let configuration = try N.configuration()
+ let plan = try QwenLayerStagePlan(configuration: configuration, ranges: [0..<5, 5.. MLXArray {
+ let frame = QwenLayerStageFrame(sequence: sequence, phase: phase, tokenOffset: offset,
+ tokenCount: tokens.count, finalPromptChunk: final)
+ let input = MLXArray(tokens.map(Int32.init)).reshaped([1, tokens.count])
+ let residual = try states[0].run(tokenCount: tokens.count, check: {}, forward: { caches, evaluation in
+ NemotronStageForward.run(model: models[0], stageIndex: 0, tokens: input, residual: nil,
+ caches: caches, evaluation: evaluation, frame: frame)
+ }, validateOutput: { _ in })
+ // What crosses the cut is bytes: the consumer gets a copy with no graph behind it.
+ let crossed = MLXArray(bytes(residual), residual.shape, dtype: residual.dtype)
+ let output = try states[1].run(tokenCount: tokens.count, check: {}, forward: { caches, evaluation in
+ NemotronStageForward.run(model: models[1], stageIndex: 1, tokens: input, residual: crossed,
+ caches: caches, evaluation: evaluation, frame: frame)
+ }, validateOutput: { _ in })
+ recorded += [bytes(residual), bytes(output)]
+ offset += tokens.count; sequence += 1
+ return output
+ }
+ var row = try GPU.withCommandBufferLimits(rankGuard) { () -> MLXArray in
+ _ = try frame(prompt[0], .prefill)
+ return try frame(prompt[1], .prefill, final: true)
+ }
+ try GPU.withCommandBufferLimits(limits) {
+ for _ in 0..<6 { row = try frame([argmax(row)], .decode) }
+ }
+ for (index, state) in states.enumerated() {
+ recorded += try state.snapshot(globalLayerIndices: plan.stages[index].layers.map(\.globalIndex),
+ includeBytes: true, check: {}).entries.compactMap(\.bytes)
+ try state.retire()
+ }
+ return recorded
+ }
+
+ @Test func nemotronStagesDecodeTheSameBytes() throws {
+ let reference = try Self.nemotronTrace(decode: Self.rankGuard)
+ Self.requireSameBytes(reference, try Self.nemotronTrace(decode: Self.everyOperation), "nemotron, a buffer per operation")
+ Self.requireSameBytes(reference, try Self.nemotronTrace(decode: Self.decodeLimits), "nemotron")
+ }
+
+ // MARK: Gemma 4 (the decoder its layer-stage seam runs through `QwenLayerStageSession`)
+
+ /// Two layers (one sliding with a window of 8, one full), keys equal to
+ /// values, head widths 256 and 512 as registered; 16 experts of width
+ /// 1,024 (8 a token) beside the dense MLP: each expert bank holds 2 Mi
+ /// elements at 4 bits.
+ static func gemmaModel() throws -> Gemma4TextModel {
+ let configuration: [String: Any] = [
+ "model_type": "gemma4_text", "hidden_size": 1024, "num_hidden_layers": 2,
+ "intermediate_size": 512, "num_attention_heads": 4, "head_dim": 256,
+ "global_head_dim": 512, "num_key_value_heads": 2, "num_global_key_value_heads": 1,
+ "num_kv_shared_layers": 0, "hidden_size_per_layer_input": 0,
+ "vocab_size": 512, "tie_word_embeddings": true, "attention_k_eq_v": true,
+ "enable_moe_block": true, "num_experts": 16, "top_k_experts": 8,
+ "moe_intermediate_size": 1024, "sliding_window": 8,
+ "layer_types": ["sliding_attention", "full_attention"],
+ "use_double_wide_mlp": false, "final_logit_softcapping": 30.0,
+ "rope_parameters": [
+ "full_attention": ["partial_rotary_factor": 0.25, "rope_theta": 1_000_000.0, "rope_type": "proportional"],
+ "sliding_attention": ["rope_theta": 10_000.0, "rope_type": "default"]],
+ ]
+ let config = try JSONDecoder().decode(Gemma4TextConfiguration.self,
+ from: JSONSerialization.data(withJSONObject: configuration))
+ let model = withRandomState(MLXRandom.RandomState(seed: 31)) { Gemma4TextModel(config) }
+ model.update(parameters: ModuleParameters.unflattened(model.parameters().flattened().map {
+ ($0.0, $0.1.asType(.bfloat16))
+ }))
+ quantize(model: model, filter: { path, _ -> (groupSize: Int, bits: Int, mode: QuantizationMode)? in
+ (64, path.hasSuffix(".router.proj") ? 8 : 4, .affine)
+ })
+ model.freeze(); eval(model)
+ return model
+ }
+
+ /// Two requests on contiguous request-owned KV: each prompt a token at a
+ /// time under the rank's guard; then four steps of the first alone and
+ /// four of both as lanes, under `limits`. Every logits row, then every
+ /// committed key and value array.
+ static func gemmaTrace(_ model: Gemma4TextModel, decode limits: GPU.CommandBufferLimits) throws -> [Data] {
+ let backend = CBv2ContiguousKVBackend(config: .init(bytesCapacity: 256 << 20, kvDType: .bfloat16))
+ let prompts = [[5, 17, 3, 44, 96, 8, 21, 60, 2, 33, 71], [9, 4, 81, 2, 15, 66, 30]]
+ let requests = try prompts.map {
+ try backend.makeSequenceState(layerKinds: model.cbv2LayerKinds, promptLength: $0.count, maxLength: 64)
+ }
+ let caches = try model.newCacheV2 { CBv2LayerCache(layerIndex: $0, kind: $1) }
+ defer {
+ for cache in caches { cache.setRows([]) }
+ for request in requests { backend.release(request) }
+ }
+ func forward(_ rows: [Int], _ tokens: [Int]) -> MLXArray {
+ for index in caches.indices { caches[index].setRows(rows.map { requests[$0][index]! }) }
+ let input = MLXArray(tokens.map(Int32.init), [rows.count, 1])
+ let output = Gemma4BatchDecodeScope.withDecodeFrame(tokens: input, enabled: rows.count > 1) {
+ model(input, cache: caches.map { $0 as! any KVCache })
+ }
+ eval([output] + caches.flatMap { ($0 as! any KVCache).innerState() })
+ return output[0..., -1, 0...]
+ }
+ var recorded: [Data] = [], next: [Int] = []
+ try GPU.withCommandBufferLimits(rankGuard) {
+ for (index, prompt) in prompts.enumerated() {
+ var row = MLXArray(0)
+ for token in prompt { row = forward([index], [token]) }
+ next.append(argmax(row))
+ }
+ }
+ GPU.withCommandBufferLimits(limits) {
+ for _ in 0..<4 {
+ let row = forward([0], [next[0]])
+ recorded.append(bytes(row)); next[0] = argmax(row)
+ }
+ for _ in 0..<4 {
+ let rows = forward([0, 1], next)
+ recorded.append(bytes(rows)); next = (0..<2).map { argmax(rows[$0]) }
+ }
+ }
+ for request in requests {
+ for layer in request {
+ guard let snapshot = layer?.snapshot() else { continue }
+ recorded += [bytes(snapshot.keys), bytes(snapshot.values)]
+ }
+ }
+ return recorded
+ }
+
+ @Test func gemmaDecoderDecodesTheSameBytes() throws {
+ let model = try Self.gemmaModel()
+ let banks = model.parameters().flattened().filter { $0.0.contains("experts") && $0.0.hasSuffix(".weight") }
+ #expect(!banks.isEmpty && banks.allSatisfy { $0.1.size >= 2 << 20 }, "every expert bank holds 2 Mi elements")
+ let reference = try Self.gemmaTrace(model, decode: Self.bankGuard)
+ Self.requireSameBytes(reference, try Self.gemmaTrace(model, decode: Self.everyOperation), "gemma, a buffer per operation")
+ Self.requireSameBytes(reference, try Self.gemmaTrace(model, decode: Self.decodeLimits), "gemma")
+ }
+
+ // MARK: GPT-OSS stages (`GPTOSSLayerStageSession`)
+
+ static func gptossPages(_ model: GPTOSSModel) -> [GPTOSSPagedKVCache] {
+ model.cbv2LayerKinds.map { kind in
+ switch kind.attention {
+ case .full: GPTOSSPagedKVCache()
+ case .slidingWindow(let window): GPTOSSPagedKVCache(window: window)
+ }
+ }
+ }
+
+ /// Two stages of a packed four-layer GPT-OSS (MXFP4 experts, affine 8-bit
+ /// projections, learned sinks, a window of 8) on paged caches: two prompts
+ /// alone under the rank's guard, then four steps of the first
+ /// (`GPTOSSLayerStageSession.decode`'s forward) and four of both as lanes
+ /// (`GPTOSSBatchForward.decode`), under `limits`. Every residual and
+ /// logits row, then every cache array.
+ static func gptossTrace(decode limits: GPU.CommandBufferLimits) throws -> [Data] {
+ typealias F = GPTOSSNativeTestFixture
+ let whole = try F.model(layers: 0..<4, dtype: .bfloat16)
+ let producer = try F.stage(from: whole, layers: 0..<2, first: true, dtype: .bfloat16)
+ let consumer = try F.stage(from: whole, layers: 2..<4, first: false, dtype: .bfloat16)
+ let head = try #require(consumer.namedModules().first { $0.0 == "lm_head" }?.1 as? Linear)
+ let prompts = [[3, 9, 17, 2, 41, 6, 12, 30, 7, 55, 1], [8, 20, 33, 5, 61]]
+ let before = prompts.map { _ in gptossPages(producer) }, after = prompts.map { _ in gptossPages(consumer) }
+ var recorded: [Data] = [], next: [Int] = []
+ func one(_ lane: Int, _ tokens: [Int]) -> MLXArray {
+ let input = MLXArray(tokens.map(Int32.init)).reshaped([1, tokens.count])
+ let residual = producer.model(input, cache: before[lane])
+ eval([residual] + before[lane].flatMap { $0.innerState() })
+ let crossed = MLXArray(bytes(residual), residual.shape, dtype: residual.dtype)
+ let row = head(consumer.model(input, cache: after[lane], inputEmbeddings: crossed))[0..., -1, 0...]
+ eval([row] + after[lane].flatMap { $0.innerState() })
+ recorded += [bytes(residual), bytes(row)]
+ return row
+ }
+ GPU.withCommandBufferLimits(rankGuard) {
+ for (lane, prompt) in prompts.enumerated() { next.append(argmax(one(lane, prompt))) }
+ }
+ try GPU.withCommandBufferLimits(limits) {
+ for _ in 0..<4 { next[0] = argmax(one(0, [next[0]])) }
+ for _ in 0..<4 {
+ let residual = try GPTOSSBatchForward.decode(model: producer, head: nil, stageIndex: 0, hiddenSize: 64,
+ vocabularySize: 64, dtype: .bfloat16, tokens: next, residual: nil, histories: before, check: {})
+ let crossed = MLXArray(bytes(residual), residual.shape, dtype: residual.dtype)
+ let rows = try GPTOSSBatchForward.decode(model: consumer, head: head, stageIndex: 1, hiddenSize: 64,
+ vocabularySize: 64, dtype: .bfloat16, tokens: next, residual: crossed, histories: after, check: {})
+ recorded += [bytes(residual), bytes(rows)]
+ next = (0..<2).map { argmax(rows[$0]) }
+ }
+ }
+ recorded += (before + after).flatMap { $0.flatMap { $0.state } }.map(bytes)
+ return recorded
+ }
+
+ @Test func gptossStagesDecodeTheSameBytes() throws {
+ let reference = try Self.gptossTrace(decode: Self.rankGuard)
+ Self.requireSameBytes(reference, try Self.gptossTrace(decode: Self.everyOperation), "gpt-oss, a buffer per operation")
+ Self.requireSameBytes(reference, try Self.gptossTrace(decode: Self.decodeLimits), "gpt-oss")
+ }
+
+ // MARK: GLM stages (`GLM5NextStageSession`)
+
+ /// The verified stages of the synthetic GLM artifact (`GLM5NextStageSessionTests`,
+ /// cut 3 of 8 layers), driven as `GLM5NextStageSession.forward` drives them:
+ /// the prompt in two frames under the rank's guard, then five decode
+ /// frames under `limits`. Every four-stream boundary, every logits row and,
+ /// at the end, every cache array of both stages.
+ static func glmTrace(decode limits: GPU.CommandBufferLimits) throws -> [Data] {
+ let fixture = try GLM5NextStageSessionTests.Fixture()
+ defer { try? fixture.first.close(check: {}); try? fixture.last.close(check: {}) }
+ let stages = [fixture.firstStage.model, fixture.lastStage.model]
+ let caches = stages.map { $0.newCache() }
+ var recorded: [Data] = []
+ func frame(_ tokens: [Int], logits: Bool) throws -> MLXArray? {
+ let produced = try stages[0].prepareForward(tokens: MLXArray(tokens.map(Int32.init), [1, tokens.count]),
+ cache: caches[0])
+ try produced.commit { roots in eval(roots); Stream.gpu.synchronize() }
+ guard case .streams(let streams) = produced.output else { throw ProbeError("GLM producer returned no streams") }
+ let crossed = MLXArray(bytes(streams), streams.shape, dtype: streams.dtype)
+ let consumed = try stages[1].prepareForward(streams: crossed, cache: caches[1], readout: logits ? .lastToken : .none)
+ try consumed.commit { roots in eval(roots); Stream.gpu.synchronize() }
+ recorded.append(bytes(streams))
+ guard logits, case .final(let value) = consumed.output else { return nil }
+ let row = value.logits[0..., -1, 0...]
+ recorded.append(bytes(row))
+ return row
+ }
+ var row = try GPU.withCommandBufferLimits(rankGuard) { () -> MLXArray in
+ _ = try frame([4, 5], logits: false)
+ return try #require(try frame([6, 7], logits: true))
+ }
+ try GPU.withCommandBufferLimits(limits) {
+ for _ in 0..<5 { row = try #require(try frame([argmax(row)], logits: true)) }
+ }
+ recorded += caches.flatMap { $0.layers.flatMap { $0.innerState() } }.map(bytes)
+ return recorded
+ }
+
+ @Test func glmStagesDecodeTheSameBytes() throws {
+ let reference = try Self.glmTrace(decode: Self.rankGuard)
+ Self.requireSameBytes(reference, try Self.glmTrace(decode: Self.everyOperation), "glm, a buffer per operation")
+ Self.requireSameBytes(reference, try Self.glmTrace(decode: Self.decodeLimits), "glm")
+ }
+}
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift
index f00db705af..4357c1a722 100644
--- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift
@@ -44,9 +44,12 @@ struct QwenTensorParallelBatchBudgetTests {
#expect(candidate.perLaneStateBytes - candidate.prefix.captureBytes < scalar.stateBytes)
#expect(candidate.allowance.requestBytesExcludingCollectives == lanes * candidate.perLaneStateBytes + candidate.sharedBytesExcludingCollectives)
let logits = 3 * bound(lanes * plan.vocabularySize * 4)
+ // A merged prompt step's seven further frames: five frames' FP32 payload each.
+ let wavefront = plan.routedExperts ? 0 : 7 * 5 * bound(chunk * plan.maximumPartialBytesPerToken)
+ #expect(wavefront == 367_001_600, "the 27B rank's merged-step charge at 512-row frames")
#expect(candidate.sharedBytesExcludingCollectives == scalar.fusionBytes + scalar.transientBytes + logits
+ 2 * scalar.projectionConstantBytes + candidate.pagedPoolSlackBytes
- + candidate.promptGatherBytes)
+ + candidate.promptGatherBytes + wavefront)
#expect(candidate.pagedPoolSlackBytes >= 2 * CBv2StageKVHost.segmentBytes)
// The underlying host's entire admitted page capacity, its gather
// and replacement pages fit inside the full state charges, at every
@@ -66,7 +69,8 @@ struct QwenTensorParallelBatchBudgetTests {
for context in [1, 17, 512, 65536] {
let candidate = try QwenTensorParallelBatchBudget.derive(geometry: family.geometry, plan: plan,
tensors: tensors, maximumTokens: context, chunkSize: 1, lanes: 8, paged: true, allocationBound: bound)
- let payload = max(8 * plan.vocabularySize * 4, QwenTensorParallelBatchWire.words * 4, 8 * plan.maximumPartialBytesPerToken)
+ let payload = max(8 * plan.vocabularySize * 4, (QwenTensorParallelBatchWire.words + 6 * 8) * 4,
+ 8 * plan.maximumPartialBytesPerToken)
#expect(candidate.allowance.maximumCollectivePayloadBytes == payload)
#expect(candidate.allowance.maximumCollectiveFrameBytes == payload + QwenTensorParallelSealCodec.frameOverhead)
#expect(candidate.allowance.collectiveScratchBytes == 8 * bound(payload + QwenTensorParallelSealCodec.frameOverhead))
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchDriverTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchDriverTests.swift
index a13d9f3a1a..385d4c8101 100644
--- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchDriverTests.swift
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchDriverTests.swift
@@ -18,6 +18,8 @@ struct QwenTensorParallelBatchDriverTests {
let condition = NSCondition()
var values: [Int: [Float]] = [:], result: [Float] = []
var leaving = 0, failure: Error?
+ /// Every completed collective's word count, in order.
+ var lengths: [Int] = []
func fail(_ error: Error) { condition.withLock { failure = error; condition.broadcast() } }
func sum(_ words: [Float], rank: Int) throws -> [Float] {
condition.lock(); defer { condition.unlock() }
@@ -30,7 +32,7 @@ struct QwenTensorParallelBatchDriverTests {
values[rank] = words
if values.count == 2 {
guard values[0]!.count == values[1]!.count else { throw ProbeError("TP test collective shapes differ") }
- result = zip(values[0]!, values[1]!).map(+); leaving = 2; condition.broadcast()
+ result = zip(values[0]!, values[1]!).map(+); leaving = 2; lengths.append(result.count); condition.broadcast()
} else {
while leaving == 0 && failure == nil {
guard condition.wait(until: deadline) else { throw ProbeError("TP test peer exchange timed out") }
@@ -95,8 +97,11 @@ struct QwenTensorParallelBatchDriverTests {
let rank: Int
var sessions: [UUID: HistoryBatchTestSession] = [:]
var maximumWidth = 0, failCleanup = Set()
+ /// Requests opened as assisted rows, and each rectangle whose selection sum carried control words.
+ var assisted = Set(), folded: [[UUID]] = []
var afterDecode: ([UUID]) throws -> Void = { _ in }
var preparing: (UUID) throws -> Void = { _ in }
+ var carriesSelectionControl = true
init(pair: Pair, rank: Int) { self.pair = pair; self.rank = rank }
func exchange(_ words: [Float], check: () throws -> Void) throws -> [Float] { try check(); return try pair.link.sum(words, rank: rank) }
func discard(_ reservation: Reservation) throws {
@@ -108,6 +113,7 @@ struct QwenTensorParallelBatchDriverTests {
try preparing(reservation.request.requestID)
let session = HistoryBatchTestSession(reservation.request)
session.failCleanup = failCleanup.contains(reservation.request.requestID)
+ session.plainSelection = !assisted.contains(reservation.request.requestID)
sessions[reservation.request.requestID] = session; return session
}
func prefill(_ lane: HistoryBatchTestSession, frame: QwenLayerStageFrame, check: () throws -> Void) throws -> Int? {
@@ -115,14 +121,26 @@ struct QwenTensorParallelBatchDriverTests {
return frame.finalPromptChunk ? HistoryBatchTestSession.next(lane.history) : nil
}
func decode(_ lanes: [HistoryBatchTestSession], tokens: [Int], check: () throws -> Void) throws -> [Int] {
+ try decode(lanes, tokens: tokens, control: { nil }, check: check).tokens
+ }
+ func decode(_ lanes: [HistoryBatchTestSession], tokens: [Int], control: () throws -> [Float]?,
+ check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) {
for (lane, token) in zip(lanes, tokens) { try lane.advance([token]) }
maximumWidth = max(maximumWidth, lanes.count)
try afterDecode(lanes.map { $0.request.requestID })
- return lanes.map { HistoryBatchTestSession.next($0.history) }
+ let selected = lanes.map { HistoryBatchTestSession.next($0.history) }
+ guard let words = try control() else { return (selected, nil) }
+ guard carriesSelectionControl else { throw ProbeError("Control words reached an executor that cannot carry them") }
+ folded.append(lanes.map { $0.request.requestID })
+ // The selection's own sum: rank 0's tokens, rank 1's zeros, then both ranks' control words.
+ let sum = try pair.link.sum(selected.map { rank == 0 ? Float($0) : 0 } + words, rank: rank)
+ return (sum.prefix(lanes.count).map { Int($0) }, Array(sum.dropFirst(lanes.count)))
}
func retire(_ lane: HistoryBatchTestSession, reason: QwenLayerStageGenerationFinishReason?, selected: Int, last: Int?) throws {
- if let reason, let last { try lane.finishGeneration(reason, selectedTokenCount: selected, lastTokenID: last) }
- else { try lane.cancel() }
+ if let reason, let last {
+ let decoded = lane.frames.count - lane.request.prefillFrameCount
+ try lane.finishGeneration(reason, selectedTokenCount: selected, lastTokenID: last, discarded: decoded + 1 - selected)
+ } else { try lane.cancel() }
pair.set("closed-\(rank)-\(lane.request.requestID)")
}
func confirmedRetirement(_ lane: HistoryBatchTestSession, clean: Bool) throws {
@@ -377,6 +395,211 @@ struct QwenTensorParallelBatchDriverTests {
#expect(pair.hosts.allSatisfy { $0.finished.isEmpty && $0.left.isEmpty })
}
+ final class Retired: @unchecked Sendable {
+ let lock = NSLock()
+ var byRank: [[UUID: ([Int], QwenLayerStageGenerationFinishReason)]] = [[:], [:]]
+ }
+ /// Each rank's retired selections (`retiredSelection`), per request.
+ private func runRetiring(_ pair: Pair) throws -> [[UUID: ([Int], QwenLayerStageGenerationFinishReason)]] {
+ let group = DispatchGroup(), retired = Retired()
+ for rank in 0...1 {
+ group.enter()
+ DispatchQueue.global().async {
+ defer { group.leave() }
+ do {
+ let driver = try QwenTensorParallelBatchDriver(executor: pair.native[rank], book: pair.books[rank],
+ capacity: pair.capacity, vocabulary: 64, now: pair.now)
+ try driver.serve(host: pair.hosts[rank], retiredSelection: { id, tokens, reason in
+ retired.lock.withLock { retired.byRank[rank][id] = (tokens, reason) }
+ }, check: {})
+ } catch {
+ pair.lock.withLock { pair.errors.append(String(describing: error)) }; pair.link.fail(error)
+ }
+ }
+ }
+ guard group.wait(timeout: .now() + 15) == .success else { throw ProbeError("TP test driver timed out") }
+ if !pair.errors.isEmpty { throw ProbeError(pair.errors.joined(separator: "; ")) }
+ return retired.lock.withLock { retired.byRank }
+ }
+
+ /// A steady decode step's plan and report ride its own selection sum:
+ /// between the first and the last decode, one collective a step, of the
+ /// rectangle's words and the control words, and no separate exchange.
+ @Test func controlWordsRideTheSelectionSumOfEverySteadyDecodeStep() throws {
+ let pair = Pair(1), request = try pair.request(output: 24)
+ try pair.reserve(request)
+ try pair.run()
+ #expect(pair.hosts[0].tokens[request.requestID] == HistoryBatchTestSession.oracle(request))
+ for rank in 0...1 { #expect(pair.hosts[rank].finished[request.requestID] == .length) }
+ let folded = 1 + QwenTensorParallelBatchWire.words, lengths = pair.link.lengths
+ let first = try #require(lengths.firstIndex(of: folded)), last = try #require(lengths.lastIndex(of: folded))
+ // The prompt's step selects the first token; every other token is one folded step.
+ #expect(lengths.filter { $0 == folded }.count == request.outputCount - 1)
+ #expect(lengths[first...last].allSatisfy { $0 == folded })
+ #expect(!lengths[first...last].contains(QwenTensorParallelBatchWire.words))
+ }
+
+ /// An executor whose selection sum cannot carry control words keeps the
+ /// exchange every step, with today's tokens.
+ @Test func anExecutorWithoutSelectionControlKeepsTheExchange() throws {
+ let pair = Pair(1), request = try pair.request(output: 24)
+ for rank in 0...1 { pair.native[rank].carriesSelectionControl = false }
+ try pair.reserve(request)
+ try pair.run()
+ #expect(pair.hosts[0].tokens[request.requestID] == HistoryBatchTestSession.oracle(request))
+ for rank in 0...1 {
+ #expect(pair.hosts[rank].finished[request.requestID] == .length)
+ #expect(pair.native[rank].folded.isEmpty)
+ }
+ #expect(!pair.link.lengths.contains(1 + QwenTensorParallelBatchWire.words))
+ }
+
+ /// Both ranks end a row at its stop token or output count from the tokens
+ /// in the sum: the same kept tokens and reason, and no forward after it.
+ @Test func eosAndLengthAreDerivedIdenticallyOnBothRanks() throws {
+ // The stop token comes after every prompt step, so the step selecting it
+ // carries the next plan: alone, and beside rows that end at their length.
+ for width in [1, 4] {
+ let pair = Pair(width)
+ let oracle = HistoryBatchTestSession.oracle(try pair.request(length: 3, output: 24))
+ let at = try #require(oracle.indices.last { !oracle.prefix($0).contains(oracle[$0]) })
+ let stopping = try pair.request(length: 3, output: 24, stops: [oracle[at]])
+ var expected: [(QwenLayerStageGenerationRequest, QwenLayerStageGenerationFinishReason)] = [(stopping, .eos)]
+ if width > 1 {
+ expected += [(try pair.request(length: 2, output: 9), .length), (try pair.request(length: 4, output: 16), .length)]
+ }
+ for (request, _) in expected { try pair.reserve(request) }
+ let retired = try runRetiring(pair)
+ for (request, reason) in expected {
+ let tokens = HistoryBatchTestSession.oracle(request)
+ #expect(pair.hosts[0].tokens[request.requestID] == tokens)
+ for rank in 0...1 {
+ #expect(retired[rank][request.requestID]?.0 == tokens)
+ #expect(retired[rank][request.requestID]?.1 == reason)
+ #expect(pair.hosts[rank].finished[request.requestID] == .init(rawValue: reason.rawValue))
+ // Prompt frames, then one decode forward per token after the first: none after the end.
+ let session = try #require(pair.native[rank].sessions[request.requestID])
+ #expect(session.frames.count == request.prefillFrameCount + tokens.count - 1)
+ }
+ }
+ #expect(at >= 4 && HistoryBatchTestSession.oracle(stopping).count == at + 1)
+ #expect(pair.link.lengths.contains { $0 > QwenTensorParallelBatchWire.words })
+ }
+ }
+
+ /// The owner's stop answer reaches the plan one step late: the row has
+ /// already selected one more token, which is never published, and both
+ /// ranks retire the tokens the owner saw as a clean client stop.
+ @Test func aHostStopAppliesOneStepLateAndItsExtraTokenIsNeverPublished() throws {
+ // Every decode after the first is a folded step; a stop answer to
+ // a later token reaches the plan one step after the forward on it.
+ for stopAfter in [2, 6] {
+ let pair = Pair(1), stopped = try pair.request(output: 24)
+ try pair.reserve(stopped)
+ pair.hosts[0].answer = { id in pair.hosts[0].tokens[id]?.count == stopAfter ? false : true }
+ let retired = try runRetiring(pair)
+ let seen = Array(HistoryBatchTestSession.oracle(stopped).prefix(stopAfter))
+ #expect(pair.hosts[0].tokens[stopped.requestID] == seen)
+ for rank in 0...1 {
+ #expect(retired[rank][stopped.requestID]?.0 == seen)
+ #expect(retired[rank][stopped.requestID]?.1 == .clientStop)
+ #expect(pair.hosts[rank].finished[stopped.requestID] == .clientStop)
+ #expect(pair.flag("prefix-true-\(rank)-\(stopped.requestID)"))
+ // The extra step ran (a decode forward on the last seen token) and was dropped.
+ let session = try #require(pair.native[rank].sessions[stopped.requestID])
+ #expect(session.frames.count == stopped.prefillFrameCount + stopAfter)
+ }
+ }
+ }
+
+ /// A token selected before the owner answered the one before it is held
+ /// on rank 0. A stop answer drops it: it is never published, and both
+ /// ranks retire the tokens the owner saw.
+ @Test func aStopAnswerDropsAHeldTokenThatWasNeverPublished() throws {
+ // The owner answers each token at the second poll after it, so the row
+ // selects its 3rd, 5th, ... token before the answer to the one before.
+ for stopAfter in [2, 4] {
+ let pair = Pair(1), stopped = try pair.request(output: 24)
+ try pair.reserve(stopped)
+ var polls = 0
+ pair.hosts[0].onToken = { _, _ in polls = 0 }
+ pair.hosts[0].answer = { id in
+ polls += 1
+ return polls < 2 ? nil : pair.hosts[0].tokens[id]?.count != stopAfter
+ }
+ let retired = try runRetiring(pair)
+ let seen = Array(HistoryBatchTestSession.oracle(stopped).prefix(stopAfter))
+ #expect(pair.hosts[0].tokens[stopped.requestID] == seen)
+ for rank in 0...1 {
+ #expect(retired[rank][stopped.requestID]?.0 == seen)
+ #expect(retired[rank][stopped.requestID]?.1 == .clientStop)
+ #expect(pair.hosts[rank].finished[stopped.requestID] == .clientStop)
+ #expect(pair.flag("prefix-true-\(rank)-\(stopped.requestID)"))
+ // The held token's forward ran on both ranks; only the seen tokens retire.
+ let session = try #require(pair.native[rank].sessions[stopped.requestID])
+ #expect(session.frames.count == stopped.prefillFrameCount + stopAfter)
+ }
+ }
+ }
+
+ /// Joins, a prompt beside decoding rows and a cancellation interleave
+ /// folded steps with exchanged ones; every row keeps its own tokens, and
+ /// a cancelled row publishes nothing after the cancellation was seen.
+ @Test func joinsPromptsAndCancellationInterleaveWithFoldedSteps() throws {
+ let pair = Pair(4), first = try pair.request(output: 20), cancelled = try pair.request(length: 4, output: 20)
+ let late = try pair.request(length: 40, output: 8)
+ try pair.reserve(first); try pair.reserve(cancelled)
+ pair.hosts[0].onToken = { id, ordinal in
+ if id == first.requestID && ordinal == 3 && !pair.flag("late") {
+ pair.set("late"); try pair.reserve(late, rank: 0)
+ }
+ if id == cancelled.requestID && ordinal == 5 { pair.books[0].cancel(cancelled.requestID) }
+ }
+ pair.hosts[1].onControl = {
+ if pair.flag("late") && !pair.flag("late-1") { pair.set("late-1"); try pair.reserve(late, rank: 1) }
+ }
+ try pair.run()
+ for request in [first, late] {
+ #expect(pair.hosts[0].tokens[request.requestID] == HistoryBatchTestSession.oracle(request))
+ for rank in 0...1 { #expect(pair.hosts[rank].finished[request.requestID] == .length) }
+ }
+ #expect(pair.hosts[0].tokens[cancelled.requestID] == Array(HistoryBatchTestSession.oracle(cancelled).prefix(6)))
+ for rank in 0...1 {
+ #expect(pair.hosts[rank].left.contains(cancelled.requestID))
+ #expect(pair.books[rank].isEmpty)
+ }
+ let lengths = pair.link.lengths
+ #expect(lengths.contains { $0 > QwenTensorParallelBatchWire.words })
+ #expect(lengths.contains(QwenTensorParallelBatchWire.words))
+ }
+
+ /// An assisted row keeps today's exchange and gate beside plain rows: no
+ /// rectangle that holds it carries control words, and it decodes only once
+ /// the owner answered its last published token. Plain rows fold again
+ /// once it has left.
+ @Test func assistedRowsKeepTheirExchangeAndGate() throws {
+ let pair = Pair(2), plain = try pair.request(output: 20), assisted = try pair.request(length: 5, output: 6)
+ for rank in 0...1 { pair.native[rank].assisted = [assisted.requestID] }
+ try pair.reserve(plain); try pair.reserve(assisted)
+ var answered: [UUID: Int] = [:], aheadOfAnswer = 0, besidePlain = 0
+ pair.hosts[0].answer = { id in answered[id] = pair.hosts[0].tokens[id]?.count; return true }
+ pair.native[0].afterDecode = { ids in
+ guard ids.contains(assisted.requestID) else { return }
+ if ids.count > 1 { besidePlain += 1 }
+ if answered[assisted.requestID] != pair.hosts[0].tokens[assisted.requestID]?.count { aheadOfAnswer += 1 }
+ }
+ try pair.run()
+ for request in [plain, assisted] {
+ #expect(pair.hosts[0].tokens[request.requestID] == HistoryBatchTestSession.oracle(request))
+ for rank in 0...1 { #expect(pair.hosts[rank].finished[request.requestID] == .length) }
+ }
+ #expect(besidePlain > 0 && aheadOfAnswer == 0)
+ for rank in 0...1 {
+ #expect(!pair.native[rank].folded.isEmpty)
+ #expect(pair.native[rank].folded.allSatisfy { !$0.contains(assisted.requestID) })
+ }
+ }
+
@Test func controlWordsPreserveEveryInt32BitAndRejectMalformedAndStaleFrames() throws {
var slot = QwenBatchWire.Slot(state: .active, requestID: UUID())
slot.fingerprintWords = [Int32.min, Int32.max, -1, 0]
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift
index 5365fd4e6d..b0984f3b83 100644
--- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift
@@ -52,6 +52,7 @@ struct QwenTensorParallelBatchSessionTests {
var executor: QwenTensorParallelNativeBatchExecutor?
var nativeLanes: [QwenTensorParallelNativeBatchLane] = []
var selected: [Int] = []
+ var control: [Float]?
var failure: Error?
var releaseAttempts = 0, rejectRelease = false
init(_ model: QwenTensorParallelModel, lanes: Int, maximumTokens: Int = 256) throws {
@@ -569,6 +570,22 @@ struct QwenTensorParallelBatchSessionTests {
tensors: tensors, hiddenSize: 256)
}
+ /// The next step's plan and report ride a plain rectangle's selection sum
+ /// (after greedy rows' words, or sampled rows' choices): every token and
+ /// logprob equals the same cohort's without them, at widths 1 to 8, and
+ /// both ranks read back both ranks' exact control words.
+ @Test func controlWordsInTheSelectionSumKeepTokensAndLogprobs() throws {
+ let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 256, layers: 4, heads: 4, kvHeads: 2, vocabulary: 256)
+ var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any]
+ var text = root["text_config"] as! [String: Any]
+ text["full_attention_interval"] = 1; root["text_config"] = text
+ var tensors = fixture.tensors.filter { !$0.0.contains(".linear_attn.") }
+ let attention = fixture.tensors.filter { $0.0.contains(".layers.3.self_attn.") }
+ for layer in 0..<3 { tensors += attention.map { ($0.0.replacingOccurrences(of: ".layers.3.", with: ".layers.\(layer)."), $0.1) } }
+ try verifyMixedSampling(configuration: try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]),
+ tensors: tensors, hiddenSize: 256, foldedControl: true)
+ }
+
/// Routed experts on the native executor: greedy, sampled and
/// logprob rows of one cohort select what each selects alone, on the GPU
/// (the product backend), as the hybrid fixtures run.
@@ -578,7 +595,10 @@ struct QwenTensorParallelBatchSessionTests {
try verifyMixedSampling(configuration: fixture.configuration, tensors: fixture.tensors, hiddenSize: 128)
}
- private func verifyMixedSampling(configuration fixture: Data, tensors: [(String, MLXArray)], hiddenSize: Int) throws {
+ /// `foldedControl`: the candidate cohort's selection sums also carry a
+ /// plan and report (as a folded driver step does).
+ private func verifyMixedSampling(configuration fixture: Data, tensors: [(String, MLXArray)], hiddenSize: Int,
+ foldedControl: Bool = false) throws {
try Device.withDefaultDevice(device) {
var root = try JSONSerialization.jsonObject(with: fixture) as! [String: Any]
var text = root["text_config"] as! [String: Any]
@@ -587,7 +607,7 @@ struct QwenTensorParallelBatchSessionTests {
let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-selection-tiny", vocabularySize: 256,
hiddenSize: hiddenSize, activationDType: "bfloat16", maximumPromptTokens: 128,
maximumChunkTokens: 64, maximumOutputTokens: 16, maximumContextTokens: 256)
- for width in [2, 4, 8] {
+ for width in foldedControl ? [1, 2, 4, 8] : [2, 4, 8] {
func pair(_ wire: Rendezvous) throws -> [Owned] {
try (0..<2).map { rank in
let reduction = Rank(rank, wire)
@@ -642,12 +662,28 @@ struct QwenTensorParallelBatchSessionTests {
#expect(reference[1].selected[row] == expected[row])
}
let order = (0.. 1 ? 2 : 0)
try parallel(candidate) { owner in
+ let rank = owner.executor!.rank
+ let words = foldedControl ? try QwenTensorParallelBatchWire.contribution(rank: rank,
+ plan: rank == 0 ? plan : nil, report: rank == 1 ? report : nil) : nil
let output = try owner.executor!.decode(order.map { owner.nativeLanes[$0] },
- tokens: order.map { owner.selected[$0] }, check: {})
- for (slot, row) in order.enumerated() { owner.selected[row] = output[slot] }
+ tokens: order.map { owner.selected[$0] }, control: { words }, check: {})
+ owner.control = output.control
+ for (slot, row) in order.enumerated() { owner.selected[row] = output.tokens[slot] }
}
for rank in 0..<2 { #expect(candidate[rank].selected == expected, "width=\(width) step=\(step) rank=\(rank)") }
+ for rank in 0..<2 where foldedControl {
+ let read = try QwenTensorParallelBatchWire.read(try #require(candidate[rank].control),
+ step: step, lanes: width)
+ #expect(read.0 == plan && read.1 == report, "width=\(width) step=\(step) rank=\(rank)")
+ }
for row in 0.. QwenLayerStageGenerationRequest {
+ let chunk = min(chunk, prompt)
+ let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-prompt-wavefront", vocabularySize: 256,
+ hiddenSize: 2048, activationDType: "bfloat16", maximumPromptTokens: prompt, maximumChunkTokens: chunk,
+ maximumOutputTokens: output, maximumContextTokens: prompt + output)
+ let request = try QwenLayerStageGenerationRequest(profile: profile, requestID: UUID(),
+ promptTokenIDs: (0.. MLXArray {
+ let values = array.asType(.float32).asArray(Float.self)
+ condition.lock()
+ while leaving > 0 { condition.wait() }
+ let generation = step
+ inputs[rank] = values; shapes[rank] = array.shape
+ if inputs.count == 2 {
+ precondition(shapes[0] == shapes[1], "ranks summed different shapes")
+ result = zip(inputs[0]!, inputs[1]!).map(+)
+ leaving = 2; condition.broadcast()
+ } else {
+ let deadline = Date().addingTimeInterval(120)
+ while leaving == 0 && step == generation {
+ precondition(condition.wait(until: deadline), "TP rank failed to meet its peer")
+ }
+ }
+ let output = result
+ leaving -= 1
+ if leaving == 0 { inputs = [:]; shapes = [:]; result = []; step += 1; condition.broadcast() }
+ condition.unlock()
+ return MLXArray(output, array.shape).asType(array.dtype)
+ }
+ }
+ final class Rank: QwenTensorParallelReduction, @unchecked Sendable {
+ let rank: Int, size = 2
+ let shared: Rendezvous
+ var collectives = 0
+ init(_ rank: Int, _ shared: Rendezvous) { self.rank = rank; self.shared = shared }
+ func allSum(_ value: MLXArray) -> MLXArray { collectives += 1; return shared.sum(value, rank: rank) }
+ }
+
+ /// One rank's outcome: the last logits, every row's keys and values, every
+ /// recurrent state, the prefix capture, the decoding lane's logits per step
+ /// and the collectives the prompt's steps issued.
+ struct Outcome: Equatable {
+ var logits = Data()
+ var rows: [Data] = []
+ var recurrent: [Data] = []
+ var capture: [Data] = []
+ var decoded: [Data] = []
+ var collectives = 0
+ var steps = 0
+ }
+
+ private static func bytes(_ a: MLXArray) -> Data { eval(a); return a.asData(access: .copy).data }
+
+ private static func state(of session: QwenTensorParallelBatchSession) -> (rows: [Data], recurrent: [Data]) {
+ var rows: [Data] = []
+ for row in session.state.rows {
+ let snapshot = row!.snapshot()
+ rows += [Data("\(snapshot.offset)".utf8), bytes(snapshot.keys), bytes(snapshot.values)]
+ }
+ let committed = session.state.recurrent.confirmedStateSnapshot() ?? [:]
+ let recurrent = committed.keys.sorted().flatMap { [bytes(committed[$0]!.conv!), bytes(committed[$0]!.ssm!)] }
+ return (rows, recurrent)
+ }
+
+ /// A prompt of `prompt` tokens on both ranks, each step merging up to
+ /// `limit` frames (1: today's one frame a step, through `prefill(check:)`).
+ /// With `decodeBeside`, a 300-token lane is prefilled first and decodes one
+ /// fixed token before each prompt step and after the last. With
+ /// `restoreAt`, the prompt resumes from the state a donor run one frame a
+ /// step kept there (a prefix-cache hit).
+ private static func run(_ models: [QwenTensorParallelModel], _ ranks: [Rank], configuration: Data,
+ kind: ClusterStageKVBackendKind, prompt: Int, limit: Int, captureFrontier: Int = 0,
+ decodeBeside: Bool = false, restoreAt: Int = 0) throws -> [Outcome] {
+ let threads = TensorParallelRankThreads()
+ let id = UUID(), besideID = UUID()
+ let results = (0..<2).map { _ in RankResult() }
+ for rank in ranks { rank.collectives = 0 }
+ threads.run { rank in
+ Device.withDefaultDevice(.gpu) {
+ do {
+ let model = models[rank]
+ let host = try CBv2StageKVHost(model: model.model, kind: kind, lanes: decodeBeside ? 2 : 1,
+ maximumTokensPerRequest: prompt + 16, maximumChunkTokens: 512)
+ var target = try Self.request(prompt: prompt)
+ target = try QwenLayerStageGenerationRequest(profile: target.profile, requestID: id,
+ promptTokenIDs: target.promptTokenIDs, chunkSize: 512, outputCount: 16, stopTokenIDs: [])
+ let bound: (Int) throws -> Int = { (($0 + 16_383) / 16_384) * 16_384 }
+ var restored: QwenTensorParallelBatchPrefixState?
+ if restoreAt > 0 {
+ let donorHost = try CBv2StageKVHost(model: model.model, kind: kind, lanes: 1,
+ maximumTokensPerRequest: prompt + 16, maximumChunkTokens: 512)
+ let donor = try QwenTensorParallelBatchSession(model: model, configuration: configuration,
+ host: donorHost, request: target,
+ capture: QwenTensorParallelPrefixCapture(frontiers: [restoreAt], limitBytes: 256 << 20, allocationBound: bound))
+ while donor.schedule.committedPromptTokens < prompt { _ = try donor.prefill(check: {}) }
+ try donor.retire()
+ restored = try #require(try donor.takeCapturedPrefix()?.states.first(where: { $0.committedTokens == restoreAt }))
+ target = try target.planned(reusedPrefix: restoreAt, splitFinalToken: false)
+ }
+ let session = try QwenTensorParallelBatchSession(model: model, configuration: configuration,
+ host: host, request: target, restored: restored,
+ capture: captureFrontier > 0
+ ? QwenTensorParallelPrefixCapture(frontiers: [captureFrontier], limitBytes: 256 << 20, allocationBound: bound) : nil)
+ var beside: QwenTensorParallelBatchSession?
+ if decodeBeside {
+ let short = try Self.request(prompt: 300)
+ let other = try QwenLayerStageGenerationRequest(profile: short.profile, requestID: besideID,
+ promptTokenIDs: short.promptTokenIDs, chunkSize: short.chunkSize, outputCount: 16,
+ stopTokenIDs: [])
+ beside = try QwenTensorParallelBatchSession(model: model, configuration: configuration,
+ host: host, request: other)
+ _ = try beside!.prefill(check: {})
+ }
+ var outcome = Outcome()
+ func decodeBesideStep() throws {
+ guard let beside else { return }
+ let token = 11 + outcome.decoded.count
+ outcome.decoded.append(bytes(try QwenTensorParallelBatchSession.decode([beside],
+ tokens: [token], check: {})))
+ }
+ var last: MLXArray?
+ while session.schedule.committedPromptTokens < prompt {
+ try decodeBesideStep()
+ let issued = ranks[rank].collectives
+ defer { outcome.collectives += ranks[rank].collectives - issued; outcome.steps += 1 }
+ if limit == 1 {
+ last = try session.prefill(check: {}) ?? last
+ } else {
+ let step = try #require(QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: limit)))
+ last = try session.prefill(step: step, check: {}) ?? last
+ }
+ }
+ try decodeBesideStep()
+ outcome.logits = bytes(try #require(last))
+ (outcome.rows, outcome.recurrent) = state(of: session)
+ try session.retire()
+ if let captured = try session.takeCapturedPrefix() {
+ // Every kept boundary's state, beside the one attention copy they share.
+ outcome.capture = [Data("\(captured.sharedBytes)".utf8)]
+ for kept in captured.states {
+ outcome.capture.append(Data("\(kept.committedTokens)".utf8))
+ outcome.capture += kept.attention.keys.sorted().flatMap { [bytes(kept.attention[$0]!.keys),
+ bytes(kept.attention[$0]!.values)] }
+ outcome.capture += kept.recurrent.keys.sorted().flatMap { [bytes(kept.recurrent[$0]!.conv),
+ bytes(kept.recurrent[$0]!.ssm)] }
+ }
+ }
+ try beside?.retire()
+ results[rank].outcome = outcome
+ } catch { results[rank].failure = error }
+ }
+ }
+ for result in results { if let failure = result.failure { throw failure } }
+ return try results.map { try #require($0.outcome) }
+ }
+
+ /// One rank thread's own result.
+ final class RankResult: @unchecked Sendable {
+ var outcome: Outcome?
+ var failure: Error?
+ }
+
+ /// Hybrid shards of one synthetic checkpoint (six recurrent, two attention
+ /// layers) on two in-process ranks that sum by meeting each other.
+ private static func pair() throws -> (configuration: Data, ranks: [Rank], models: [QwenTensorParallelModel]) {
+ let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 2048, layers: 8, heads: 8, kvHeads: 2,
+ vocabulary: 256)
+ var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any]
+ var text = root["text_config"] as! [String: Any]
+ text["max_position_embeddings"] = 8192; root["text_config"] = text
+ let configuration = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys])
+ let wire = Rendezvous()
+ let ranks = (0..<2).map { Rank($0, wire) }
+ let models = try (0..<2).map { rank in
+ try QwenTensorParallelModel.assemble(configurationData: configuration,
+ role: .shard(rank: rank, size: 2), reduction: ranks[rank]) { _, keep in
+ for (name, value) in fixture.tensors { try keep(name, value) }
+ }
+ }
+ return (configuration, ranks, models)
+ }
+
+ /// Both ranks' temporaries per prompt step of `limit` frames (the largest
+ /// step's peak above the settled allocation before and after it).
+ private static func promptTransient(_ models: [QwenTensorParallelModel], configuration: Data, prompt: Int,
+ limit: Int) throws -> Int {
+ let threads = TensorParallelRankThreads()
+ let id = UUID()
+ let sessions = try (0..<2).map { rank -> QwenTensorParallelBatchSession in
+ let host = try CBv2StageKVHost(model: models[rank].model, kind: .paged, lanes: 1,
+ maximumTokensPerRequest: prompt + 16, maximumChunkTokens: 512)
+ let shape = try Self.request(prompt: prompt)
+ let request = try QwenLayerStageGenerationRequest(profile: shape.profile, requestID: id,
+ promptTokenIDs: shape.promptTokenIDs, chunkSize: 512, outputCount: 16, stopTokenIDs: [])
+ return try QwenTensorParallelBatchSession(model: models[rank], configuration: configuration, host: host,
+ request: request)
+ }
+ defer { for session in sessions { try? session.retire() } }
+ var largest = 0
+ while sessions[0].schedule.committedPromptTokens < prompt {
+ Stream.gpu.synchronize(); Memory.clearCache()
+ let before = Memory.activeMemory
+ Memory.peakMemory = 0
+ let results = (0..<2).map { _ in RankResult() }
+ threads.run { rank in
+ Device.withDefaultDevice(.gpu) {
+ do {
+ let session = sessions[rank]
+ let step = try #require(QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: limit)))
+ if let logits = try session.prefill(step: step, check: {}) { eval(logits) }
+ } catch { results[rank].failure = error }
+ }
+ }
+ for result in results { if let failure = result.failure { throw failure } }
+ Stream.gpu.synchronize()
+ largest = max(largest, Memory.peakMemory - max(before, Memory.activeMemory))
+ Memory.clearCache()
+ }
+ return largest
+ }
+
+ /// A merged step of eight frames allocates no more temporaries than the
+ /// largest lone frame plus the further frames' charge
+ /// (`QwenTensorParallelPromptWavefront.inFlightBytes`, which LOAD and each
+ /// request's charge add to the shared prompt workspace), measured on both
+ /// in-process ranks of a paged one-lane host at a 4,096-token prompt.
+ @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1"))
+ func mergedStepTemporariesStayWithinTheirCharge() throws {
+ try Device.withDefaultDevice(.gpu) {
+ let (configuration, _, models) = try Self.pair()
+ let single = try Self.promptTransient(models, configuration: configuration, prompt: 4096, limit: 1)
+ let merged = try Self.promptTransient(models, configuration: configuration, prompt: 4096,
+ limit: QwenTensorParallelPromptWavefront.maximumFrames)
+ let charge = try QwenTensorParallelPromptWavefront.inFlightBytes(plan: models[0].plan, chunkTokens: 512,
+ allocationBound: { (($0 + 16_383) / 16_384) * 16_384 })
+ print("darkbloom-tp-wavefront-memory-v1 frames=\(QwenTensorParallelPromptWavefront.maximumFrames)"
+ + " single_pair=\(single) merged_pair=\(merged) in_flight_per_rank=\(charge)")
+ #expect(single > 0 && merged <= single + 2 * charge, "a merged step exceeded a frame and its charge")
+ }
+ }
+
+ /// Hybrid shards (six recurrent, two attention layers) over the in-process
+ /// pair. Each case runs today's one frame a step, then merged steps:
+ /// - a prompt ending mid-frame (1,100 tokens: one step of three frames),
+ /// paged (the one-lane host's prefill mirror) and contiguous;
+ /// - a capture frontier inside the prompt (2,600 tokens, kept at 1,024:
+ /// steps of two and four frames, the capture taken between them);
+ /// - beside a decoding lane on a two-lane paged host (each prompt history
+ /// gathered from its pages): two frames a step, the decoding lane's
+ /// logits unchanged at every step;
+ /// - after a prefix restored at 1,024 tokens: the suffix's four frames in one step.
+ @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1"))
+ func mergedFramesKeepEveryBit() throws {
+ try Device.withDefaultDevice(.gpu) {
+ let (configuration, ranks, models) = try Self.pair()
+ #expect(Qwen35PromptWavefront.supports(models[0].model))
+ let cases: [(name: String, kind: ClusterStageKVBackendKind, prompt: Int, limit: Int, capture: Int, beside: Bool,
+ restore: Int)] = [
+ ("mid-frame end, paged", .paged, 1_100, 8, 0, false, 0),
+ ("mid-frame end, contiguous", .contiguous, 1_100, 8, 0, false, 0),
+ ("capture frontier", .paged, 2_600, 8, 1_024, false, 0),
+ ("beside a decoding lane", .paged, 1_100, QwenTensorParallelPromptWavefront.framesBesideDecoding, 0, true, 0),
+ ("restored prefix", .paged, 2_600, 8, 0, false, 1_024),
+ ]
+ for item in cases {
+ let before = try Self.run(models, ranks, configuration: configuration, kind: item.kind,
+ prompt: item.prompt, limit: 1, captureFrontier: item.capture, decodeBeside: item.beside,
+ restoreAt: item.restore)
+ let after = try Self.run(models, ranks, configuration: configuration, kind: item.kind,
+ prompt: item.prompt, limit: item.limit, captureFrontier: item.capture, decodeBeside: item.beside,
+ restoreAt: item.restore)
+ for rank in 0..<2 {
+ let x = before[rank], y = after[rank]
+ #expect(x.logits == y.logits, "\(item.name): final logits, rank \(rank)")
+ #expect(x.rows == y.rows && x.rows.count == 6, "\(item.name): attention rows, rank \(rank)")
+ #expect(x.recurrent == y.recurrent && x.recurrent.count == 12, "\(item.name): conv/SSM, rank \(rank)")
+ #expect(x.capture == y.capture && x.capture.isEmpty == (item.capture == 0),
+ "\(item.name): prefix capture, rank \(rank)")
+ #expect(x.collectives == y.collectives && x.collectives > 0,
+ "\(item.name): the prompt's collectives, rank \(rank)")
+ #expect(y.steps < x.steps, "\(item.name): \(y.steps) merged steps against \(x.steps) frames")
+ // Two merged steps (three decodes) against three frames (four): each decode is the lane's own.
+ #expect(y.decoded.count == (item.beside ? 3 : 0) && x.decoded.prefix(y.decoded.count).elementsEqual(y.decoded),
+ "\(item.name): the decoding lane's logits, rank \(rank)")
+ }
+ #expect(before[0].logits != before[1].logits, "\(item.name): ranks hold distinct vocabulary halves")
+ }
+ }
+ }
+
+ struct Reservation: QwenTensorParallelBatchReservation {
+ let request: QwenLayerStageGenerationRequest
+ let deadline: UInt64 = .max
+ var laneStateBytes: Int { 1 }
+ var joinable: Bool { true }
+ }
+
+ /// The native executor runs the leader's planned step: a 1,100-token
+ /// prompt in one merged step selects the token one frame a step selects,
+ /// on both ranks, and a lane takes a planned token count only where it
+ /// ends one of its own steps (`promptStep(tokens:)`).
+ @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1"))
+ func executorRunsThePlannedMergedStep() throws {
+ try Device.withDefaultDevice(.gpu) {
+ let (configuration, ranks, models) = try Self.pair()
+ let shape = try Self.request(prompt: 1_100)
+ let request = try QwenLayerStageGenerationRequest(profile: shape.profile, requestID: UUID(),
+ promptTokenIDs: shape.promptTokenIDs, chunkSize: 512, outputCount: 16, stopTokenIDs: [])
+ func selected(limit: Int) throws -> [(token: Int, steps: Int)] {
+ let results = (0..<2).map { _ in ExecutorResult() }
+ let lanes = try (0..<2).map { rank -> QwenTensorParallelNativeBatchLane in
+ let host = try CBv2StageKVHost(model: models[rank].model, kind: .paged, lanes: 1,
+ maximumTokensPerRequest: 1_116, maximumChunkTokens: 512)
+ let executor = try QwenTensorParallelNativeBatchExecutor(model: models[rank],
+ configuration: configuration, host: host, group: ranks[rank], prepare: { _, _ in nil },
+ completedDecode: { _ in }, completedPrefill: {}, releaseResources: { _ in })
+ let lane = try executor.open(.init(request: request), check: {})
+ if rank == 0 {
+ #expect(lane.promptStep(tokens: 1_100) == QwenTensorParallelPromptWavefront.step(
+ lane.session.promptFrames(limit: 3)))
+ #expect(lane.promptStep(tokens: 1_024)?.finalPromptChunk == false)
+ #expect(lane.promptStep(tokens: 700) == nil && lane.promptStep(tokens: 2_048) == nil)
+ }
+ results[rank].executor = executor
+ return lane
+ }
+ defer { for lane in lanes { try? lane.session.retire() } }
+ let threads = TensorParallelRankThreads()
+ threads.run { rank in
+ Device.withDefaultDevice(.gpu) {
+ do {
+ let lane = lanes[rank], executor = try #require(results[rank].executor)
+ var steps = 0, token: Int?
+ while lane.nextFrame?.phase == .prefill {
+ let step = try #require(lane.promptStep(frames: limit))
+ token = try executor.prefill(lane, frame: step, check: {}); steps += 1
+ }
+ results[rank].selection = (try #require(token), steps)
+ } catch { results[rank].failure = error }
+ }
+ }
+ for result in results { if let failure = result.failure { throw failure } }
+ return try results.map { try #require($0.selection) }
+ }
+ let one = try selected(limit: 1)
+ let merged = try selected(limit: QwenTensorParallelPromptWavefront.maximumFrames)
+ #expect(one.map(\.steps) == [3, 3] && merged.map(\.steps) == [1, 1])
+ #expect(one.map(\.token) == merged.map(\.token) && one[0].token == one[1].token)
+ }
+ }
+
+ /// One rank thread's executor and selection.
+ final class ExecutorResult: @unchecked Sendable {
+ var executor: QwenTensorParallelNativeBatchExecutor?
+ var selection: (token: Int, steps: Int)?
+ var failure: Error?
+ }
+}
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ResidentAdmissionGemma4Tests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ResidentAdmissionGemma4Tests.swift
index 3b39be7e89..81198c5d5c 100644
--- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ResidentAdmissionGemma4Tests.swift
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ResidentAdmissionGemma4Tests.swift
@@ -373,6 +373,26 @@ struct ResidentAdmissionGemma4Tests {
#expect(small.stateAndBoundaryBytes < largest.stateAndBoundaryBytes)
}
+ /// A decode step's command buffers can keep every layer's temporaries
+ /// alive at once (`QwenLayerStageSession.decodeCommandBuffers`): the
+ /// transient prices each layer's decode row together whenever that is
+ /// more than one prompt frame's largest layer.
+ @Test func theDecodeStepPricesEveryLayersRowAtOnce() throws {
+ typealias G = Gemma4StageGeometry
+ let layers = (0..<15).map { QwenLayerStagePlan.Layer(globalIndex: $0, localIndex: $0, kind: G.kind(globalLayerIndex: $0)) }
+ let full = layers.filter { $0.kind == G.fullKind }.count, sliding = layers.count - full
+ #expect(full == 2 && sliding == 13)
+ func bytes(chunk: Int, rows: Int) throws -> Int {
+ try Gemma4PrefillTransient.bytes(layers: layers, chunkTokens: chunk, contextTokens: 8320,
+ decodeRows: rows, decodeLayers: layers)
+ }
+ let fullRow = G.queryHeads * (8320 + G.fullHeadDimension) * 4
+ let slidingRow = G.queryHeads * (G.slidingWindow + G.slidingHeadDimension) * 4
+ #expect(try bytes(chunk: 1, rows: 0) == fullRow)
+ #expect(try bytes(chunk: 1, rows: 1) == full * fullRow + sliding * slidingRow)
+ #expect(try bytes(chunk: 512, rows: 1) == (try bytes(chunk: 512, rows: 0)))
+ }
+
@Test func onlyTheLastLayerOfTheOutputRankNarrowsAPromptChunk() {
typealias Policy = Gemma4StagePromptPolicy
func decide(_ layer: Int, prefill: Bool = true, owns: Bool = true, length: Int = 512,
diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ResidentAdmissionNemotronTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ResidentAdmissionNemotronTests.swift
index 0b8fed0a9b..bdb0f6c52d 100644
--- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ResidentAdmissionNemotronTests.swift
+++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/ResidentAdmissionNemotronTests.swift
@@ -229,6 +229,29 @@ struct ResidentAdmissionNemotronTests {
}
}
+ /// A decode step on every attention block it runs at once
+ /// (`QwenLayerStageSession.decodeCommandBuffers`): a one-token prompt pays
+ /// those rows; a prompt frame of 512 already covers them.
+ @Test func theDecodeStepPricesEveryAttentionBlocksRow() throws {
+ let profile = try Self.profile()
+ let plan = try profile.makePlanningPlan(stageCut: 25)
+ let blocks = plan.stages.flatMap(\.layers).filter { $0.kind == "attention" }.count
+ #expect(blocks == 6)
+ for rank in 0...1 {
+ let own = plan.stages[rank].layers.filter { $0.kind == "attention" }.count
+ func transient(_ chunk: Int, _ decode: LayerStageDecodeShape = .plain) throws -> Int {
+ try QwenResidentRequestAllowance.derive(profile: profile, plan: plan, rank: rank, maximumTokens: 8320,
+ chunkSize: chunk, decode: decode, bound: { $0 }).transientBytes
+ }
+ // 32 query heads of width 128 take MLX's fused kernel: a row prices its float32 output.
+ #expect(try transient(1) == 32 * own * 128 * 4)
+ #expect(try transient(1, .init(wholeModel: true)) == 32 * blocks * 128 * 4)
+ // A phase split's producer rank decodes nothing: its prompt frame alone.
+ #expect(try transient(1, .init(rows: 0)) == (own > 0 ? 32 * 128 * 4 : 0))
+ #expect(try transient(512) == (try transient(512, .init(wholeModel: true))))
+ }
+ }
+
/// The state rank 0 hands over in a phase split: its Mamba blocks'
/// convolution history and SSM state and its attention blocks' keys and
/// values, by the block's index in the complete model; nothing for an
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift
new file mode 100644
index 0000000000..1322a06a42
--- /dev/null
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift
@@ -0,0 +1,49 @@
+import DarkbloomClusterPlacement
+import DarkbloomClusterProtocol
+import Foundation
+
+/// Gemma 4 26B routes each token to 8 of a layer's 128 experts. The QAT
+/// 4-bit layout built here from the artifact's retained real tensor headers
+/// (`StageMetadataChecks/Inputs`) must equal its golden layout, routed experts
+/// included, and the hardware prior must read 8/128 of those banks per token:
+/// 2,424,219,708 bytes, the figure the exact-header audit of 2026-09-20
+/// recorded, instead of every layer byte.
+func checkGemmaRoutedExperts(golden: URL, _ checks: PlacementChecks) throws {
+ let inputs = golden.deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("StageMetadataChecks/Inputs", isDirectory: true)
+ var tensors: [ClusterPlacementStoredTensor] = []
+ let headers = try FileManager.default.contentsOfDirectory(atPath: inputs.path)
+ .filter { $0.hasSuffix(".safetensors.header.json") }.sorted()
+ for file in headers {
+ let header = try JSONSerialization.jsonObject(with: Data(contentsOf: inputs.appendingPathComponent(file)))
+ as? [String: Any] ?? [:]
+ for (name, value) in header where name != "__metadata__" {
+ guard let entry = value as? [String: Any], let dtype = entry["dtype"] as? String,
+ let shape = entry["shape"] as? [Int], let offsets = entry["data_offsets"] as? [Int],
+ offsets.count == 2, offsets[1] > offsets[0] else {
+ throw ProbeError("Malformed retained Gemma header entry: \(name)")
+ }
+ tensors.append(.init(name: name, byteCount: offsets[1] - offsets[0], dtype: dtype, shape: shape))
+ }
+ }
+ let layout = try ClusterPlacementLayouts.layout(
+ configuration: Data(contentsOf: inputs.appendingPathComponent("config.json")), tensors: tensors,
+ manifest: Data(contentsOf: inputs.appendingPathComponent("manifest.json")))
+ let expected = try ClusterModelLayout.decode(
+ Data(contentsOf: golden.appendingPathComponent("layouts/gemma-4-26b-qat-4bit.json")))
+ checks.require("Gemma QAT 4-bit: the layout from the retained real headers equals its golden layout, routed experts included",
+ headers.count == 3 && layout == expected)
+ let experts = layout.routedExperts
+ checks.require("Gemma QAT 4-bit routes 8 of 128 experts; its expert banks hold 12,846,366,720 bytes, no tensor-parallel share",
+ experts?.routing == ClusterExpertRouting(selected: 8, experts: 128) && experts?.loadedBytes == 12_846_366_720
+ && experts?.tensorParallelDividedBytes == nil)
+ checks.require("Gemma QAT 4-bit decode reads 2,424,219,708 weight bytes per token (8/128 of the expert banks)",
+ ClusterHardwarePrior.decodeBytesPerToken(layout) == 2_424_219_708)
+ // The 8-bit artifact's golden layout carries the same routing over its 8-bit banks.
+ for name in ["gemma-4-26b-8bit", "gemma-4-26b"] {
+ let eight = try ClusterModelLayout.decode(Data(contentsOf: golden.appendingPathComponent("layouts/\(name).json")))
+ checks.require("\(name): 8 of 128 routed experts over 24,265,359,360 bytes of 8-bit banks",
+ eight.routedExperts?.routing == ClusterExpertRouting(selected: 8, experts: 128)
+ && eight.routedExperts?.loadedBytes == 24_265_359_360)
+ }
+}
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json
index 8bd6c48808..c57640d98a 100644
--- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json
@@ -43,9 +43,9 @@
},
"gemma-4-26b": {
"cut": 15,
- "handOffPlanSHA256": "d18c86e08d609efff04dba63a250d8a26580ff9bc0fe3854b2399961cc8711a9",
+ "handOffPlanSHA256": "660cb1537bea8a3af6709fa7e82fe8f59a197c54200be814083be361c8410aa7",
"mode": "pipeline_v1",
- "planSHA256": "4a7acb8341eb99036e819e651b6eb0a91f7d17256192b06c1864c1fdb938eeb4",
+ "planSHA256": "4773f5dda0b6eab7234e2345227ce08f7f1e5e75e1be6872a6709dea650e7da6",
"ranks": [
{
"device": "mac-a",
@@ -64,9 +64,9 @@
},
"gemma-4-26b-8bit": {
"cut": 15,
- "handOffPlanSHA256": "4c7e27371b3173548670079e804af65e7229ab812146d9a9d3b5a532ea96d511",
+ "handOffPlanSHA256": "92f2a8f617a28b13fc68ba89a34a7870e953e17ccdb004d9a0087e2030e63dd6",
"mode": "pipeline_v1",
- "planSHA256": "8c0e0dc6c7781fe37db90ea37f423fa8b9c370bfea8010a3e2531d00cc41ca8b",
+ "planSHA256": "98018701fbd5f5049ab44f105fe0ab2f0edb1b7dc63443cedd08597bbbdf63c2",
"ranks": [
{
"device": "mac-a",
@@ -85,9 +85,9 @@
},
"gemma-4-26b-qat-4bit": {
"cut": 15,
- "handOffPlanSHA256": "2b8dc675c45902362c5c01aa93149de0472c2afec72f00232f240278d6ede4df",
+ "handOffPlanSHA256": "d134439b21431a48404e2af363824fccf6e02053d771a5b7a67ae7599a6af3a5",
"mode": "pipeline_v1",
- "planSHA256": "d6bc775b447fc25abc13db52b72b7d0c17b47a0b87f356f0cd57f86d5aa7e21c",
+ "planSHA256": "ef31103798080a01f959ba00f07a56b5d80cbacf4f16634b9313007d776c31fa",
"ranks": [
{
"device": "mac-a",
@@ -127,9 +127,9 @@
},
"mimo-v2.6-flash-mopd-2026-09-28-r1": {
"cut": 41,
- "handOffPlanSHA256": "b5ad60578a8438482ea406eac34caf0a4083237335d0a94c6214bfe33d7d0454",
+ "handOffPlanSHA256": "6a1b96bcc6cd5b3fc16ee04e13199d01b2105639943a643bad0d9baf4d5bb700",
"mode": "pipeline_v1",
- "planSHA256": "b8e47f8ec25b077706df9be8516a679cf4503960491729e6915e47c6b70e3d1a",
+ "planSHA256": "b6051c34d22236f1f42add34fc54474eaf5b5beb2fc3f1509d11bbb26a91dfde",
"ranks": [
{
"device": "mac-a",
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json
index b1778ac039..b13a8ab341 100644
--- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json
@@ -1 +1 @@
-{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b_8bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]}
+{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":24265359360,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b_8bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]}
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json
index 1668d30971..2eb3687281 100644
--- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json
@@ -1 +1 @@
-{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785","boundaryBytesPerToken":5632,"configurationSHA256":"29910322dd085f45c8f95c6c0f1611b20f722d6f6c8394321b34817e98a972fa","egress":{"largestTensorBytes":369098752,"loadedBytes":415241728,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1140925536,"requestWorkBytes":0,"storedBytes":1140925536,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":369098752,"loadedBytes":415236096,"requestWorkBytes":0,"storedBytes":415236096,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b_qat_4bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]}
+{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785","boundaryBytesPerToken":5632,"configurationSHA256":"29910322dd085f45c8f95c6c0f1611b20f722d6f6c8394321b34817e98a972fa","egress":{"largestTensorBytes":369098752,"loadedBytes":415241728,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1140925536,"requestWorkBytes":0,"storedBytes":1140925536,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":369098752,"loadedBytes":415236096,"requestWorkBytes":0,"storedBytes":415236096,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":12846366720,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b_qat_4bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]}
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json
index 0f7b245b87..7007a83d71 100644
--- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json
@@ -1 +1 @@
-{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]}
+{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":24265359360,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]}
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/mimo-v2.6-flash-mopd-2026-09-28-r1.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/mimo-v2.6-flash-mopd-2026-09-28-r1.json
index c92b16aeb8..68fbf03c9e 100644
--- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/mimo-v2.6-flash-mopd-2026-09-28-r1.json
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/mimo-v2.6-flash-mopd-2026-09-28-r1.json
@@ -1 +1 @@
-{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47],"artifactSHA256":"2334547d8acc9898ad4a74570ce44d2b12390bbac8d4bc52c092eb5ad5cfe034","boundaryBytesPerToken":8192,"configurationSHA256":"35b6e3d4543b65e6fa9d6174e2260d9ac1d3ea1e5acb9955d9fe9f2b815d13d4","egress":{"largestTensorBytes":624951296,"loadedBytes":664018944,"requestWorkBytes":0,"storedBytes":664018944,"tensorCount":4},"excluded":{"largestTensorBytes":134217728,"loadedBytes":3710306688,"requestWorkBytes":0,"storedBytes":3710306688,"tensorCount":629},"generationModes":["pipeline_v1","pipeline_compact_decode_v1","phase_split_v1"],"ingress":{"largestTensorBytes":624951296,"loadedBytes":664010752,"requestWorkBytes":0,"storedBytes":664010752,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"full_dense","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":67108864,"loadedBytes":308625408,"requestWorkBytes":0,"storedBytes":308625408,"tensorCount":23}},{"cost":1,"index":1,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":2,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":3,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":4,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":5,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":6,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":7,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":8,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":9,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":10,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":11,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":12,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":13,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":14,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":15,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":16,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":17,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":18,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":19,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":20,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":21,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":22,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":23,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":24,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":25,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":26,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":27,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":28,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":29,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":30,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":31,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":32,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":33,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":34,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":35,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":36,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":37,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":38,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":39,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":40,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":41,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":42,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":43,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":44,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":45,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":46,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":47,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":32640,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":0,"runtimeModelID":"registered_mimo_v26_flash_mopd","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47]}
+{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47],"artifactSHA256":"2334547d8acc9898ad4a74570ce44d2b12390bbac8d4bc52c092eb5ad5cfe034","boundaryBytesPerToken":8192,"configurationSHA256":"35b6e3d4543b65e6fa9d6174e2260d9ac1d3ea1e5acb9955d9fe9f2b815d13d4","egress":{"largestTensorBytes":624951296,"loadedBytes":664018944,"requestWorkBytes":0,"storedBytes":664018944,"tensorCount":4},"excluded":{"largestTensorBytes":134217728,"loadedBytes":3710306688,"requestWorkBytes":0,"storedBytes":3710306688,"tensorCount":629},"generationModes":["pipeline_v1","pipeline_compact_decode_v1","phase_split_v1"],"ingress":{"largestTensorBytes":624951296,"loadedBytes":664010752,"requestWorkBytes":0,"storedBytes":664010752,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"full_dense","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":67108864,"loadedBytes":308625408,"requestWorkBytes":0,"storedBytes":308625408,"tensorCount":23}},{"cost":1,"index":1,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":2,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":3,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":4,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":5,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":6,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":7,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":8,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":9,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":10,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":11,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":12,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":13,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":14,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":15,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":16,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":17,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":18,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":19,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":20,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":21,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":22,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":23,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":24,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":25,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":26,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":27,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":28,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":29,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":30,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":31,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":32,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":33,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":34,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":35,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":36,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":37,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":38,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":39,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":40,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":41,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}},{"cost":1,"index":42,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":43,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":44,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":45,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":46,"kind":"sliding_moe","stateBytesPerToken":0,"stateFixedBytes":3276800,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"transientKeyWindow":640,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3524936832,"requestWorkBytes":0,"storedBytes":3524936832,"tensorCount":23}},{"cost":1,"index":47,"kind":"full_moe","stateBytesPerToken":2560,"stateFixedBytes":0,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":256,"weights":{"largestTensorBytes":1073741824,"loadedBytes":3519366144,"requestWorkBytes":0,"storedBytes":3519366144,"tensorCount":22}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":32640,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":0,"routedExperts":{"loadedBytes":160859947008,"routing":{"experts":256,"selected":8}},"runtimeModelID":"registered_mimo_v26_flash_mopd","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47]}
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json
index e275189a6c..b2ec36c0c1 100644
--- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json
@@ -43,9 +43,9 @@
},
"gemma-4-26b": {
"cut": 15,
- "handOffPlanSHA256": "2420b14ee7687f033f5a58b7fa9c325ae6121af03b4cd4be0f5f41a016e2c436",
+ "handOffPlanSHA256": "6dbd01083d074d1aa44f08f1d25603e93145492395501e6f9a1f6c1766247a00",
"mode": "pipeline_v1",
- "planSHA256": "ad764d50791a75f5c9c1a9f407276e1c717fb6f5e6847e8ea82380f5b0cdbf79",
+ "planSHA256": "dbc808e3abc53b12d32170bdbb964cbc478e129050f06b0d843a8880a164d5d5",
"ranks": [
{
"device": "mac-a",
@@ -64,9 +64,9 @@
},
"gemma-4-26b-8bit": {
"cut": 15,
- "handOffPlanSHA256": "cbaef9455f5c272fe17a847a206a173ce94c84f9c5ebadde7a9b0f43f1ebc6e5",
+ "handOffPlanSHA256": "9608c7ee6e2b22cb943a557b68cf734c22c6ecc4f93a07f8a0b26104cc191cb3",
"mode": "pipeline_v1",
- "planSHA256": "042a04d32603765619f97b7044c24c9d846a4bde9e741830d39648504c73ad27",
+ "planSHA256": "4edd4f8c73fb0e0eadb07f432ffc2644c42212b7c53aa29a041482e6fad7a625",
"ranks": [
{
"device": "mac-a",
@@ -85,9 +85,9 @@
},
"gemma-4-26b-qat-4bit": {
"cut": 15,
- "handOffPlanSHA256": "ea678c6cf760925bd0ac3ec68359692b856dee2e6f67a0ee51d25fb3fe52abdb",
+ "handOffPlanSHA256": "db53aeb719616838b61b304b734aaaa284fac2ba3b18ccbc6b9063604f2cf1b4",
"mode": "pipeline_v1",
- "planSHA256": "b4c956fee4903ca1e6c6a81b54d0409d531ec446b12dd644ff0690734455ff6c",
+ "planSHA256": "c5b174e249c69c9f7eacef02029a1c80125dc7fa9e7832e60fa96c2d44571ccb",
"ranks": [
{
"device": "mac-a",
@@ -127,9 +127,9 @@
},
"mimo-v2.6-flash-mopd-2026-09-28-r1": {
"cut": 24,
- "handOffPlanSHA256": "77fc561ea09ba714c48901e1347f6e9145ab7dd97002207b0574874577f96cde",
+ "handOffPlanSHA256": "e82df159a1c621e78c7df42036186197ebfd42b2478fbc7e72341b0c897fa1e0",
"mode": "pipeline_v1",
- "planSHA256": "9bf6bb39b3917dce07b56d9bf9e2fb8fdc07349d6a0adec635c8a61c3393e7fc",
+ "planSHA256": "6293c023542cf48a48b977bd0c5944c2577a8a197383782f4e548e1a43d93f38",
"ranks": [
{
"device": "mac-a",
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift
index 1c51a219b2..995f65e5df 100644
--- a/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift
@@ -63,8 +63,10 @@ import Foundation
try checkForcedMode(inputs, checks)
try checkAutoChoice(inputs, golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks)
try checkGLMTensorParallel(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks)
+ try checkGemmaRoutedExperts(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks)
try checkServedModes(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks)
try checkPipelineSpeculativeHolding(URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks)
+ try checkMiMoRoutedExperts(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks)
try checkQwenPipelineSpeculative(URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks)
guard checks.failures.isEmpty else {
for failure in checks.failures { fputs("FAIL: \(failure)\n", stderr) }
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoRoutedExpertChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoRoutedExpertChecks.swift
new file mode 100644
index 0000000000..03116a0bde
--- /dev/null
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoRoutedExpertChecks.swift
@@ -0,0 +1,75 @@
+import DarkbloomClusterPlacement
+import DarkbloomClusterProtocol
+import Foundation
+
+/// MiMo V2.6 Flash routes each token to 8 of the 256 experts of each of its
+/// 47 routed layers. The layout its family builds from the registered tensor
+/// headers names those experts, so the hardware prior counts what one decode
+/// step reads (10,767,036,288 bytes) rather than every expert's bytes
+/// (166,600,109,952). The golden layout carries the same routed experts beside
+/// the bytes the real headers recorded. The prior prices tensor parallel only,
+/// so a MiMo plan without tensor-parallel facts is unchanged by the routing:
+/// the printed plan differs only by the layout it echoes, and without the
+/// routed experts it is byte for byte the plan both Macs printed.
+func checkMiMoRoutedExperts(golden: URL, _ checks: PlacementChecks) throws {
+ struct Header: Decodable { let name: String; let shape: [Int]; let sourceDType: String; let byteCount: Int }
+ let libraries = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent()
+ let fixtures = libraries.appendingPathComponent("darkbloom-cluster-worker/Tests/CapabilityChecks/Fixtures")
+ let configuration = try Data(contentsOf: fixtures.appendingPathComponent("registered-mimo-v26-flash-mopd.configuration.json"))
+ let headers = try JSONDecoder().decode([Header].self, from: Data(contentsOf:
+ fixtures.appendingPathComponent("registered-mimo-v26-flash-mopd.tensor-inventory.json")))
+ let family = try MiMoPlacementFamily(configuration: configuration)
+ let built = try ClusterModelLayoutBuilder.build(family: family,
+ tensors: headers.map { .init(name: $0.name, byteCount: $0.byteCount, dtype: $0.sourceDType, shape: $0.shape) },
+ artifactSHA256: family.specification.artifactSHA256, configurationSHA256: family.specification.configurationSHA256)
+ let routed = built.routedExperts
+ let banks = headers.filter { family.isRoutedExpert(storedTensor: $0.name) }
+ checks.require("MiMo routed experts: 8 of 256 in 47 layers, each layer's three packed banks and their scales",
+ routed?.routing == ClusterExpertRouting(selected: 8, experts: 256) && routed?.tensorParallelDividedBytes == nil
+ && banks.count == 47 * 6 && routed?.loadedBytes == 160_859_947_008
+ && Set(banks.compactMap { family.layer(ofStoredTensor: $0.name) }) == Set(1..<48)
+ && !banks.contains { $0.name.contains(".mlp.gate.") })
+ let whole = built.layers.reduce(0) { $0 + $1.weights.loadedBytes } + built.egress.loadedBytes
+ checks.require("MiMo prior: a decode step reads 10,767,036,288 bytes, not every expert's (166,600,109,952)",
+ ClusterHardwarePrior.decodeBytesPerToken(built) == 10_767_036_288 && whole == 166_600_109_952)
+
+ let file = golden.appendingPathComponent("layouts/mimo-v2.6-flash-mopd-2026-09-28-r1.json")
+ let recorded = try ClusterModelLayout.decode(Data(contentsOf: file))
+ checks.require("MiMo golden layout: the family's routed experts beside the bytes the real headers recorded",
+ recorded.routedExperts == routed && recorded.layers.map(\.weights) == built.layers.map(\.weights)
+ && recorded.ingress == built.ingress && recorded.egress == built.egress && recorded.excluded == built.excluded)
+
+ var object = try JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any] ?? [:]
+ object["routedExperts"] = nil
+ let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("mimo-routing-\(getpid())", isDirectory: true)
+ try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let unrouted = scratch.appendingPathComponent("mimo.json")
+ try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object)).encoded().write(to: unrouted)
+ // The golden plans of this layout as both Macs printed them, before it named its routed experts.
+ let recordedPlans = [
+ "Golden": ["b8e47f8ec25b077706df9be8516a679cf4503960491729e6915e47c6b70e3d1a",
+ "b5ad60578a8438482ea406eac34caf0a4083237335d0a94c6214bfe33d7d0454"],
+ "m3ultra-m5ultra": ["9bf6bb39b3917dce07b56d9bf9e2fb8fdc07349d6a0adec635c8a61c3393e7fc",
+ "77fc561ea09ba714c48901e1347f6e9145ab7dd97002207b0574874577f96cde"],
+ ]
+ for pair in [golden, golden.appendingPathComponent("pairs/m3ultra-m5ultra", isDirectory: true)] {
+ let peers = ["mac-a", "mac-b"].flatMap { ["--peer", "\($0)=" + pair.appendingPathComponent("profile-\($0).json").path] }
+ for (index, extra) in [[], ["--hand-off-modes"]].enumerated() {
+ func plan(_ layout: URL) throws -> String {
+ try ClusterPlacementTool.run(["plan", "--layout", layout.path] + peers + ["--leader", "mac-a", "--json"] + extra,
+ sampleDevice: { throw ProbeError("recorded profiles only") })
+ }
+ let routedPlan = try plan(file), unroutedPlan = try plan(unrouted)
+ var echoed = try JSONSerialization.jsonObject(with: Data(routedPlan.utf8)) as? [String: Any] ?? [:]
+ var layout = echoed["layout"] as? [String: Any] ?? [:]
+ let echoedRouting = layout.removeValue(forKey: "routedExperts") != nil
+ echoed["layout"] = layout
+ let plain = try JSONSerialization.jsonObject(with: Data(unroutedPlan.utf8)) as? [String: Any] ?? [:]
+ checks.require("MiMo on \(pair.lastPathComponent)\(extra.isEmpty ? "" : " (hand-off opt-in)"): the routed experts change only the echoed layout, and without them the plan is the recorded golden",
+ echoedRouting && NSDictionary(dictionary: echoed).isEqual(to: plain)
+ && sha256(Data((unroutedPlan + "\n").utf8)) == recordedPlans[pair.lastPathComponent]?[index])
+ }
+ }
+}
diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/TensorBatchScopeChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/TensorBatchScopeChecks.swift
index a2270d57f1..461cdf673c 100644
--- a/libs/darkbloom-cluster/Tests/PlacementChecks/TensorBatchScopeChecks.swift
+++ b/libs/darkbloom-cluster/Tests/PlacementChecks/TensorBatchScopeChecks.swift
@@ -191,4 +191,49 @@ func checkTensorBatchScopes(_ inputs: RetainedQwenInputs, _ checks: PlacementChe
}
}
+ // A width saved at placement (`applyWidth`): the same owner's quote at that width in place of the singleton's,
+ // for a reference request inside its envelope. Memory is priced at the width; the prediction stays a request's.
+ let single = try quote(1)
+ func singleton() throws -> ClusterPlacementPolicy {
+ var p = ClusterPlacementPolicy(); p.leader = "a"; p.promptTokens = 700; p.outputTokens = 90
+ try single.applySingleton(to: &p, layout: layout)
+ return p
+ }
+ let alone = try ClusterPlacementPlanner.evaluate(devices: fast, cuts: [], mode: .tensorParallel,
+ prefillSchedule: .serial, layout: layout, policy: singleton(), link: link)
+ for lanes in [2, 4, 6, 8] {
+ let value = try quote(lanes)
+ var widened = try singleton()
+ widened.tensorParallelWideningQuote = try quote(2)
+ try value.applyWidth(to: &widened, layout: layout)
+ let candidate = try ClusterPlacementPlanner.evaluate(devices: fast, cuts: [], mode: .tensorParallel,
+ prefillSchedule: .serial, layout: layout, policy: widened, link: link)
+ checks.require("TP width \(lanes): each rank is priced at the width's complete quote",
+ zip(candidate.ranks, fast).allSatisfy { $0.requestNeedBytes == value.allowance.reservedBytes + $1.profile.memory.loadingHeadroomBytes })
+ checks.require("TP width \(lanes): the singleton's reference request and prediction are kept",
+ candidate.rested == alone.rested && candidate.sustained == alone.sustained
+ && widened.promptTokens == 700 && widened.outputTokens == 90)
+ checks.require("TP width \(lanes): the singleton's widening steer is cleared", widened.tensorParallelWideningQuote == nil)
+ }
+ checks.refuses("TP width: a singleton quote is no width", because: "same owner's singleton quote") {
+ var p = try singleton(); try single.applyWidth(to: &p, layout: layout)
+ }
+ checks.refuses("TP width: no singleton quote to replace", because: "same owner's singleton quote") {
+ var p = ClusterPlacementPolicy(); p.promptTokens = 700; p.outputTokens = 90
+ try quote(8).applyWidth(to: &p, layout: layout)
+ }
+ checks.refuses("TP width: another request envelope is another owner's", because: "same owner's singleton quote") {
+ let other = try ClusterPlacementRequestScope(runtimeModelID: request.runtimeModelID, artifactSHA256: request.artifactSHA256,
+ configurationSHA256: request.configurationSHA256, promptTokens: 2048, outputTokens: 128, maximumPromptTokens: 32768,
+ maximumOutputTokens: 32768, maximumContextTokens: 65536, requestChargeEveryRankBytes: 4 * gib)
+ let wide = try ClusterPlacementTensorBatchQuote(request: other, lanes: 8, chunkTokens: 128, perLaneStateBytes: 4 * gib,
+ sharedBytesExcludingCollectives: 80 * gib, allowance: try quote(8).allowance)
+ var p = try singleton(); try wide.applyWidth(to: &p, layout: layout)
+ }
+ checks.refuses("TP width: another assistant is another owner's", because: "same owner's singleton quote") {
+ let plain = try quote(8)
+ let assisted = try ClusterPlacementTensorBatchQuote(request: request, lanes: 8, chunkTokens: 128, perLaneStateBytes: 4 * gib,
+ sharedBytesExcludingCollectives: 80 * gib, allowance: plain.allowance, assistant: assistant)
+ var p = try singleton(); try assisted.applyWidth(to: &p, layout: layout)
+ }
}
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index 747dd09cfd..2311af6e67 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44
+Subproject commit 2311af6e67c2d79b6b7b59504978af67fe6857e0
diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift
index 5f2fb22126..3740de188d 100644
--- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift
+++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift
@@ -48,7 +48,8 @@ public protocol NativePairMemberServingHost: AnyObject, Sendable {
func serveCommittedStart(_ start: NativePairMemberServingStart) async throws
/// The session is ending: retire what `serveCommittedStart` published for
/// this epoch (or stop a serve still under way) and return once it is
- /// retired. Idempotent; an unknown epoch does nothing.
+ /// retired. The epoch is released at once, so a later start can begin
+ /// during that retirement, and is never served afterwards. Idempotent.
func stopServingCommittedStart(epoch: UUID) async
}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift
index 5fab33f75f..356fdbbc9f 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift
@@ -596,7 +596,7 @@ final class LiveContext: @unchecked Sendable {
let manifest = ClusterSetupModelFolders.readManifest(directory.appendingPathComponent("manifest.json")) ?? Data()
let assistantQuote: Result?
var targetFallback: Result? = nil
- var discoveredWidening: ClusterPlacementTensorBatchQuote?, fallbackWidening: ClusterPlacementTensorBatchQuote?
+ var discoveredWidths: [ClusterPlacementTensorBatchQuote] = [], fallbackWidths: [ClusterPlacementTensorBatchQuote] = []
if !settings.privateImageQualification,
case .success(let admittedValue) = capability,
ClusterPlacementTensorBatchQuote.runtimeModelIDs.contains(admittedValue.record.runtimeModelID) {
@@ -606,6 +606,17 @@ final class LiveContext: @unchecked Sendable {
? ClusterPlacementRequestLimits.chunkTokens(runtimeModelID: admitted.runtimeModelID,
artifactSHA256: admitted.artifactSHA256, layoutMaximum: measured.maximumChunkTokens,
capabilityMaximum: admitted.profile.maximumChunkTokens).tokens : description.chunkTokens
+ // The same owner's complete quote at every wider width, each of the singleton's own request and
+ // assistant: the plan saves the widest both Macs admit now, and the two-lane one also steers the
+ // retained split (capacity changes keep the shares). A width the helper does not quote is not offered.
+ func widths(of singleton: ClusterPlacementTensorBatchQuote?, mode: MTPMode) -> [ClusterPlacementTensorBatchQuote] {
+ guard let singleton else { return [] }
+ return ClusterPlacementBatchScope.tensorParallelWidths.compactMap { lanes in
+ try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory,
+ publicModelID: model.modelID, capability: admitted, mode: mode, chunkTokens: chunk,
+ deadline: deadline(), lanes: lanes)
+ }.filter { $0.request == singleton.request && $0.assistant?.policy == singleton.assistant?.policy }
+ }
if mtpMode != .off, SpecDecArtifactFunnel.killSwitchEnabled(environment: ProcessInfo.processInfo.environment),
let policy = settings.tensorAssistants[model.modelID] {
assistantQuote = .success(try ClusterPlacementTensorAssistantSelection.read(tool: tool,
@@ -618,31 +629,26 @@ final class LiveContext: @unchecked Sendable {
modelDirectory: directory, publicModelID: model.modelID, capability: admitted,
mode: discovery, chunkTokens: chunk, deadline: deadline())
assistantQuote = discovered.map { .success($0) }
- // Capacity changes keep the shares, so the first widening's complete
- // quote steers the initial split; without it the choice is speed-only.
- if discovered != nil {
- discoveredWidening = try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool,
- modelDirectory: directory, publicModelID: model.modelID, capability: admitted,
- mode: discovery, chunkTokens: chunk, deadline: deadline(), lanes: 2)
- }
+ discoveredWidths = widths(of: discovered, mode: discovery)
// Only a discovered assistant may give way to the ordinary target (`assistantOrTarget`).
if discovered?.assistant != nil {
+ var target: ClusterPlacementTensorBatchQuote?
do {
- targetFallback = try ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool,
+ target = try ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool,
modelDirectory: directory, publicModelID: model.modelID, capability: admitted,
- mode: .off, chunkTokens: chunk, deadline: deadline()).map { .success($0) }
+ mode: .off, chunkTokens: chunk, deadline: deadline())
+ targetFallback = target.map { .success($0) }
} catch { targetFallback = .failure(ClusterSetupFailure(error)) }
- fallbackWidening = try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool,
- modelDirectory: directory, publicModelID: model.modelID, capability: admitted,
- mode: .off, chunkTokens: chunk, deadline: deadline(), lanes: 2)
+ fallbackWidths = widths(of: target, mode: .off)
}
}
} catch { assistantQuote = .failure(ClusterSetupFailure(error)) }
} else { assistantQuote = nil }
return .init(model: model, layout: layout, capability: capability,
tokenizerFiles: ClusterSetupPlanning.tokenizerFiles(manifest: manifest), tensorAssistantQuote: assistantQuote,
- targetFallbackQuote: targetFallback, tensorWideningQuote: discoveredWidening,
- targetFallbackWideningQuote: fallbackWidening)
+ targetFallbackQuote: targetFallback, tensorWideningQuote: discoveredWidths.first { $0.lanes == 2 },
+ targetFallbackWideningQuote: fallbackWidths.first { $0.lanes == 2 },
+ tensorWidthQuotes: discoveredWidths, targetFallbackWidthQuotes: fallbackWidths)
}
// The profiles are kept for the serving leader's per-request route; the speed
// records of requests this pair served join the measurements (the next plan).
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift
index 85e3b9e42c..ca9e8a545a 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift
@@ -26,6 +26,10 @@ enum ClusterSetupPlanning {
/// the retained split. Absent, the split is chosen by speed alone.
var tensorWideningQuote: ClusterPlacementTensorBatchQuote? = nil
var targetFallbackWideningQuote: ClusterPlacementTensorBatchQuote? = nil
+ /// The same owners' complete quotes at the wider widths: the setup
+ /// saves the widest both Macs admit now (`ClusterPlacementTensorWidth`).
+ var tensorWidthQuotes: [ClusterPlacementTensorBatchQuote] = []
+ var targetFallbackWidthQuotes: [ClusterPlacementTensorBatchQuote] = []
}
typealias PlacementDecision = (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?)
@@ -146,12 +150,16 @@ enum ClusterSetupPlanning {
func widening(_ quote: ClusterPlacementTensorBatchQuote?) -> ClusterPlacementTensorBatchQuote? {
quote == nil ? nil : quote == discovered ? reading.tensorWideningQuote : reading.targetFallbackWideningQuote
}
+ func widths(_ quote: ClusterPlacementTensorBatchQuote?) -> [ClusterPlacementTensorBatchQuote] {
+ quote == nil ? [] : quote == discovered ? reading.tensorWidthQuotes : reading.targetFallbackWidthQuotes
+ }
let selected = try assistantOrTarget(discovered,
fallback: try? reading.targetFallbackQuote?.get()) { quote in
try ClusterPlacementFlow.decide(description: pair, capability: capability.record, localMemberID: localMemberID,
localProfile: localProfile, peerProfile: peerProfile, layout: layout, measurements: measurements,
- tensorAssistantQuote: quote, tensorWideningQuote: widening(quote), leader: sessionLeader,
- served: served, link: link, shareProbes: probes, incumbentMode: incumbent, coordinator: coordinator)
+ tensorAssistantQuote: quote, tensorWideningQuote: widening(quote), tensorWidthQuotes: widths(quote),
+ leader: sessionLeader, served: served, link: link, shareProbes: probes, incumbentMode: incumbent,
+ coordinator: coordinator)
}
var decided = selected.decision
let assistantQuote = selected.quote, fellBack = discovered != nil && selected.quote != discovered
@@ -160,8 +168,9 @@ enum ClusterSetupPlanning {
decided = try ClusterPlacementFlow.decide(description: pair.withPorts(.conventional), capability: capability.record,
localMemberID: localMemberID, localProfile: localProfile, peerProfile: peerProfile, layout: layout,
measurements: measurements, tensorAssistantQuote: assistantQuote,
- tensorWideningQuote: widening(assistantQuote), leader: sessionLeader,
- served: served, link: link, shareProbes: probes, incumbentMode: incumbent, coordinator: coordinator)
+ tensorWideningQuote: widening(assistantQuote), tensorWidthQuotes: widths(assistantQuote),
+ leader: sessionLeader, served: served, link: link, shareProbes: probes, incumbentMode: incumbent,
+ coordinator: coordinator)
if fellBack { decided.lines = [assistantDoesNotFit] + decided.lines }
}
guard let chosen = decided.result.chosen else {
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift
index d4478d00ae..edcf91c9d2 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift
@@ -44,21 +44,25 @@ extension DistributedCBv2Engine {
admissionStartedAt: admissionStartedAt, reservedAt: clock.now())
actives[state.generation] = state
observe(state, phase: .reserved)
+ // Both run from task cancellation: they never wait for the queue (a
+ // cancellation already consumed here, during reserve, still runs at once).
cancellation?.arm { [weak self, weak state] in
guard let self, let state else { return }
- self.onQueue { self.stop(state, reason: .cancelled) }
+ self.onQueueWithoutWaiting { self.stop(state, reason: .cancelled) }
}
continuation.onTermination = { [weak self, generation = state.generation] _ in
- self?.onQueue {
- guard self?.actives[generation] != nil else { return }
- self?.stop(state, reason: .cancelled)
+ guard let self else { return }
+ self.onQueueWithoutWaiting {
+ guard self.actives[generation] != nil else { return }
+ self.stop(state, reason: .cancelled)
}
}
// Always retain the engine and lease until acknowledgement, even if the
// consumer drops the stream or the owner throws after partially starting.
+ // A cooperative thread never waits for the queue.
Task { [self, state] in
await state.lease.waitUntilRetired()
- onQueue { retire(state) }
+ queue.async { [self] in retire(state) }
}
var refused = false
let admittedAt = clock.now()
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift
index 8171ad022c..62c71a93e2 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift
@@ -74,6 +74,14 @@ public final class DistributedCBv2Engine: CBv2Engine, @unchecked Sendable {
return try queue.sync(execute: body)
}
+ /// `onQueue` for a caller that must never wait for the queue: a task's
+ /// cancellation handler, or a stream's termination that cancellation runs.
+ /// Those hold the task's status lock, which the queue needs to resume that
+ /// task (a `yield` to its stream, its retirement), so waiting can deadlock.
+ func onQueueWithoutWaiting(_ body: @escaping @Sendable () -> Void) {
+ if DispatchQueue.getSpecific(key: queueKey) != nil { body() } else { queue.async(execute: body) }
+ }
+
public func cancel(_ id: CBv2RequestID) {
onQueue {
guard let state = actives.values.first(where: { $0.request.id == id }) else { return }
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift
index 6369d1c732..15036f9b2c 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift
@@ -264,8 +264,9 @@ struct DistributedInstalledPlan: Sendable {
"DARKBLOOM_CLUSTER_LOAD_DIGESTS": ["1", "tensors"],
]
- /// The pair's batch lanes: the adapter's default in the selected mode
- /// (`defaultBatchLanes(adapter:mode:hasPrivateImages:)`), unless the owner's
+ /// The pair's batch lanes: the adapter's default in the selected mode and
+ /// prefill schedule (`defaultBatchLanes(adapter:mode:hasPrivateImages:runtimeModelID:prefillSchedule:)`),
+ /// unless the setup saved a priced width or the owner's
/// environment names 1...8 (1 serves one request at a time). A malformed
/// override explicitly keeps one lane, so a sanitized child cannot restore
/// a wider family default. Nil where the
@@ -277,7 +278,8 @@ struct DistributedInstalledPlan: Sendable {
func batchLanes(_ environment: [String: String] = ProcessInfo.processInfo.environment) -> Int? {
guard let adapter = ClusterRuntimeAdapter(rawValue: capability.adapterID),
let lanes = Self.defaultBatchLanes(adapter: adapter, mode: configuration.selectedGenerationMode,
- hasPrivateImages: capability.hasPrivateImages, runtimeModelID: capability.runtimeModelID) else {
+ hasPrivateImages: capability.hasPrivateImages, runtimeModelID: capability.runtimeModelID,
+ prefillSchedule: configuration.selectedPrefillSchedule) else {
return nil
}
// The assistant quote admits exactly this capacity. A diagnostic
@@ -313,10 +315,15 @@ struct DistributedInstalledPlan: Sendable {
/// The lanes a pair of `adapter` serves by default in `mode`, or nil when
/// its workers serve one request at a time there.
/// - Pipeline: the lane adapters (`laneAdapters`), text only, at
- /// `defaultBatchLanes`.
+ /// `defaultBatchLanes`; Gemma 4 with serial prefill at
+ /// `gemma4PipelineBatchLanes`. Lanes prefill serially, so a setup that
+ /// saved the one-chunk lookahead keeps it and one lane. A nil schedule
+ /// names no setup and takes the family-neutral default.
/// - Qwen tensor parallel (every registered TP row, dense or routed
- /// experts): one by default; a priced saved width or explicit local
- /// diagnostic may select its native 2...8 lane owner.
+ /// experts): one for a setup saved without a width. Guided placement
+ /// saves the widest width both Macs admit now under its LOAD quote
+ /// (`ClusterPlacementTensorWidth`); that saved width or an explicit
+ /// local diagnostic selects the native 2...8 lane owner.
/// - Other tensor parallel: GLM (`GLM5NextTensorParallelResidentRuntime`'s lane
/// loop), at `tensorParallelBatchLanes`. Each lane keeps its request's
/// own arithmetic, so a request's tokens are those it gets alone. A
@@ -324,8 +331,11 @@ struct DistributedInstalledPlan: Sendable {
/// path as a request alone (`GLM5NextTensorParallelMedia`), so the
/// capability's image candidate does not change the lanes.
static func defaultBatchLanes(adapter: ClusterRuntimeAdapter, mode: ClusterGenerationMode,
- hasPrivateImages: Bool, runtimeModelID: String? = nil) -> Int? {
+ hasPrivateImages: Bool, runtimeModelID: String? = nil,
+ prefillSchedule: ClusterPrefillSchedule? = nil) -> Int? {
switch mode {
+ case .pipeline where !hasPrivateImages && adapter == .gemma4LayerStage && prefillSchedule == .serial:
+ gemma4PipelineBatchLanes
case .pipeline where !hasPrivateImages && laneAdapters.contains(adapter): defaultBatchLanes
case .tensorParallel where tensorParallelLaneAdapters.contains(adapter): tensorParallelBatchLanes
case .tensorParallel where servesQwenTensorLanes(adapter: adapter, runtimeModelID: runtimeModelID) && !hasPrivateImages:
@@ -343,11 +353,25 @@ struct DistributedInstalledPlan: Sendable {
/// Concurrent requests a lane-serving pair batches by default. Both
/// owners serve them (`ClusterOwnerLeaseState.lanes`), and the leader's
/// session, bridge and local API admit as many; more requests wait in the
- /// API's queue. The default stays one while the repaired joining and
- /// cancellation paths undergo model-specific multi-lane qualification.
- /// Earlier pair measurements (Qwen 3.5 35B A3B, 2026-10-19) preceded
- /// those repairs and do not qualify the current loop.
+ /// API's queue. The default stays one (Gemma 4's serial pipeline aside)
+ /// while the repaired joining and cancellation paths undergo
+ /// model-specific multi-lane qualification. Earlier pair measurements
+ /// (Qwen 3.5 35B A3B, 2026-10-19) preceded those repairs and do not
+ /// qualify the current loop. A Qwen TP width is saved at placement
+ /// instead, priced by the owner's LOAD quote; a default here would be held
+ /// to no quote.
static let defaultBatchLanes = 1
+ /// Concurrent requests a serial-prefill Gemma 4 pipeline serves by
+ /// default, coordinator-registered pairs included. Each decode row keeps
+ /// its one-request arithmetic (`Gemma4BatchDecodeScope`, bound by
+ /// `Gemma4BatchArithmeticAgreement`) and each prompt frame runs alone on
+ /// its request's own chunk grid, so a lane costs no request its own
+ /// tokens. Each lane is charged its whole request state on every rank
+ /// and admitted against live memory; a lane the host cannot hold is
+ /// refused alone, retryably. Paged KV reserves pages per request, not per
+ /// lane, so the width adds no load-time allocation. Four is one of the
+ /// priced pipeline widths (2, 4 and 8), kept until the pair measures more.
+ static let gemma4PipelineBatchLanes = 4
/// Concurrent requests GLM tensor parallel serves by default: the
/// protocol's lane cap (`ClusterWorkerLaneSession`, `ClusterWorkerPair`).
/// Its lanes run one request's unit after another (each bitwise alone), so
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchFactory.swift
index a5acf743fa..28b3b6ceaa 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchFactory.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchFactory.swift
@@ -4,9 +4,11 @@ import DarkbloomClusterPlacement
import DarkbloomClusterProtocol
import DarkbloomClusterProcess
-/// The local API's same-model scaling policy. Initial singleton placement is
-/// unchanged. Only queued demand can propose a separately priced native batch;
-/// every side effect remains inside the host's deferred post-release factory.
+/// The local API's same-model scaling policy. Only queued demand can propose a
+/// separately priced native batch wider than the running one; every side effect
+/// remains inside the host's deferred post-release factory. A Qwen TP setup is
+/// planned at the widest width both Macs admit now (`ClusterPlacementTensorWidth`),
+/// so this is the fallback for a pair planned narrower.
public actor DistributedAutomaticBatchFactory {
private let providerConfiguration: URL
private let paths: ClusterUserPaths
@@ -25,19 +27,15 @@ public actor DistributedAutomaticBatchFactory {
public func replacement(for demand: DistributedLocalBatchDemand) async throws -> DistributedLocalBatchReplacement? {
// An explicit diagnostic choice keeps its meaning. This path never
// changes an installed coordinator-approved native member contract.
+ let widths = Self.replacementWidths(for: demand)
guard environment[DistributedInstalledPlan.batchLanesSwitch] == nil,
environment[ClusterForcedModeSetting.environmentName] == nil,
environment[ClusterHandOffModes.environmentName] == nil,
- demand.waitingRequests > 0, demand.currentCapacity < 8,
+ !widths.isEmpty,
let adapter = ClusterRuntimeAdapter.registering(runtimeModelID: demand.runtimeModelID),
[.qwen35Dense, .qwen35RoutedExperts, .qwen35PrismHadamard, .nemotronH, .gemma4LayerStage, .gptossLayerStage, .mimoV26LayerStage].contains(adapter),
let child = ClusterService.publishedLive()?.child,
- child.running, child.pid == getpid(), child.configurationSHA256 != nil else { return nil }
- let total = min(8, max(0, demand.activeRequests)) + min(8, demand.waitingRequests)
- let widths = ClusterPlacementBatchScope.candidateWidths(waitingRequests: total,
- tensorParallel: ClusterPlacementTensorBatchQuote.runtimeModelIDs.contains(demand.runtimeModelID))
- .filter { $0 > demand.currentCapacity }
- guard !widths.isEmpty, attempts.begin() else { return nil }
+ child.running, child.pid == getpid(), child.configurationSHA256 != nil, attempts.begin() else { return nil }
let planner = DistributedAutomaticBatchPlanner(providerConfiguration: providerConfiguration, paths: paths)
let reference = try ClusterConfigurationStore.installedReference(providerConfiguration: providerConfiguration)
guard child.configurationSHA256 == reference.sha256 else { return nil }
@@ -65,6 +63,16 @@ public actor DistributedAutomaticBatchFactory {
makeSession: { try await transition.prepareReplacement() },
restorePreviousSession: { try await transition.restorePrevious() })
}
+
+ /// The widths queued demand may propose, widest first: only wider than the running capacity, so a pair whose
+ /// placement saved its widest admitted width is never drained for a width it already serves.
+ static func replacementWidths(for demand: DistributedLocalBatchDemand) -> [Int] {
+ guard demand.waitingRequests > 0, demand.currentCapacity < 8 else { return [] }
+ let total = min(8, max(0, demand.activeRequests)) + min(8, demand.waitingRequests)
+ return ClusterPlacementBatchScope.candidateWidths(waitingRequests: total,
+ tensorParallel: ClusterPlacementTensorBatchQuote.runtimeModelIDs.contains(demand.runtimeModelID))
+ .filter { $0 > demand.currentCapacity }
+ }
}
/// Pair-control adoption after native release. The host serializes these two
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchPlanner.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchPlanner.swift
index ece6f476af..4aae29cf23 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchPlanner.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchPlanner.swift
@@ -61,11 +61,11 @@ struct DistributedAutomaticBatchPlanner {
/// An automatic replacement cannot promise that unrelated memory will
/// disappear. A present-fit preview uses the same bilateral predicate as
- /// the mandatory post-release recheck; hardware possibility alone is not
+ /// the mandatory post-release recheck and a saved width at placement
+ /// (`ClusterPlacementTensorWidth`); hardware possibility alone is not
/// current admission.
static func accepts(_ candidate: ClusterPlacementCandidate, requireNow: Bool) -> Bool {
- candidate.possible && candidate.withinGPUWorkingSet
- && (!requireNow || candidate.ranks.allSatisfy { $0.fit == .now })
+ candidate.admitted(requireNow: requireNow)
}
/// Preview only, for a request-owned TP owner whose replacement keeps its
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift
index 0edb597639..d7b35568c4 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift
@@ -62,6 +62,7 @@ public enum ClusterPlacementFlow {
batchScope: ClusterPlacementBatchScope? = nil,
tensorAssistantQuote: ClusterPlacementTensorBatchQuote? = nil,
tensorWideningQuote: ClusterPlacementTensorBatchQuote? = nil,
+ tensorWidthQuotes: [ClusterPlacementTensorBatchQuote] = [],
regime: ClusterPlacementPolicy.Regime = .rested, leader: String? = nil,
served: [ClusterServedSpeedRecords.Entry] = [],
link: ClusterLinkCosts = .unmeasured,
@@ -279,7 +280,11 @@ public enum ClusterPlacementFlow {
policy.modesReason = policy.modesReason ?? "a capacity change keeps the running tensor-parallel shares"
policy.requiredTensorShares = incumbentTensorShares
}
- let result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link)
+ // A singleton tensor placement saves the widest width its owner's quotes admit on both Macs now. One call
+ // initializes a constant `result`, so the sizing's plans stay off this frame, which a deep planner stack shares.
+ var batchLanes = batchScope?.lanes
+ let result = try ClusterPlacementTensorWidth.plan(devices: devices, layout: layout, policy: policy, link: link,
+ quotes: tensorWidthQuotes, lanes: &batchLanes)
var lines = (forced.map(ClusterForcedModeSetting.lines) ?? [])
+ (benchCap.map(ClusterPlannerBenchCap.lines(capBytes:)) ?? []) + (benchChip.map(ClusterBenchChip.lines(chipName:)) ?? [])
+ servedLines
@@ -303,8 +308,8 @@ public enum ClusterPlacementFlow {
+ "This pair's own figure replaces it once the pair has served the same placement both with and without the rounds.")
}
if let note = granted.note { lines.append("Pair serving"); lines.append(" " + note) }
- if let batchScope {
- lines += ["Concurrent request memory", " \(batchScope.lanes) independent histories, charged at the quoted request bound on both Macs. Stage-rate predictions remain single-request estimates; no batch speed is inferred from the lane count."]
+ if let batchLanes {
+ lines += ["Concurrent request memory", " \(batchLanes) independent histories, charged at the quoted request bound on both Macs. Stage-rate predictions remain single-request estimates; no batch speed is inferred from the lane count."]
}
if records.restrictsShapes {
lines.append("Diverged placements")
@@ -334,7 +339,7 @@ public enum ClusterPlacementFlow {
lines.append(" Request deadline " + deadline.basis + ".")
}
let value = try ClusterPlacementSetup.synthesize(description: described, capability: capability,
- chosen: chosen, batchLanes: batchScope?.lanes, tensorAssistant: assistant?.policy)
+ chosen: chosen, batchLanes: batchLanes, tensorAssistant: assistant?.policy)
lines.append("What happens next")
lines += value.narration(localMemberID: localMemberID).map { " " + $0 }
setup = value
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift
new file mode 100644
index 0000000000..c948f41354
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift
@@ -0,0 +1,60 @@
+import DarkbloomClusterPlacement
+import DarkbloomClusterProtocol
+
+/// The width a request-owned Qwen TP placement saves (`ClusterConfiguration.batchLanes`), so a pair serves concurrent
+/// requests from its first load instead of after a drained replacement, and a pair saved for coordinator pairing,
+/// which never widens afterwards, serves them at all. The widest of the owner's quoted widths at which the chosen
+/// placement, its leader and split unchanged, fits both Macs now under that width's complete LOAD quote: the predicate
+/// a replacement is held to (`ClusterPlacementCandidate.admitted`). When none fits, the setup saves no width and keeps
+/// the family default.
+enum ClusterPlacementTensorWidth {
+ /// The plan `ClusterPlacementFlow.decide` keeps: `ClusterPlacementPlanner.plan`'s or, given width quotes,
+ /// `widest`'s. Never inlined, and only `widest`'s frame holds the sizing's plans: the caller's frame, which a deep
+ /// planner stack shares, holds just the one plan it keeps.
+ @inline(never)
+ static func plan(devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy,
+ link: ClusterLinkCosts, quotes: [ClusterPlacementTensorBatchQuote], lanes: inout Int?) throws
+ -> ClusterPlacementResult {
+ guard !quotes.isEmpty else {
+ return try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link)
+ }
+ return try widest(devices: devices, layout: layout, policy: policy, link: link, quotes: quotes, lanes: &lanes)
+ }
+
+ /// The singleton plan or, when the widest admitted width exists, that width's plan, with `lanes` set to it. Only a
+ /// placement priced by its owner's singleton quote is sized: a batch scope's quote, or none, leaves the plan as it
+ /// is. The mode was chosen for one request, so a sized plan keeps that choice's reasons and comparisons
+ /// (`deploymentReason`); only its chosen placement is priced at the width.
+ @inline(never)
+ static func widest(devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy,
+ link: ClusterLinkCosts, quotes: [ClusterPlacementTensorBatchQuote], lanes: inout Int?) throws
+ -> ClusterPlacementResult {
+ let singleton = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link)
+ // A split the setup can save: equal, or integer weights.
+ guard let chosen = singleton.chosen, chosen.mode == .tensorParallel, chosen.shares == nil || chosen.tensorShares != nil,
+ policy.tensorParallelBatchQuote?.lanes == 1, let leader = chosen.ranks.first?.device else { return singleton }
+ for quote in quotes.sorted(by: { $0.lanes > $1.lanes }) {
+ var widened = policy
+ try quote.applyWidth(to: &widened, layout: layout)
+ widened.modes = [.tensorParallel]; widened.schedules = [chosen.prefillSchedule]
+ widened.leader = leader; widened.requiredTensorShares = chosen.tensorShares ?? [1, 1]
+ var sized = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: widened, link: link)
+ guard let wide = sized.chosen, wide.mode == .tensorParallel, wide.ranks.map(\.device) == chosen.ranks.map(\.device),
+ wide.tensorShares == chosen.tensorShares, wide.admitted(requireNow: true) else { continue }
+ sized.modesReason = singleton.modesReason; sized.keptModeReason = singleton.keptModeReason
+ sized.tensorParallel = singleton.tensorParallel; sized.shards = singleton.shards
+ lanes = quote.lanes
+ return sized
+ }
+ return singleton
+ }
+}
+
+extension ClusterPlacementCandidate {
+ /// Possible and inside the GPU working set and, with `requireNow`, every rank fits what its Mac admits now:
+ /// hardware possibility alone is not current admission. A saved width and an automatic replacement
+ /// (`DistributedAutomaticBatchPlanner.accepts`) are held to it alike.
+ func admitted(requireNow: Bool) -> Bool {
+ possible && withinGPUWorkingSet && (!requireNow || ranks.allSatisfy { $0.fit == .now })
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift
index feda25ed98..bfd4c65e71 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift
@@ -12,6 +12,7 @@ extension EngineV2Bridge {
continuation: AsyncStream.Continuation,
holdsSharedReservation: Bool,
stopSequences: [String] = [],
+ stopStringScope: CBv2StopStringScope? = nil,
usageSignal: EngineV2RequestUsageSignal? = nil,
prefixCacheReceiptID: CBv2RequestID? = nil,
readyReceiptRegistered: Bool = false,
@@ -28,6 +29,7 @@ extension EngineV2Bridge {
id: id, events: events, continuation: continuation,
holdsSharedReservation: holdsSharedReservation,
stopSequences: stopSequences,
+ stopStringScope: stopStringScope,
usageSignal: usageSignal,
prefixCacheReceiptID: prefixCacheReceiptID,
readyReceiptRegistered: readyReceiptRegistered,
@@ -59,6 +61,7 @@ extension EngineV2Bridge {
continuation: AsyncStream.Continuation,
holdsSharedReservation: Bool,
stopSequences: [String] = [],
+ stopStringScope: CBv2StopStringScope? = nil,
usageSignal: EngineV2RequestUsageSignal? = nil,
prefixCacheReceiptID: CBv2RequestID? = nil,
readyReceiptRegistered: Bool = false,
@@ -153,7 +156,8 @@ extension EngineV2Bridge {
if reason == .stop || reason == .length {
usageSignal?.record(matchedStopSequence: matchedStopSequence(
candidates: stopSequences,
- generatedTokens: generatedTokens
+ generatedTokens: generatedTokens,
+ scope: stopStringScope
))
}
// Out-of-band usage detail: the
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift
index 6fb0f4c4c7..c038b63c5a 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift
@@ -4,7 +4,8 @@ import MLXLMCommon
extension EngineV2Bridge {
func matchedStopSequence(
candidates: [String],
- generatedTokens: [Int]
+ generatedTokens: [Int],
+ scope: CBv2StopStringScope?
) -> String? {
guard !candidates.isEmpty, !generatedTokens.isEmpty else { return nil }
let generatedText = tokenizer.inner.decode(
@@ -12,23 +13,26 @@ extension EngineV2Bridge {
skipSpecialTokens: false
)
return Self.matchedStopSequence(
- candidates: candidates, generatedText: generatedText, scope: stopStringScope)
+ candidates: candidates, generatedText: generatedText, scope: scope)
}
- /// The candidate that ended generation. A scoped model matched stops only
- /// inside its scope, so a candidate seen elsewhere (Harmony analysis) did
- /// not stop it.
+ /// The candidate that ended generation. A scoped request matched stops
+ /// only inside its scope, so a candidate seen elsewhere (Harmony analysis,
+ /// reasoning) did not stop it.
static func matchedStopSequence(
candidates: [String],
generatedText: String,
scope: CBv2StopStringScope? = nil
) -> String? {
if let scope {
- let holdback = StopHoldback(stopStrings: candidates, scope: scope)
- let scan = holdback.ingest(generatedText)
+ let scan = StopHoldback(stopStrings: candidates, scope: scope).ingest(generatedText)
guard scan.stopped else { return nil }
- let tail = generatedText.unicodeScalars.dropFirst(scan.text.unicodeScalars.count)
- return candidates.first { !$0.isEmpty && tail.starts(with: $0.unicodeScalars) }
+ // The first candidate that alone stops at the same place: one that
+ // merely starts there may not count (whitespace before an answer).
+ return candidates.first {
+ !$0.isEmpty
+ && StopHoldback(stopStrings: [$0], scope: scope).ingest(generatedText) == scan
+ }
}
let generatedScalars = Array(generatedText.unicodeScalars)
var best: (position: Int, candidateIndex: Int, value: String)?
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift
index ae75b11981..60695e7941 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift
@@ -60,6 +60,7 @@ extension EngineV2Bridge {
hybridPrefixIdentity: CBv2HybridPrefixIdentity? = nil,
mediaKind: EngineV2MediaKind? = nil,
tokenConstraint: (any CBv2TokenConstraint)? = nil,
+ stopStringScope: CBv2StopStringScope? = nil,
donationDemand: SSDCheckpointDonationDemand? = nil,
promptWork: PromptWork? = nil,
measurementPurpose: EngineMeasurementPurpose = .serving
@@ -79,6 +80,7 @@ extension EngineV2Bridge {
hybridPrefixIdentity: hybridPrefixIdentity,
mediaKind: mediaKind,
tokenConstraint: tokenConstraint,
+ stopStringScope: stopStringScope,
donationDemand: donationDemand,
firstContentDeadline: nil, promptWork: promptWork,
measurementPurpose: measurementPurpose)
@@ -131,6 +133,9 @@ extension EngineV2Bridge {
hybridPrefixIdentity: CBv2HybridPrefixIdentity? = nil,
mediaKind: EngineV2MediaKind? = nil,
tokenConstraint: (any CBv2TokenConstraint)? = nil,
+ /// Where this request's stop strings apply (`ReasoningStopScope`); nil
+ /// keeps the model's scope (`ModelEOSPolicy.stopStringScope`).
+ stopStringScope: CBv2StopStringScope? = nil,
/// Coordinator repeat-demand hint for the complete-checkpoint write
/// gate; nil keeps the legacy write-every-checkpoint behaviour.
donationDemand: SSDCheckpointDonationDemand? = nil,
@@ -317,7 +322,11 @@ extension EngineV2Bridge {
// engine which fork boundary is worth staging.
prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens,
defaultMaxTokensContextLimit: defaultMaxTokensContextLimit,
- stopStringScope: stopStringScope
+ // The native block engine's decoder matches stops over the whole
+ // output, so its requests carry no scope and the reported stop
+ // agrees with the one that matched.
+ stopStringScope: ownedEngine is CBv2NativeBlockEngine
+ ? nil : stopStringScope ?? self.stopStringScope
)
cbv2Request.mimoClusterImages = mimoClusterImages
cbv2Request.clusterStillImages = clusterStillImages
@@ -1061,6 +1070,7 @@ extension EngineV2Bridge {
id: id, events: events, continuation: continuation,
holdsSharedReservation: sharedKVReserved,
stopSequences: cbv2Request.stopStrings,
+ stopStringScope: cbv2Request.stopStringScope,
usageSignal: usageSignal,
prefixCacheReceiptID: prefixCacheReceiptID,
readyReceiptRegistered: readyReceiptRegistered,
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift
index c06745f783..59c723e673 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift
@@ -121,8 +121,8 @@ public actor EngineV2Bridge {
/// tokens) β `buildStopTokenIds` semantics, computed ONCE at bridge
/// construction so B=1 and batched behavior stay identical.
let stopTokenIds: Set
- /// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`);
- /// nil matches the whole generated text.
+ /// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`)
+ /// unless a request brings its own; nil matches the whole generated text.
let stopStringScope: CBv2StopStringScope?
/// Artifact sampling defaults resolved once at construction
/// (`EngineV2SamplingDefaults.resolve`); `.legacy` for every family
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
index b3c768dc12..e1e4b213b8 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
@@ -786,6 +786,17 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// failures) stay correct as written.
await mediaGate.release(requestId: mediaReqId)
try checkFirstContentDeadline()
+ // Initialize the think parser from the rendered media
+ // prompt: reasoning for an open block, content for a
+ // pre-closed block (thinking-disabled media). The stop
+ // scope starts in the same state.
+ let reasoningPrefix = ReasoningPromptProbe.streamingPrefix(
+ reasoningParser: visionRequest.reasoningParser,
+ stream: visionRequest.stream,
+ promptTokens: visionPrepared.promptTokens,
+ modelType: modelType,
+ decodeTail: { tokenizer.inner.decode(tokenIds: $0, skipSpecialTokens: false) }
+ ) ?? contentSeed(parser: visionRequest.reasoningParser, stream: visionRequest.stream)
// Qualified native media shares text's request-owned
// parser. Other VLMs retain their legacy media behavior.
let upstream = try await bridge.submitTokenized(
@@ -807,6 +818,10 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
multimodal: visionPrepared.multimodalInput(),
hybridPrefixIdentity: mediaPrefixIdentity,
mediaKind: visionPrepared.mediaKind,
+ stopStringScope: ReasoningStopScope.scope(
+ reasoningParser: visionRequest.reasoningParser,
+ reasoningPrefix: reasoningPrefix,
+ parsesToolCalls: toolHandler != nil),
donationDemand: donationDemand,
firstContentDeadline: firstContentDeadline,
profile: profile,
@@ -822,18 +837,6 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
await bridge.cancel(requestId: visionRequestId)
throw error
}
- // Initialize the think parser from the rendered media
- // prompt: reasoning for an open block, content for a
- // pre-closed block (thinking-disabled media).
- try checkFirstContentDeadline()
- let reasoningPrefix = ReasoningPromptProbe.streamingPrefix(
- reasoningParser: visionRequest.reasoningParser,
- stream: visionRequest.stream,
- promptTokens: visionPrepared.promptTokens,
- modelType: modelType,
- decodeTail: { tokenizer.inner.decode(tokenIds: $0, skipSpecialTokens: false) }
- ) ?? contentSeed(parser: visionRequest.reasoningParser, stream: visionRequest.stream)
- try checkFirstContentDeadline()
return try await makeDeadlineCheckedEventStream(
upstream: upstream,
cancelUpstream: { await bridge.cancel(requestId: visionRequestId) },
@@ -1038,6 +1041,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
cacheEnabled: cacheEnabled,
usageSignal: requestUsage,
tokenConstraint: tokenConstraint,
+ stopStringScope: ReasoningStopScope.scope(
+ reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix,
+ parsesToolCalls: toolHandler != nil),
donationDemand: donationDemand,
firstContentDeadline: firstContentDeadline,
profile: profile,
@@ -1419,7 +1425,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
request:Self.translate(openAIRequest:request,defaultMaxTokens:maximumOutput,
logitBias:engineV2Sampling?.logitBias,seed:engineV2Sampling?.seed),
requestId:id,cacheScope:cacheScope,cacheEnabled:false,usageSignal:requestUsage,
- multimodal:native.request.multimodal,firstContentDeadline:firstContentDeadline,profile:profile,
+ multimodal:native.request.multimodal,
+ stopStringScope:ReasoningStopScope.scope(reasoningParser:request.reasoningParser,reasoningPrefix:nil,parsesToolCalls:toolHandler != nil),
+ firstContentDeadline:firstContentDeadline,profile:profile,
measurementPurpose:measurementPurpose)
// Install the ONE existing router/forwarder before any post-submit
// cancellation veto. Its protected mode drains actual terminal/error.
diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift
index b41577d9c4..d7fb39e297 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift
@@ -83,12 +83,15 @@ private struct LocalTokenizerBridge: @unchecked Sendable, MLXLMCommon.Tokenizer,
private let chatTemplate: String?
private let modelType: String?
let promptTokenCache: PromptTokenCache?
+ /// Byte values by token ID, when the decoder holds `<0xHH>` tokens back.
+ private let heldBackBytes: [Int: UInt8]
init(
_ upstream: any Tokenizers.Tokenizer, chatTemplate: String?, modelType: String?,
promptCacheConfigurations: PromptTokenCache.Configurations?, environment: [String: String]
) {
self.upstream = upstream
+ heldBackBytes = Self.byteTokens(heldBackBy: upstream)
self.chatTemplate = chatTemplate.map {
NemotronTemplateFilters.bindingFilters(
in: normalizeSwiftJinjaTemplate($0), modelType: modelType)
@@ -111,8 +114,41 @@ private struct LocalTokenizerBridge: @unchecked Sendable, MLXLMCommon.Tokenizer,
upstream.encode(text: text, addSpecialTokens: addSpecialTokens)
}
+ /// swift-transformers' `ByteFallbackDecoder` releases `<0xHH>` tokens only when a later
+ /// token arrives, so a decode ending in them drops them and shows nothing pending: Gemma 4
+ /// lost a reply's last character outside its vocabulary, and `DetokenizerV2` could restart
+ /// its segment inside one. A partial run reads as U+FFFD, which `DetokenizerV2` holds back.
func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String {
- upstream.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens)
+ let text = upstream.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens)
+ guard !heldBackBytes.isEmpty else { return text }
+ var bytes: [UInt8] = []
+ // With `skipSpecialTokens` upstream drops special tokens before its decoder runs, so one
+ // inside or after the run does not end it.
+ for id in tokenIds.reversed() {
+ if let byte = heldBackBytes[id] {
+ bytes.append(byte)
+ } else if !skipSpecialTokens || !upstream.decode(tokens: [id], skipSpecialTokens: true).isEmpty {
+ break
+ }
+ }
+ return bytes.isEmpty ? text : text + String(decoding: bytes.reversed(), as: UTF8.self)
+ }
+
+ /// The `<0xHH>` tokens of a decoder that holds them back: a lone one decodes to nothing.
+ /// Empty for a decoder that spells or releases them, so a fixed upstream turns this off.
+ private static func byteTokens(heldBackBy upstream: any Tokenizers.Tokenizer) -> [Int: UInt8] {
+ var bytes: [Int: UInt8] = [:]
+ for value in UInt8.min...UInt8.max {
+ let token = String(format: "<0x%02X>", value)
+ // A token outside the vocabulary converts to the unknown ID.
+ if let id = upstream.convertTokenToId(token), upstream.convertIdToToken(id) == token {
+ bytes[id] = value
+ }
+ }
+ guard let probe = bytes.keys.first,
+ upstream.decode(tokens: [probe], skipSpecialTokens: false).isEmpty
+ else { return [:] }
+ return bytes
}
func convertTokenToId(_ token: String) -> Int? {
diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift
new file mode 100644
index 0000000000..0162d04e6e
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift
@@ -0,0 +1,43 @@
+// Copyright Β© 2026 Eigen Labs.
+//
+// Client stop strings end the answer, never the reasoning before it. Matched
+// against all generated text, a stop the model happened to write while it
+// reasoned ended the request before any answer: finish_reason "stop",
+// reasoning only, empty content. Each scope mirrors the request's reasoning
+// parser, so text it returns as reasoning never matches. Tool-call frames don't
+// either when the request parses tool calls; otherwise a literal tool tag in an
+// answer is text the client receives, so stops still apply.
+
+import Foundation
+import MLXLMCommon
+import MLXLMServer
+
+enum ReasoningStopScope {
+ static let think = CBv2StopStringScope.Span(opener: "", closers: [""])
+ static let thinkToolCall = CBv2StopStringScope.Span(
+ opener: "", closers: [""])
+ static let gemmaThought = CBv2StopStringScope.Span(opener: "<|channel>", closers: [""])
+ static let gemmaToolCall = CBv2StopStringScope.Span(
+ opener: "<|tool_call>", closers: [""])
+
+ /// The scope for one request. `reasoningPrefix` is the prompt's
+ /// `ReasoningPromptProbe` state: an open think block means output starts
+ /// inside reasoning. nil keeps the model's scope (GPT-OSS's Harmony final
+ /// channel) or, without a reasoning parser, whole-output matching.
+ /// `parsesToolCalls` is whether the request has a tool stream handler.
+ static func scope(
+ reasoningParser: ReasoningParserFormat?, reasoningPrefix: String?, parsesToolCalls: Bool
+ ) -> CBv2StopStringScope? {
+ switch reasoningParser {
+ case .qwen3?, .deepseekR1?:
+ return CBv2StopStringScope(
+ excluding: parsesToolCalls ? [think, thinkToolCall] : [think],
+ startingInside: reasoningPrefix == ReasoningPromptProbe.thinkOpen)
+ case .gemma4?:
+ return CBv2StopStringScope(
+ excluding: parsesToolCalls ? [gemmaThought, gemmaToolCall] : [gemmaThought])
+ default:
+ return nil
+ }
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift
index 6163b503fd..f46e6bc827 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift
@@ -136,10 +136,13 @@ extension ProviderLoop: NativePairMemberServingHost {
guard let context = clusterPairServing, start.rank == 0 else {
throw ClusterPairSlotError.notServing("this member serves no committed start")
}
- guard clusterPairServingEpoch == nil else { throw ClusterPairSlotError.notServing("a committed start is already served") }
let epoch = start.membershipEpoch
- clusterPairServingEpoch = epoch; clusterPairServingStopped = false; clusterPairServingForming = true
- defer { clusterPairServingForming = false }
+ // Its session's stop can reach this actor before its serve does.
+ guard epoch != clusterPairServingEndedEpoch else {
+ throw ClusterPairSlotError.notServing("the committed start already ended")
+ }
+ guard clusterPairServingEpoch == nil else { throw ClusterPairSlotError.notServing("a committed start is already served") }
+ clusterPairServingEpoch = epoch
let owner: any DistributedResidentExecutionOwner
do { owner = try await Task.detached { try context.makeOwner(start) }.value }
catch {
@@ -147,9 +150,10 @@ extension ProviderLoop: NativePairMemberServingHost {
recordClusterPairIncident(.activationLaunchFailed, error: error, context: context, start: start)
endClusterPairServing(epoch); throw error
}
- // A stop that arrived while the pair formed wins: nothing publishes.
- guard clusterPairServingEpoch == epoch, !clusterPairServingStopped else {
- await owner.shutdown(); endClusterPairServing(epoch)
+ // A stop that arrived while the pair formed wins: nothing publishes,
+ // and the next start may already hold the member.
+ guard clusterPairServingEpoch == epoch else {
+ await owner.shutdown()
throw ClusterPairSlotError.notServing("the committed start ended while the pair formed")
}
let wire = start.identity
@@ -169,25 +173,28 @@ extension ProviderLoop: NativePairMemberServingHost {
modelDirectory: context.modelDirectory, pairTelemetry: telemetry)
do { try await publishClusterPairSlot(specification, owner: owner) }
catch { await owner.shutdown(); endClusterPairServing(epoch); throw error }
- clusterPairServingForming = false
// A stop during the publication hops retires what was just published.
- if clusterPairServingStopped { await stopServingCommittedStart(epoch: epoch) }
+ if clusterPairServingEpoch != epoch { await retireCommittedStartSlot(epoch) }
}
public func stopServingCommittedStart(epoch: UUID) async {
- guard clusterPairServingEpoch == epoch else { return }
- clusterPairServingStopped = true
- // The session sends its release receipt once this returns, so the
- // slot retires first, even while the serve still forms the pair (its
- // publication and warmup canary can take minutes). Retirement is
- // idempotent and the publication stops at a retired slot.
- if let handle = clusterPairSlot, handle.membershipEpoch == epoch {
- await retireClusterPairSlot(handle.id, reason: "committed start ended")
- }
- // A serve still forming sees the stop and ends the start itself;
- // ending it here would let the next start begin under it.
- guard !clusterPairServingForming else { return }
+ // The start ends with its session, now: not when the slot's drain or
+ // a serve still under way ends, which can outlast the session's own
+ // bounded wait (its receipt then lets the coordinator commit the next
+ // start). A serve that lost its start stands down by itself, and the
+ // retirement below closes the slot's admission before it suspends.
+ clusterPairServingEndedEpoch = epoch
endClusterPairServing(epoch)
+ // The session sends its release receipt once this returns, so every
+ // call waits until the slot retired, even while the serve still forms
+ // the pair (its publication and warmup canary can take minutes).
+ // Retirement is idempotent and the publication stops at a retired slot.
+ await retireCommittedStartSlot(epoch)
+ }
+
+ private func retireCommittedStartSlot(_ epoch: UUID) async {
+ guard let handle = clusterPairSlot, handle.membershipEpoch == epoch else { return }
+ await retireClusterPairSlot(handle.id, reason: "committed start ended")
}
/// One incident about a committed start this leader serves (S24), with
@@ -206,6 +213,6 @@ extension ProviderLoop: NativePairMemberServingHost {
/// Clears the served epoch, once, for this epoch only.
func endClusterPairServing(_ epoch: UUID) {
guard clusterPairServingEpoch == epoch else { return }
- clusterPairServingEpoch = nil; clusterPairServingStopped = false; clusterPairServingForming = false
+ clusterPairServingEpoch = nil
}
}
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift
index 8ffe9fdd59..bea3888653 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift
@@ -733,13 +733,12 @@ public actor ProviderLoop {
/// When the pair slot's engine was first seen wedged ("crashed"), for the
/// supervisor's liveness guard (S18).
internal var clusterPairWedgedSince: ContinuousClock.Instant?
- /// The leader's serving context for committed starts (S10), and the one
- /// start it serves: its epoch, whether the session asked it to stop, and
- /// whether the pair is still forming.
+ /// The leader's serving context for committed starts (S10), the one
+ /// start it serves (held from its serve until its session's stop), and
+ /// the last start whose session stopped, which is never served after.
internal var clusterPairServing: ClusterPairServingContext?
internal var clusterPairServingEpoch: UUID?
- internal var clusterPairServingStopped = false
- internal var clusterPairServingForming = false
+ internal var clusterPairServingEndedEpoch: UUID?
/// The follower member's link serving of its committed starts; retained
/// here because the session control holds its serving host weakly.
internal var clusterPairFollower: DistributedMemberLinkFollower?
diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift
index 41956de4b2..ce784144a1 100644
--- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift
+++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift
@@ -201,6 +201,23 @@ extension InstalledSessionCheck {
registered: ("registered_gemma4_26b_qat_4bit", "registered_gemma4_26b_qat_4bit_greedy_generation_v1", "fixture/gemma"),
adapter: .gemma4LayerStage)
let gemmaPrepared = try gemma.prepare()
+ // A serial-prefill Gemma pipeline, coordinator-registered or not, serves its four default lanes.
+ try require(gemmaPrepared.plan.configuration.selectedPrefillSchedule == .serial
+ && gemmaPrepared.plan.batchLanes([:]) == DistributedInstalledPlan.gemma4PipelineBatchLanes
+ && gemmaPrepared.plan.lanesRetireAlone([:]), "Gemma serial pipeline default lanes differ")
+ let gemmaDefault = gemmaPrepared.plan.nativeEnvironment(matrix: gemmaPrepared.matrixURL,
+ ownerEnvironment: try observed(gemmaPrepared.plan.localOwnerConfiguration(ownerEnvironment: [:])))
+ try require(gemmaDefault[key] == String(DistributedInstalledPlan.gemma4PipelineBatchLanes),
+ "Gemma default lanes did not reach the rank")
+ // A saved one-chunk lookahead keeps its schedule: lanes prefill serially, so it keeps one lane.
+ let lookahead = try InstalledFixture.make(root: f.root.appendingPathComponent("lane-gemma-lookahead"),
+ probe: f.probe, owner: probe, worker: f.worker,
+ registered: ("registered_gemma4_26b_qat_4bit", "registered_gemma4_26b_qat_4bit_greedy_generation_v1", "fixture/gemma"),
+ adapter: .gemma4LayerStage, prefillSchedule: .oneChunkLookahead)
+ let lookaheadPlan = try lookahead.prepare().plan
+ try require(lookaheadPlan.configuration.selectedPrefillSchedule == .oneChunkLookahead
+ && lookaheadPlan.batchLanes([:]) == 1 && !lookaheadPlan.lanesRetireAlone([:]),
+ "Gemma lookahead pipeline gained default lanes")
for lanes in [1, 2, 4, 8] {
let child = try observed(gemmaPrepared.plan.localOwnerConfiguration(ownerEnvironment: [key: String(lanes)]))
let native = gemmaPrepared.plan.nativeEnvironment(matrix: gemmaPrepared.matrixURL, ownerEnvironment: child)
diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift
index 37e14e873a..af24383ab6 100644
--- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift
+++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift
@@ -22,7 +22,7 @@ struct InstalledFixture: Sendable {
registered: (model: String, profile: String, publicID: String) = ("registered_qwen35_9b",
"registered_qwen35_9b_greedy_generation_v1", "fixture/public-model"),
adapter: ClusterRuntimeAdapter = .qwen35Dense, standsForRegisteredArtifact: Bool = true,
- batchLanes: Int? = nil) throws -> Self {
+ batchLanes: Int? = nil, prefillSchedule: ClusterPrefillSchedule? = nil) throws -> Self {
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
let model = root.appendingPathComponent("model", isDirectory: true)
try FileManager.default.createDirectory(at: model, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
@@ -58,6 +58,7 @@ struct InstalledFixture: Sendable {
.init(rank:0,sourceLayerStart:0,sourceLayerEnd:4,stagePlanSHA256:pin("1"),constructionConfigurationSHA256:pin("2")),
.init(rank:1,sourceLayerStart:4,sourceLayerEnd:32,stagePlanSHA256:pin("3"),constructionConfigurationSHA256:pin("4"))])],
arithmeticPolicyID:adapter.arithmeticPolicyID,arithmeticPolicySHA256:pin("5"),
+ supportedPrefillSchedules:prefillSchedule == nil ? [.serial] : ClusterPrefillSchedule.allCases,
supportedGenerationModes:advertisedModes)
let capBytes = try ClusterRuntimeCapabilityCodec.encode(cap), capHash = hash(capBytes)
try capBytes.write(to: model.appendingPathComponent("fixture-capability.json"))
@@ -76,6 +77,7 @@ struct InstalledFixture: Sendable {
"tokenizerFiles":named.filter{$0.1 != "config"}.map{["path":$0.0,"sha256":hash($0.2),"purpose":$0.1 == "template" ? "chatTemplate":"tokenizer"]}]
if let generationMode { object["generationMode"]=generationMode }
if let batchLanes { object["batchLanes"] = batchLanes }
+ if let prefillSchedule { object["prefillSchedule"] = prefillSchedule.rawValue }
if pairing {
let approval:[String:Any]=["id":"installed-fixture-approval","model":"fixture/public-model","generation":1,
"plan_sha256":pin("f"),"artifact_sha256":artifact,"native_runtime_sha256":binary,"metallib_sha256":pin("6"),
diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift
index 5c90dfd238..60a9c05081 100644
--- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift
+++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift
@@ -981,7 +981,9 @@ final class EndpointBox: @unchecked Sendable {
/// values every rank is given (the pair driver's own values), under budgets
/// derived from the setup; GPT-OSS and Gemma 4 included.
static func adaptersOnTheInstalledPath(_ f:InstalledFixture) throws {
- let gemma=["MLX_GATHER_QMM_EXPERT_SLICES":"trust","MLX_GEMMA4_FUSED_WEIGHTED_UNSORT":"1"]
+ // A serial-prefill Gemma pipeline also names its default lanes.
+ let gemma=["MLX_GATHER_QMM_EXPERT_SLICES":"trust","MLX_GEMMA4_FUSED_WEIGHTED_UNSORT":"1",
+ DistributedInstalledPlan.batchLanesSwitch:String(DistributedInstalledPlan.gemma4PipelineBatchLanes)]
let cases:[(String,ClusterRuntimeAdapter,String,[String:String],String?)]=[
("a35",.qwen35RoutedExperts,"registered_qwen35_35b_a3b",["MLX_GATHER_QMM_EXPERT_SLICES":"trust"],"phase_split_v1"),
("a36",.qwen35RoutedExperts,"registered_qwen36_35b_a3b",["MLX_GATHER_QMM_EXPERT_SLICES":"trust"],"phase_split_v1"),
diff --git a/provider-swift/Tests/ClusterPlacementChecks/run.sh b/provider-swift/Tests/ClusterPlacementChecks/run.sh
index 4ac7ce3d18..33731c0298 100755
--- a/provider-swift/Tests/ClusterPlacementChecks/run.sh
+++ b/provider-swift/Tests/ClusterPlacementChecks/run.sh
@@ -42,6 +42,7 @@ xcrun swiftc -j 4 "${task_flags[@]}" -D DARKBLOOM_CLUSTER_FIXTURE_ARTIFACTS -par
"$task_provider/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairQualificationRecords.swift" \
"$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementSetup.swift" \
"$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift" \
+ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift" \
"$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterForcedModeSetting.swift" \
"$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlannerBenchCap.swift" \
"$task_provider/Sources/ProviderCore/Inference/Distributed/Installed/ClusterBenchChip.swift" \
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift
index 690546bba2..7b85a3de14 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift
@@ -30,11 +30,12 @@ final class ClusterApprovalMacs: @unchecked Sendable {
static let chip = ClusterChipClass(chipName: "Apple M3 Ultra")
/// What both Macs' setups place: the Qwen3.5 9B pipeline, or Qwen3.8 27B in tensor parallel as the guided setup
- /// saves it, with or without the model's embedded speculative assistant (`ClusterConfiguration.tensorAssistant`)
- /// and with equal shares or the unequal ones a plan for two unequal Macs saves (`ClusterConfiguration.tensorShares`).
+ /// saves it, with or without the model's embedded speculative assistant (`ClusterConfiguration.tensorAssistant`),
+ /// with equal shares or the unequal ones a plan for two unequal Macs saves (`ClusterConfiguration.tensorShares`),
+ /// and the width its placement saved (`ClusterConfiguration.batchLanes`).
enum Shape {
case pipeline
- case qwen27TensorParallel(assistant: ClusterQwenTensorAssistantPolicy?, shares: [Int]? = nil)
+ case qwen27TensorParallel(assistant: ClusterQwenTensorAssistantPolicy?, shares: [Int]? = nil, lanes: Int? = nil)
}
let root: URL
@@ -153,10 +154,11 @@ final class ClusterApprovalMacs: @unchecked Sendable {
"linkControl": ["schema": ClusterLinkControlAttachment.schemaName, "port": 47999,
"linkEpoch": record.link.linkEpoch, "edgeID": record.link.edgeID, "secretFile": secret.path],
"tokenizerFiles": [["path": "tokenizer.json", "sha256": h("6"), "purpose": "tokenizer"]]]
- if case .qwen27TensorParallel(let assistant, let shares) = shape {
+ if case .qwen27TensorParallel(let assistant, let shares, let lanes) = shape {
configuration["generationMode"] = ClusterGenerationMode.tensorParallel.rawValue
if let assistant { configuration["tensorAssistant"] = assistant.object }
if let shares { configuration["tensorShares"] = shares }
+ if let lanes { configuration["batchLanes"] = lanes }
}
let input = mac.scratch.appendingPathComponent("setup.json"), capabilityInput = mac.scratch.appendingPathComponent("capability.json")
try JSONSerialization.data(withJSONObject: configuration, options: [.sortedKeys]).write(to: input)
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthRegisteredTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthRegisteredTests.swift
new file mode 100644
index 0000000000..b960d4433c
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthRegisteredTests.swift
@@ -0,0 +1,173 @@
+import DarkbloomClusterPlacement
+@testable import DarkbloomClusterRuntime
+import DarkbloomClusterProtocol
+import Foundation
+import Testing
+@testable import ProviderCore
+
+/// The width the registered Qwen3.8 27B saves on idle pairs of each size: its retained headers, LOAD's own quote at
+/// every width (`ClusterPlacementArtifact.tensorBatchQuote`, as `tensor-batch-scope` derives it) and the guided step's
+/// own decision (`ClusterPlacementFlow.decide`), plain (a pair served through Darkbloom) and with the depth-3 assistant
+/// (a local pair). The vision tower's resident bytes are left out, as the served layout leaves them. Header metadata
+/// only: no model, no GPU.
+struct ClusterPlacementTensorWidthRegisteredTests {
+ private struct Retained: Decodable {
+ struct Tensor: Decodable { let name: String; let shape: [Int]; let sourceDType: String; let byteCount: Int }
+ struct Profile: Decodable { let configuration: Data; let canonicalTensors: [Tensor] }
+ let twentySeven: Profile
+ }
+ private struct Assistant: Decodable {
+ struct Tensor: Decodable { let name: String; let shape: [Int]; let dtype: String; let byteCount: Int }
+ let tensors: [Tensor]
+ }
+ private static let gib = 1 << 30
+ private static func bound(_ bytes: Int) -> Int { ((bytes + 16_383) / 16_384) * 16_384 }
+ private static func hash(_ c: Character) -> String { String(repeating: String(c), count: 64) }
+
+ /// An idle Mac of `physicalGiB`, as the placement checks construct one (`SyntheticMac.idle`): wired 3 % (at least
+ /// 2.5 GiB), other programs 4 % (at least 3 GiB), 1 GiB of file cache, the rest free.
+ private static func idle(_ physicalGiB: Double) throws -> ClusterDeviceProfile {
+ let page = 16_384
+ func pages(_ value: Double) -> Int { Int((value * Double(gib) / Double(page)).rounded()) }
+ let wiredGiB = max(2.5, physicalGiB * 0.03), otherGiB = max(3, physicalGiB * 0.04)
+ let physical = pages(physicalGiB), wired = pages(wiredGiB), free = pages(physicalGiB - wiredGiB - otherGiB - 1)
+ let cache = pages(1), pageable = physical - wired, anonymous = max(0, pageable - free - cache)
+ let observation = QwenDenseStageLoadOSObservation(startedNanoseconds: 900, completedNanoseconds: 1_000,
+ timestampUTC: "2026-11-01T00:00:00Z", physicalMemoryBytes: physical * page, pageSizeBytes: page,
+ kernelFreePages: free, freePages: free, inactivePages: cache + anonymous / 2, speculativePages: 0,
+ actualFreeBytes: free * page, estimatedReclaimableBytes: (free + cache + anonymous / 2) * page, pressureLevel: 1,
+ swapUsedBytes: 0, activePages: anonymous - anonymous / 2, fileBackedPages: cache, anonymousPages: anonymous,
+ wiredPages: wired, purgeablePages: 0, compressorPages: 0, kernelFileCacheMinimumPages: nil,
+ inactiveFileBackedPages: cache, inactiveAnonymousPages: anonymous / 2, compressionPages: 0, swapoutPages: 0,
+ liveCompressionPages: 0)
+ let bytes = physical * page, workingSet = bytes / 4 * 3
+ var profile = try ClusterDeviceProfile(chip: "Synthetic", performanceCores: 8, efficiencyCores: 4, gpuCores: nil,
+ osVersion: "27.0", osBuild: "SYNTH", physicalMemoryBytes: bytes, gpuRecommendedWorkingSetBytes: workingSet,
+ gpuMaximumBufferBytes: bytes / 2, allocatorLimitBytes: min(workingSet / 2 * 3, bytes / 100 * 95),
+ memory: .gate(observation, now: 1_100),
+ power: .init(onExternalPower: true, lowPowerMode: false, thermalState: "nominal"))
+ profile.speedIndex = .init(chip: profile.chip, osBuild: profile.osBuild, benchmark: "qmm_h4096_b4_g64_x16_v1",
+ prefillIndex: 1_000_000, decodeIndex: 25_000)
+ return profile
+ }
+
+ private struct Registered {
+ let layout: ClusterModelLayout
+ let capability: ClusterRuntimeCapability
+ let pair: ClusterPairDescription
+ /// Each kind's quotes by width, 1 through 8.
+ let plain: [Int: ClusterPlacementTensorBatchQuote]
+ let assisted: [Int: ClusterPlacementTensorBatchQuote]
+ }
+
+ private static func registered() throws -> Registered {
+ let tests = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("libs/darkbloom-cluster/Tests", isDirectory: true)
+ let retained = try JSONDecoder().decode(Retained.self, from: Data(contentsOf: tests
+ .appendingPathComponent("StageMetadataChecks/Inputs/qwen-retained-inputs.json"))).twentySeven
+ let family = try QwenDensePlacementFamily(configuration: retained.configuration), p = family.profile
+ let plan = try #require(family.tensorParallel)
+ let text = retained.canonicalTensors.map {
+ ClusterPlacementStoredTensor(name: $0.name, byteCount: $0.byteCount, dtype: $0.sourceDType, shape: $0.shape)
+ }
+ let head = try JSONDecoder().decode(Assistant.self, from: Data(contentsOf: tests
+ .appendingPathComponent("DarkbloomClusterRuntimeTests/Inputs/qwen27-tp-mtp-inventory.json"))).tensors.map {
+ ClusterPlacementStoredTensor(name: $0.name, byteCount: $0.byteCount, dtype: $0.dtype, shape: $0.shape)
+ }
+ var planning = family
+ planning.tensorParallelRequestAllowance = try QwenTensorParallelRequestBudget.derive(geometry: family.geometry,
+ plan: plan, tensors: family.requireRegisteredInventory(text), maximumTokens: family.largestContextTokens,
+ chunkSize: family.maximumChunkTokens, allocationBound: bound).allowance
+ let specification = family.definition.specification
+ var object = try JSONSerialization.jsonObject(with: ClusterModelLayoutBuilder.build(family: planning,
+ tensors: text + head, artifactSHA256: specification.artifactSHA256,
+ configurationSHA256: specification.configurationSHA256).encoded()) as! [String: Any]
+ let listed = (object["generationModes"] as? [String] ?? []) + [ClusterGenerationMode.tensorParallel.rawValue]
+ object["generationModes"] = ClusterGenerationMode.allCases.map(\.rawValue).filter(listed.contains)
+ let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]))
+ let request = try ClusterPlacementRequestScope(runtimeModelID: family.runtimeModelID,
+ artifactSHA256: specification.artifactSHA256, configurationSHA256: specification.configurationSHA256,
+ promptTokens: p.maximumPromptTokens, outputTokens: p.maximumOutputTokens, maximumPromptTokens: p.maximumPromptTokens,
+ maximumOutputTokens: p.maximumOutputTokens, maximumContextTokens: p.maximumContextTokens,
+ requestChargeEveryRankBytes: family.requestChargeEveryRankBytes(contextTokens: p.maximumPromptTokens + p.maximumOutputTokens))
+ func quotes(_ depth: Int?) throws -> [Int: ClusterPlacementTensorBatchQuote] {
+ try Dictionary(uniqueKeysWithValues: [1, 2, 4, 6, 8].map { lanes in
+ (lanes, try ClusterPlacementArtifact.tensorBatchQuote(configuration: retained.configuration, stored: text + head,
+ request: request, chunkTokens: p.maximumChunkTokens, lanes: lanes, assistantDepth: depth,
+ assistantVerification: depth == nil ? .singleton : .admittedCohort, allocationBound: bound))
+ })
+ }
+ let partitions = layout.admittedCuts.enumerated().map { index, cut in
+ ClusterRuntimePartition(planSHA256: String(format: "%064lx", index + 1), stages: [
+ .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: cut, stagePlanSHA256: String(format: "%064lx", 100 + index),
+ constructionConfigurationSHA256: hash("2")),
+ .init(rank: 1, sourceLayerStart: cut, sourceLayerEnd: layout.layerCount, stagePlanSHA256: String(format: "%064lx", 200 + index),
+ constructionConfigurationSHA256: hash("4"))])
+ }
+ let capability = try ClusterRuntimeCapability(runtimeBinarySHA256: hash("a"), adapterID: "qwen35-dense-layer-stage",
+ adapterVersion: 1, runtimeModelID: layout.runtimeModelID, artifactSHA256: layout.artifactSHA256,
+ configurationSHA256: layout.configurationSHA256, manifestSHA256: hash("d"),
+ profile: .init(id: "registered_qwen38_27b_greedy_generation_v1", vocabularySize: 248320,
+ maximumPromptTokens: p.maximumPromptTokens, maximumOutputTokens: p.maximumOutputTokens,
+ maximumChunkTokens: p.maximumChunkTokens, maximumContextTokens: p.maximumContextTokens),
+ profileFingerprint: hash("e"), partitions: partitions, arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1",
+ arithmeticPolicySHA256: hash("5"), supportedGenerationModes: [.pipeline, .tensorParallel])
+ let pair = ClusterPairDescription(schema: ClusterPairDescription.schemaName, clusterID: "fixture-cluster",
+ publicModelID: "EigenLabs/Qwen3.8-27B-4bit-mtp",
+ capabilitySHA256: ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(capability)),
+ chunkTokens: p.maximumChunkTokens, requestTimeoutSeconds: 315, coordinatorPort: 5577,
+ members: ["a", "b"].enumerated().map { index, id in
+ .init(id: id, host: "192.0.2.\(index + 1)", port: 22, user: "fixture",
+ ownerExecutable: "/fixture/darkbloom", workerExecutable: "/fixture/worker", modelDirectory: "/fixture/model",
+ runtimeBinarySHA256: hash("a"), jacclDevice: "en7", linkAddress: "192.0.2.\(index + 1)", trust: nil,
+ linkSecretFile: "/fixture/\(id).secret")
+ }, tokenizerFiles: [.init(path: "tokenizer.json", sha256: hash("6"), purpose: .tokenizer)],
+ linkControl: .init(port: 5578, linkEpoch: UUID().uuidString.lowercased(), edgeID: UUID().uuidString.lowercased()))
+ return .init(layout: layout, capability: capability, pair: pair, plain: try quotes(nil), assisted: try quotes(3))
+ }
+
+ @Test func twoM5UltrasSaveEightAndSmallerPairsTheWidestTheirQuoteAdmits() throws {
+ let model = try Self.registered()
+ let link = ClusterLinkCosts(measured: true, perChunkSeconds: 0.002, perDecodeStepSeconds: [:],
+ handoffSecondsPerByte: 1 / 2e9, provenance: "constructed for a check",
+ reduction: .init(fixedSeconds: 1e-6, secondsPerByte: 1 / 5e9, keyed: true, provenance: "constructed for a check"))
+ for (kind, quotes) in [("plain", model.plain), ("assistant", model.assisted)] {
+ let singleton: ClusterPlacementTensorBatchQuote = try #require(quotes[1])
+ for lanes in [1, 2, 4, 6, 8] {
+ let quote: ClusterPlacementTensorBatchQuote = try #require(quotes[lanes])
+ print("qwen27-tp-width-quote kind=\(kind) lanes=\(lanes) request_bytes=\(quote.allowance.requestBytesExcludingCollectives)"
+ + " reserved_bytes=\(quote.allowance.reservedBytes) per_lane_bytes=\(quote.perLaneStateBytes)"
+ + " rank0_equal_bytes=\(quote.rankReservedBytes(rank: 0, shares: nil) ?? -1)"
+ + " rank1_equal_bytes=\(quote.rankReservedBytes(rank: 1, shares: nil) ?? -1)")
+ }
+ /// The width a pair of these two idle Macs saves (1: none), or nil when tensor parallel is not placed.
+ func saved(_ localGiB: Double, _ peerGiB: Double) throws -> Int? {
+ let decided = try ClusterPlacementFlow.decide(description: model.pair, capability: model.capability,
+ localMemberID: "a", localProfile: try Self.idle(localGiB), peerProfile: try Self.idle(peerGiB), layout: model.layout,
+ tensorAssistantQuote: singleton, tensorWidthQuotes: [2, 4, 6, 8].compactMap { quotes[$0] },
+ leader: "a", link: link, environment: [:], benchDebugBuild: false)
+ guard let chosen = decided.result.chosen, chosen.mode == .tensorParallel, let setup = decided.setup else {
+ print("qwen27-tp-width kind=\(kind) mac_gib=\(Int(localGiB))+\(Int(peerGiB)) placed=false")
+ return nil
+ }
+ let lanes = try ClusterConfigurationCodec.decode(try #require(setup.configurations["a"]),
+ capability: model.capability, capabilitySHA256: model.pair.capabilitySHA256).batchLanes ?? 1
+ print("qwen27-tp-width kind=\(kind) mac_gib=\(Int(localGiB))+\(Int(peerGiB)) lanes=\(lanes) shares=\(chosen.tensorShares ?? [1, 1])"
+ + chosen.ranks.map { " rank\($0.rank)_need_bytes=\($0.needBytes) rank\($0.rank)_admissible_now_bytes=\($0.admissibleNowBytes)" }.joined())
+ // Within what each Mac admits now, under the saved width's own quote.
+ #expect(chosen.ranks.allSatisfy { $0.needBytes <= $0.admissibleNowBytes && $0.fit == .now })
+ return lanes
+ }
+ var widths: [Int] = []
+ for size in [32.0, 36, 48, 64, 96, 128, 192, 256] {
+ guard let lanes = try saved(size, size) else { continue }
+ #expect(lanes >= (widths.last ?? 1), "\(kind) 2 x \(Int(size)) GiB: a larger pair never saves a narrower width")
+ widths.append(lanes)
+ }
+ #expect(widths.last == 8, "2 x 256 GiB, \(kind)")
+ #expect(widths.contains { $0 < 8 }, "\(kind): a smaller pair saves a narrower width")
+ for (local, peer) in [(256.0, 36.0), (256.0, 48.0), (256.0, 128.0)] { _ = try saved(local, peer) }
+ }
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift
new file mode 100644
index 0000000000..ac5ee2dfdc
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift
@@ -0,0 +1,280 @@
+import DarkbloomClusterPlacement
+import DarkbloomClusterProtocol
+import Foundation
+import Testing
+@testable import ProviderCore
+
+/// The width a Qwen TP placement saves (`ClusterPlacementTensorWidth`), through the guided step's own decision
+/// (`ClusterPlacementFlow.decide`) with constructed profiles and quotes. CPU metadata only; none is a hardware result.
+@Suite(.serialized)
+final class ClusterPlacementTensorWidthTests {
+ private var homes: [URL] = []
+ deinit { for home in homes { try? FileManager.default.removeItem(at: home) } }
+ private let gib = 1_073_741_824
+ private func hash(_ c: Character) -> String { String(repeating: String(c), count: 64) }
+
+ /// A home with a recorded keyed link between the two members, so tensor parallel is planned on a measured link.
+ private func home() throws -> URL {
+ let result = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
+ .appendingPathComponent("tensor-width-inputs-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: result, withIntermediateDirectories: false,
+ attributes: [.posixPermissions: 0o700])
+ homes.append(result)
+ let probe = ClusterWorkerLinkProbe(transport: "jaccl", keyed: true, pointToPointSmallBytes: 4096,
+ pointToPointSmallMicroseconds: 1, pointToPointLargeBytes: 1_048_576, pointToPointLargeMicroseconds: 10,
+ allSumSmallBytes: 4096, allSumSmallMicroseconds: 1, allSumLargeBytes: 1_048_576, allSumLargeMicroseconds: 10)
+ #expect(ClusterLinkProbeHistory.record(probe, members: ["a", "b"], homeDirectory: result))
+ return result
+ }
+
+ private func profile(free: Int) throws -> ClusterDeviceProfile {
+ let physical = 256 * gib
+ var p = try ClusterDeviceProfile(chip: "Constructed width fixture", performanceCores: 8, efficiencyCores: 4,
+ gpuCores: 40, osVersion: "27.0", osBuild: "CHECK", physicalMemoryBytes: physical,
+ gpuRecommendedWorkingSetBytes: 192 * gib, gpuMaximumBufferBytes: 128 * gib, allocatorLimitBytes: 230 * gib,
+ memory: .init(gatePolicy: "fixture", sampledUTC: "2026-11-01T00:00:00Z", judged: true, unjudgedReason: nil,
+ physicalMemoryBytes: physical, actualFreeBytes: free, countedFileCacheBytes: 0, admissibleNowBytes: free,
+ fileBackedBytes: 0, fileCacheReserveBytes: 0, fileCacheAboveReserveBytes: 0, anonymousBytes: physical - free - 4 * gib,
+ wiredBytes: 4 * gib, compressorBytes: 0, pageableBytes: 252 * gib, pressureLevel: 1, swapUsedBytes: 0,
+ minimumAdmissibleBytes: 6 * gib, minimumTrulyFreeBytes: 16 * 1_048_576, loadingHeadroomBytes: 4 * gib,
+ allocatorHeadroomBytes: 2 * gib, loadScratchBytes: 8 * 1_048_576, pageSizeBytes: 16_384),
+ power: .init(onExternalPower: true, lowPowerMode: false, thermalState: "nominal"))
+ p.speedIndex = .init(chip: p.chip, osBuild: p.osBuild, benchmark: "qmm_h4096_b4_g64_x16_v1",
+ prefillIndex: 1_000_000, decodeIndex: 25_000)
+ return p
+ }
+
+ /// A registered Qwen TP row's identity: the 27B, whose features keep its plans to tensor parallel
+ /// (`ClusterModelFeaturePolicy`), or the 9B, whose plans keep the pipeline a candidate, as the 35B A3B rows' do.
+ private typealias Row = (model: String, profile: String)
+ private static let twentySevenB: Row = ("registered_qwen38_27b", "registered_qwen38_27b_greedy_generation_v1")
+ private static let nineB: Row = ("registered_qwen35_9b", "registered_qwen35_9b_greedy_generation_v1")
+
+ /// A registered row's identity (the 27B's by default) on a constructed two-layer layout whose tensor parallel
+ /// splits 1:1, 1:2 or 2:1.
+ private func fixture(_ row: Row = twentySevenB)
+ throws -> (ClusterPairDescription, ClusterRuntimeCapability, ClusterModelLayout, ClusterPlacementRequestScope) {
+ let model = row.model
+ let part = ClusterModelLayout.Part(storedBytes: 2 * gib, loadedBytes: 2 * gib, largestTensorBytes: gib / 4, tensorCount: 16)
+ let end = ClusterModelLayout.Part(storedBytes: gib / 2, loadedBytes: gib / 2, largestTensorBytes: gib / 2, tensorCount: 1)
+ let raw = ClusterModelLayout(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"),
+ layers: (0..<2).map { .init(index: $0, kind: "fixture", weights: part, stateFixedBytes: 1024,
+ stateBytesPerToken: 1024, cost: 1) }, ingress: end, egress: end, excluded: .init(), admittedCuts: [1],
+ structuralCuts: [1], generationModes: [.pipeline, .tensorParallel], prefillSchedules: [.serial],
+ maximumPromptTokens: 1024, maximumOutputTokens: 128, maximumChunkTokens: 128,
+ boundaryBytesPerToken: 4096, requestChargeEveryRankBytes: gib)
+ let tensor = ClusterTensorParallelLayout(family: .init(plan: "fixture-heads", ranks: [2], reductionsPerLayer: 1,
+ reductionsPerStep: 0, partialBytesPerToken: 4096, stateDividesByHeads: true, shareOptions: [[1, 2], [2, 1]]),
+ layerDividedBytes: [2 * gib, 2 * gib], layerReplicatedBytes: [0, 0],
+ ingressDividedBytes: 0, ingressReplicatedBytes: gib / 2, egressDividedBytes: gib / 2, egressReplicatedBytes: 0)
+ var object = try JSONSerialization.jsonObject(with: raw.encoded()) as! [String: Any]
+ object["tensorParallel"] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(tensor))
+ let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object))
+ let cap = try ClusterRuntimeCapability(runtimeBinarySHA256: hash("a"), adapterID: "qwen35-dense-layer-stage", adapterVersion: 1,
+ runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), manifestSHA256: hash("d"),
+ profile: .init(id: row.profile, vocabularySize: 248320,
+ maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumChunkTokens: 512, maximumContextTokens: 65536),
+ profileFingerprint: hash("e"), partitions: [.init(planSHA256: hash("f"), stages: [
+ .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 1, stagePlanSHA256: hash("1"), constructionConfigurationSHA256: hash("2")),
+ .init(rank: 1, sourceLayerStart: 1, sourceLayerEnd: 2, stagePlanSHA256: hash("3"), constructionConfigurationSHA256: hash("4"))])],
+ arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", arithmeticPolicySHA256: hash("5"),
+ supportedGenerationModes: [.pipeline, .tensorParallel])
+ let capHash = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(cap))
+ let pair = ClusterPairDescription(schema: ClusterPairDescription.schemaName, clusterID: "fixture-cluster",
+ publicModelID: "fixture-model", capabilitySHA256: capHash, chunkTokens: 128, requestTimeoutSeconds: 315,
+ coordinatorPort: 5577, members: ["a", "b"].enumerated().map { index, id in
+ .init(id: id, host: "192.0.2.\(index + 1)", port: 22, user: "fixture",
+ ownerExecutable: "/fixture/darkbloom", workerExecutable: "/fixture/worker", modelDirectory: "/fixture/model",
+ runtimeBinarySHA256: hash("a"), jacclDevice: "en7", linkAddress: "192.0.2.\(index + 1)", trust: nil,
+ linkSecretFile: "/fixture/\(id).secret")
+ }, tokenizerFiles: [.init(path: "tokenizer.json", sha256: hash("6"), purpose: .tokenizer)],
+ linkControl: .init(port: 5578, linkEpoch: UUID().uuidString.lowercased(), edgeID: UUID().uuidString.lowercased()))
+ let request = try ClusterPlacementRequestScope(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"),
+ promptTokens: 1024, outputTokens: 128, maximumPromptTokens: 32768, maximumOutputTokens: 32768,
+ maximumContextTokens: 65536, requestChargeEveryRankBytes: gib)
+ return (pair, cap, layout, request)
+ }
+
+ /// One owner's complete quote at `lanes`: 4 GiB a lane beside 1 GiB shared.
+ private func quote(_ request: ClusterPlacementRequestScope, lanes: Int,
+ assistant: ClusterPlacementTensorAssistantQuote? = nil) throws -> ClusterPlacementTensorBatchQuote {
+ let payload = max(512 * 4096, lanes * 248320 * 4)
+ return try .init(request: request, lanes: lanes, chunkTokens: 128, perLaneStateBytes: 4 * gib,
+ sharedBytesExcludingCollectives: gib,
+ allowance: .init(maximumContextTokens: 65536, maximumChunkTokens: 512, requestBytesExcludingCollectives: lanes * 4 * gib + gib,
+ maximumCollectivePayloadBytes: payload, maximumCollectiveFrameBytes: payload + 1024,
+ allocationBound: { (($0 + 16383) / 16384) * 16384 }),
+ assistant: assistant)
+ }
+
+ private func decide(_ home: URL, free: Int, peerFree: Int? = nil, widths: [Int] = ClusterPlacementBatchScope.tensorParallelWidths,
+ assistant: ClusterPlacementTensorAssistantQuote? = nil,
+ row: Row = twentySevenB) throws -> ClusterSetupPlanning.PlacementDecision {
+ let (pair, cap, layout, request) = try fixture(row)
+ return try ClusterPlacementFlow.decide(description: pair, capability: cap, localMemberID: "a",
+ localProfile: profile(free: free), peerProfile: profile(free: peerFree ?? free), layout: layout,
+ tensorAssistantQuote: try quote(request, lanes: 1, assistant: assistant),
+ tensorWidthQuotes: try widths.map { try quote(request, lanes: $0, assistant: assistant) }, leader: "a",
+ link: try #require(ClusterLinkProbeHistory.costs(homeDirectory: home, members: ["a", "b"])),
+ environment: [:], benchDebugBuild: false)
+ }
+
+ /// Both Macs' saved widths: equal, or the test fails.
+ private func savedLanes(_ decision: ClusterSetupPlanning.PlacementDecision, row: Row = twentySevenB) throws -> Int? {
+ let (pair, cap, _, _) = try fixture(row)
+ let setup = try #require(decision.setup)
+ let lanes = try ["a", "b"].map { member in
+ try ClusterConfigurationCodec.decode(try #require(setup.configurations[member]), capability: cap,
+ capabilitySHA256: pair.capabilitySHA256).batchLanes
+ }
+ #expect(lanes[0] == lanes[1], "both Macs save one width")
+ return lanes[0]
+ }
+
+ /// The largest rank need of the placement at one width alone (no wider width offered).
+ private func need(_ home: URL, lanes: Int) throws -> Int {
+ let decided = try decide(home, free: 200 * gib, widths: lanes == 1 ? [] : [lanes])
+ return try #require(decided.result.chosen).ranks.map(\.needBytes).max()!
+ }
+
+ @Test func aPlacementSavesTheWidestWidthBothMacsAdmitNow() throws {
+ let home = try home()
+ let needs = try Dictionary(uniqueKeysWithValues: [1, 2, 4, 6, 8].map { ($0, try need(home, lanes: $0)) })
+ #expect(needs[1]! < needs[2]! && needs[2]! < needs[4]! && needs[4]! < needs[6]! && needs[6]! < needs[8]!)
+ let singleton = try decide(home, free: 200 * gib, widths: [])
+ #expect(try savedLanes(singleton) == nil, "no width quote: the setup saves no width, as before")
+ // Every Mac admits each width's need, and nothing between it and the next wider one.
+ for (free, expected) in [(200 * gib, 8), ((needs[6]! + needs[8]!) / 2, 6), ((needs[4]! + needs[6]!) / 2, 4),
+ ((needs[2]! + needs[4]!) / 2, 2), ((needs[1]! + needs[2]!) / 2, nil)] as [(Int, Int?)] {
+ let decided = try decide(home, free: free)
+ let chosen = try #require(decided.result.chosen)
+ #expect(try savedLanes(decided) == expected, "\(free / gib) GiB free")
+ #expect(chosen.mode == .tensorParallel && DistributedAutomaticBatchPlanner.accepts(chosen, requireNow: true))
+ // The saved width is priced at its own complete quote, within what each Mac admits now.
+ #expect(chosen.ranks.map(\.needBytes).max() == needs[expected ?? 1], "\(free / gib) GiB free")
+ #expect(chosen.ranks.allSatisfy { $0.needBytes <= $0.admissibleNowBytes })
+ // The placement is the singleton's: leader and split unchanged; only the width is added.
+ let alone = try #require(try decide(home, free: free, widths: []).result.chosen)
+ #expect(chosen.ranks.map(\.device) == alone.ranks.map(\.device) && chosen.tensorShares == alone.tensorShares)
+ #expect(decided.lines.contains(" \(expected ?? 0) independent histories, charged at the quoted request bound on both Macs. "
+ + "Stage-rate predictions remain single-request estimates; no batch speed is inferred from the lane count.") == (expected != nil))
+ }
+ // Both Macs must admit it: the smaller Mac decides.
+ #expect(try savedLanes(try decide(home, free: 200 * gib, peerFree: (needs[4]! + needs[6]!) / 2)) == 4)
+ // A width the helper did not quote is not offered.
+ #expect(try savedLanes(try decide(home, free: 200 * gib, widths: [2, 4])) == 4)
+ }
+
+ @Test func anAssistedOwnerIsSizedAtItsOwnQuote() throws {
+ let home = try home()
+ let assistant = try ClusterPlacementTensorAssistantQuote(policy: .init(depth: 3, inventorySHA256: hash("8"),
+ verification: .admittedCohort), residentBytes: gib, loadBytes: 2 * gib, largestAllocationBytes: gib)
+ let decided = try decide(home, free: 200 * gib, assistant: assistant)
+ #expect(try savedLanes(decided) == 8)
+ let (pair, cap, _, _) = try fixture()
+ let saved = try ClusterConfigurationCodec.decode(try #require(decided.setup?.configurations["a"]), capability: cap,
+ capabilitySHA256: pair.capabilitySHA256)
+ #expect(saved.tensorAssistant == assistant.policy)
+ // A width of another assistant (or none) is not this owner's.
+ let (_, _, layout, request) = try fixture()
+ var policy = ClusterPlacementPolicy()
+ try quote(request, lanes: 1, assistant: assistant).applySingleton(to: &policy, layout: layout)
+ #expect(throws: (any Error).self) { try self.quote(request, lanes: 8).applyWidth(to: &policy, layout: layout) }
+ #expect(throws: (any Error).self) { try self.quote(request, lanes: 1, assistant: assistant).applyWidth(to: &policy, layout: layout) }
+ }
+
+ /// A row whose pipeline stays a candidate is sized the same way, and its plan keeps the reason its mode was chosen
+ /// for one request (its comparison with the pipeline); only the chosen placement's memory is the width's.
+ @Test func aRowWhosePipelineStaysACandidateKeepsItsModeReason() throws {
+ let home = try home(), row = Self.nineB
+ let alone = try decide(home, free: 200 * gib, widths: [], row: row)
+ let sized = try decide(home, free: 200 * gib, row: row)
+ #expect(alone.result.chosen?.mode == .tensorParallel && alone.result.modesReason == nil)
+ #expect(try savedLanes(sized, row: row) == 8)
+ let reason = try #require(ClusterPlacementExplanation.deploymentReason(sized.result))
+ #expect(reason == ClusterPlacementExplanation.deploymentReason(alone.result) && !reason.contains("left out"), "\(reason)")
+ #expect(sized.lines.contains(" " + reason))
+ let need = { (decision: ClusterSetupPlanning.PlacementDecision) in decision.result.chosen?.ranks.map(\.needBytes).max() ?? 0 }
+ #expect(need(sized) > need(alone))
+ }
+
+ /// GLM tensor parallel keeps its own default; a pipeline, and a Qwen TP setup saved without a width, keep theirs.
+ @Test func otherFamiliesAndUnsizedSetupsKeepTheirLanes() throws {
+ typealias Plan = DistributedInstalledPlan
+ #expect(Plan.defaultBatchLanes(adapter: .glm5NextLayerStage, mode: .tensorParallel, hasPrivateImages: false) == 8)
+ #expect(Plan.defaultBatchLanes(adapter: .qwen35Dense, mode: .tensorParallel, hasPrivateImages: false,
+ runtimeModelID: "registered_qwen38_27b") == 1)
+ #expect(Plan.defaultBatchLanes(adapter: .qwen35Dense, mode: .pipeline, hasPrivateImages: false) == Plan.defaultBatchLanes)
+ // Only a placement priced by its owner's singleton quote is sized: without one, width quotes change nothing.
+ let home = try home()
+ let (pair, cap, layout, request) = try fixture()
+ let unquoted = try ClusterPlacementFlow.decide(description: pair, capability: cap, localMemberID: "a",
+ localProfile: profile(free: 200 * gib), peerProfile: profile(free: 200 * gib), layout: layout,
+ tensorWidthQuotes: try [8].map { try quote(request, lanes: $0) },
+ leader: "a", link: try #require(ClusterLinkProbeHistory.costs(homeDirectory: home, members: ["a", "b"])),
+ environment: [:], benchDebugBuild: false)
+ #expect(unquoted.result.chosen?.mode == .tensorParallel)
+ #expect(try savedLanes(unquoted) == nil)
+ }
+
+ /// A pair saved for coordinator pairing serves the width its placement saved, on both Macs, from its first start:
+ /// the approval is saved beside it unchanged, no approval or committed-start digest names it (only the setup's own
+ /// bytes do), and the automatic replacement never plans for a setup saved with an approval.
+ @Test func aCoordinatorPairKeepsTheWidthItsSetupSavedThroughApproval() throws {
+ let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider",
+ shape: .qwen27TensorParallel(assistant: nil, lanes: 8))
+ let approval = macs.approval(), facts = try macs.facts()
+ #expect(macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts).changed)
+ let epoch = UUID()
+ for mac in macs.macs {
+ let saved = try macs.saved(mac), configuration = saved.configuration
+ #expect(configuration.nativeMember?.clusterApproval == approval && configuration.batchLanes == 8, "rank \(mac.rank)")
+ let plan = try DistributedInstalledPlan(saved: saved, paths: mac.paths)
+ #expect(plan.batchLanes([:]) == 8 && plan.lanesRetireAlone([:]), "rank \(mac.rank)")
+ #expect(plan.nativeEnvironment(matrix: URL(fileURLWithPath: "/fixture/matrix.json"), ownerEnvironment: [:])[
+ DistributedInstalledPlan.batchLanesSwitch] == "8", "rank \(mac.rank)")
+ // The same setup without the width: every approval and committed-start digest is the same; only the
+ // setup's own bytes (its digest) differ.
+ let bytes = try ClusterConfigurationCodec.encode(configuration, capability: saved.capability,
+ capabilitySHA256: configuration.capabilitySHA256)
+ var object = try JSONSerialization.jsonObject(with: bytes) as! [String: Any]
+ object.removeValue(forKey: "batchLanes")
+ let unsizedBytes = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
+ let unsized = try ClusterConfigurationCodec.decode(unsizedBytes, capability: saved.capability,
+ capabilitySHA256: configuration.capabilitySHA256)
+ let other = try DistributedInstalledPlan(saved: .init(configuration: unsized, capability: saved.capability), paths: mac.paths)
+ #expect(other.batchLanes([:]) == 1)
+ #expect(try DistributedInstalledNativeStart.common(plan: plan, epoch: epoch).canonicalBytes
+ == DistributedInstalledNativeStart.common(plan: other, epoch: epoch).canonicalBytes, "rank \(mac.rank)")
+ #expect(DistributedInstalledNativeStart.runtimeBlock(plan: plan) == DistributedInstalledNativeStart.runtimeBlock(plan: other))
+ #expect(ClusterConfigurationCodec.sha256(bytes) != ClusterConfigurationCodec.sha256(
+ try ClusterConfigurationCodec.encode(unsized, capability: saved.capability, capabilitySHA256: configuration.capabilitySHA256)))
+ }
+ // Queued demand never re-plans an approved setup: the coordinator-approved contract stays as approved.
+ let reference = try ClusterConfigurationStore.installedReference(providerConfiguration: macs.leader.provider)
+ let planner = DistributedAutomaticBatchPlanner(providerConfiguration: macs.leader.provider, paths: macs.leader.paths)
+ let queued = DistributedLocalBatchDemand(generationID: UUID(), waitingRequests: 8, activeRequests: 8, currentCapacity: 8,
+ publicModelID: ClusterApprovalMacs.model, runtimeModelID: macs.capability.runtimeModelID,
+ artifactSHA256: macs.capability.artifactSHA256, configurationSHA256: macs.capability.configurationSHA256,
+ maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumContextTokens: 65536, requestTimeout: .seconds(300))
+ #expect(try planner.snapshot(reference: reference, demand: queued, widths: [8], requireNow: true) == nil)
+ }
+
+ private func demand(capacity: Int, active: Int, waiting: Int, model: String = "registered_qwen38_27b") -> DistributedLocalBatchDemand {
+ .init(generationID: UUID(), waitingRequests: waiting, activeRequests: active, currentCapacity: capacity,
+ publicModelID: "fixture-model", runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"),
+ maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumContextTokens: 65536, requestTimeout: .seconds(315))
+ }
+
+ /// A pair placed at its widest admitted width is never drained for it; one placed narrower still widens past it.
+ @Test func aLocalPairWidensByReplacementOnlyPastItsSavedWidth() {
+ typealias Factory = DistributedAutomaticBatchFactory
+ #expect(Factory.replacementWidths(for: demand(capacity: 8, active: 8, waiting: 8)).isEmpty)
+ #expect(Factory.replacementWidths(for: demand(capacity: 6, active: 6, waiting: 2)) == [8])
+ #expect(Factory.replacementWidths(for: demand(capacity: 4, active: 4, waiting: 4)) == [8, 6])
+ #expect(Factory.replacementWidths(for: demand(capacity: 1, active: 1, waiting: 7)) == [8, 6, 4, 2])
+ #expect(Factory.replacementWidths(for: demand(capacity: 4, active: 4, waiting: 0)).isEmpty)
+ // A row without a request-owned TP owner keeps the pipeline's priced widths.
+ #expect(Factory.replacementWidths(for: demand(capacity: 1, active: 1, waiting: 7, model: "fixture_pipeline_model")) == [8, 4, 2])
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift
index d980296751..e9f5785fdf 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift
@@ -905,11 +905,15 @@ final class DistributedAutomaticBatchPlannerTests {
residentBytes: gib, loadBytes: 2 * gib, largestAllocationBytes: gib))
let target = try ClusterPlacementTensorBatchQuote(request: scope.request, lanes: 1, chunkTokens: 128,
perLaneStateBytes: gib, sharedBytesExcludingCollectives: gib, allowance: try allowance(2 * gib))
+ // The planner's stack under `assistantOrTarget` outgrows a test task's thread in a debug build.
func decide(_ quote: ClusterPlacementTensorBatchQuote?) throws -> ClusterSetupPlanning.PlacementDecision {
- try ClusterPlacementFlow.decide(description: pair, capability: cap, localMemberID: "a",
- localProfile: profile(), peerProfile: profile(), layout: layout, tensorAssistantQuote: quote,
- leader: "a", link: ClusterLinkProbeHistory.costs(homeDirectory: home, members: ["a", "b"])!,
- environment: [:], benchDebugBuild: false)
+ let local = try profile(), peer = try profile()
+ let link = ClusterLinkProbeHistory.costs(homeDirectory: home, members: ["a", "b"])!
+ return try onLargeStack {
+ Result { try ClusterPlacementFlow.decide(description: pair, capability: cap, localMemberID: "a",
+ localProfile: local, peerProfile: peer, layout: layout, tensorAssistantQuote: quote,
+ leader: "a", link: link, environment: [:], benchDebugBuild: false) }
+ }.get()
}
#expect(try decide(assistant).result.chosen == nil)
let discovered = try ClusterSetupPlanning.assistantOrTarget(assistant, fallback: target, decide)
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift
new file mode 100644
index 0000000000..4de08f43a6
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift
@@ -0,0 +1,192 @@
+import Foundation
+import MLXLMCommon
+import Testing
+@testable import ProviderCore
+
+/// Production, 2026-11-01: retiring a pair slot (`EngineV2Bridge.shutdown`)
+/// cancelled a request's stream consumer while the engine queue published the
+/// pair's peer loss to that consumer. Cancellation runs its handlers holding
+/// the task's status lock; the stream's termination waited for the engine
+/// queue, and the queue waited for that lock to resume the consumer. Every
+/// wait here is bounded and polled, so a regression fails instead of hanging.
+/// Fabricated owner only: no model, GPU or peer process.
+@Suite(.timeLimit(.minutes(1)))
+struct DistributedCBv2CancellationDeadlockTests {
+ @Test func cancellingAConsumerWhileItsPeerLossIsPublishedCannotDeadlock() async throws {
+ let owner = HeldReadinessOwner()
+ let engine = try DistributedCBv2Engine(owner: owner, expectedIdentity: owner.base.identity,
+ profile: distributedTestProfile(), detokenizers: DistributedTestDetokenizers())
+ let stream = try engine.submit(distributedTestRequest(maxTokens: 8))
+ let lease = owner.base.last
+ let probe = DeadlockProbe()
+ // The consumer (the bridge's pump) takes a token, then waits in the stream.
+ let consumer = Task {
+ var events = stream.makeAsyncIterator()
+ _ = await events.next()
+ probe.mark("first token")
+ while await events.next() != nil {}
+ probe.mark("consumer ended")
+ }
+ #expect(lease.send(.token(4)))
+ #expect(await probe.wait("first token", seconds: 5))
+ try await Task.sleep(for: .milliseconds(200))
+
+ // The next token holds the engine queue in its readiness check, which
+ // then reports the peer lost: a failure published to the consumer.
+ let release = owner.holdNextReadiness(probe)
+ DispatchQueue.global().async { _ = lease.send(.token(5)); probe.mark("token returned") }
+ #expect(await probe.wait("queue held", seconds: 5))
+ // Meanwhile the owner invalidates and the slot's retirement cancels the consumer.
+ DispatchQueue.global().async { owner.base.losePeer(); probe.mark("invalidation returned") }
+ DispatchQueue.global().async { consumer.cancel(); probe.mark("cancel returned") }
+ _ = await probe.wait("cancel returned", seconds: 1)
+ release.signal()
+
+ var ended = true
+ for mark in ["cancel returned", "token returned", "invalidation returned", "consumer ended"] {
+ let reached = await probe.wait(mark, seconds: 5)
+ #expect(reached, "\(mark): the consumer's cancellation and the engine queue deadlocked")
+ ended = ended && reached
+ }
+ // A deadlocked engine is left as it is: its queue would hang the suite.
+ guard ended else { return }
+ #expect(lease.cancelCount == 1) // the peer loss took the failure path, once
+ lease.acknowledge()
+ await engine.shutdown()
+ #expect(lease.releaseCount == 1)
+ #expect(owner.base.shutdownCount == 1)
+ }
+
+ /// The same lock order through the admission cancellation: a submission
+ /// that waits for its refused reservation's retirement is cancelled while
+ /// the engine queue retires it and resumes that submission.
+ @Test func cancellingASubmissionWhileItsRetirementResumesItCannotDeadlock() async throws {
+ let owner = HeldReadinessOwner()
+ let clock = DistributedTestClock()
+ let engine = try DistributedCBv2Engine(owner: owner, expectedIdentity: owner.base.identity,
+ profile: distributedTestProfile(), detokenizers: DistributedTestDetokenizers(), clock: clock.clock)
+ owner.base.onReserve = { clock.advance(.seconds(5)) } // refused after reserve: the deadline passed
+ let probe = DeadlockProbe()
+ let submission = Task {
+ _ = try? await engine.submit(distributedTestRequest(),
+ firstTokenDeadline: distributedTestDeadline(clock.now.advanced(by: .seconds(3))))
+ probe.mark("submission ended")
+ }
+ let end = ContinuousClock.now.advanced(by: .seconds(5))
+ while (owner.base.reserveCount == 0 || owner.base.last.cancelCount == 0) && ContinuousClock.now < end {
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ let lease = owner.base.last
+ #expect(lease.cancelCount == 1)
+ try await Task.sleep(for: .milliseconds(200)) // the submission now waits for the retirement
+
+ // The retirement holds the engine queue while it releases the
+ // reservation, then resumes the submission; the caller cancels meanwhile.
+ let release = owner.holdNextRelease(probe)
+ lease.acknowledge()
+ #expect(await probe.wait("queue held", seconds: 5))
+ DispatchQueue.global().async { submission.cancel(); probe.mark("cancel returned") }
+ _ = await probe.wait("cancel returned", seconds: 1)
+ release.signal()
+
+ var ended = true
+ for mark in ["cancel returned", "submission ended"] {
+ let reached = await probe.wait(mark, seconds: 5)
+ #expect(reached, "\(mark): the submission's cancellation and the engine queue deadlocked")
+ ended = ended && reached
+ }
+ guard ended else { return }
+ #expect(lease.releaseCount == 1)
+ #expect(lease.startCount == 0)
+ await engine.shutdown()
+ #expect(owner.base.shutdownCount == 1)
+ }
+}
+
+/// Marks set from any thread, awaited by polling: no cooperative thread ever
+/// waits on a queue that may be deadlocked.
+private final class DeadlockProbe: @unchecked Sendable {
+ private let lock = NSLock()
+ private var marks = Set()
+
+ func mark(_ name: String) { _ = lock.withLock { marks.insert(name) } }
+
+ func wait(_ name: String, seconds: Double) async -> Bool {
+ let end = ContinuousClock.now.advanced(by: .milliseconds(Int(seconds * 1000)))
+ while !lock.withLock({ marks.contains(name) }) && ContinuousClock.now < end {
+ try? await Task.sleep(for: .milliseconds(5))
+ }
+ return lock.withLock { marks.contains(name) }
+ }
+}
+
+/// One held step: it marks the probe, then waits (bounded) for the test.
+private final class HeldStep: @unchecked Sendable {
+ private let lock = NSLock()
+ private var next: (probe: DeadlockProbe, release: DispatchSemaphore)?
+
+ func arm(_ probe: DeadlockProbe) -> DispatchSemaphore {
+ let release = DispatchSemaphore(value: 0)
+ lock.withLock { next = (probe, release) }
+ return release
+ }
+
+ /// True when this call was the held one.
+ func pass() -> Bool {
+ let held = lock.withLock { () -> (probe: DeadlockProbe, release: DispatchSemaphore)? in
+ defer { next = nil }
+ return next
+ }
+ guard let held else { return false }
+ held.probe.mark("queue held")
+ _ = held.release.wait(timeout: .now() + 30)
+ return true
+ }
+}
+
+/// The fabricated owner with one step held where the engine calls it on its
+/// queue: a readiness check (`readyCapacity`), which then reports the peer
+/// lost, or a reservation's release (`retire`).
+private final class HeldReadinessOwner: DistributedResidentExecutionOwner, @unchecked Sendable {
+ let base = DistributedTestOwner()
+ private let readinessStep = HeldStep()
+ private let releaseStep = HeldStep()
+
+ func holdNextReadiness(_ probe: DeadlockProbe) -> DispatchSemaphore { readinessStep.arm(probe) }
+ func holdNextRelease(_ probe: DeadlockProbe) -> DispatchSemaphore { releaseStep.arm(probe) }
+
+ func readiness() -> DistributedResidentReadiness? {
+ if readinessStep.pass() { base.losePeer(notify: false) }
+ return base.readiness()
+ }
+ func setReadinessInvalidationHandler(_ handler: @escaping @Sendable () -> Void) {
+ base.setReadinessInvalidationHandler(handler)
+ }
+ func projectFirstToken(_ request: CBv2Request, admission: CBv2FirstTokenDeadlineAdmission) -> CBv2FirstTokenProjectedWork {
+ base.projectFirstToken(request, admission: admission)
+ }
+ func reserve(_ request: CBv2Request, identity: DistributedResidentIdentity,
+ profileID: String, capacityLimit: Int) throws -> any DistributedResidentRequestLease {
+ HeldReleaseLease(try base.reserve(request, identity: identity, profileID: profileID,
+ capacityLimit: capacityLimit), release: releaseStep)
+ }
+ func shutdown() async { await base.shutdown() }
+}
+
+/// The fabricated lease, its release held when the owner armed it.
+private final class HeldReleaseLease: DistributedResidentRequestLease, @unchecked Sendable {
+ private let inner: any DistributedResidentRequestLease
+ private let release: HeldStep
+
+ init(_ inner: any DistributedResidentRequestLease, release: HeldStep) { self.inner = inner; self.release = release }
+
+ var identity: DistributedResidentIdentity { inner.identity }
+ var requestID: CBv2RequestID { inner.requestID }
+ var reservedBytes: Int { inner.reservedBytes }
+ var bytesInUse: Int { inner.bytesInUse }
+ func start(emit: @escaping @Sendable (DistributedResidentEvent) -> Bool) throws { try inner.start(emit: emit) }
+ func cancel() { inner.cancel() }
+ func requestCleanStop() -> Bool { inner.requestCleanStop() }
+ func waitUntilRetired() async { await inner.waitUntilRetired() }
+ func releaseResources() { _ = release.pass(); inner.releaseResources() }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift
index ee222dadbe..cb29c6e22c 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift
@@ -200,6 +200,7 @@ struct DistributedCBv2DeadlineTests {
_ = await distributedCollect(first)
let second = try engine.submit(distributedTestRequest(maxTokens: 1))
oldTermination?(.cancelled)
+ engine.onQueue {} // the termination reaches the queue without waiting for it
#expect(owner.last.cancelCount == 0)
owner.last.send(.token(5))
owner.last.acknowledge()
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift
index c3444e20ef..e6710ecbe7 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift
@@ -392,6 +392,7 @@ struct DistributedCBv2EngineTests {
let consumer = Task { await distributedCollect(stream) }
consumer.cancel()
_ = await consumer.value
+ engine.onQueue {} // the stream's termination reaches the queue without waiting for it
#expect(owner.last.cancelCount == 1)
#expect(owner.last.releaseCount == 0)
#expect(engine.capacity().activeRequests == 1)
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift
index db85eb8163..1ae33e2183 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift
@@ -33,6 +33,32 @@ struct DistributedInstalledLanesTests {
}
}
+ @Test func gemmaSerialPipelineServesFourLanesAndLookaheadKeepsOne() {
+ #expect(Plan.gemma4PipelineBatchLanes == 4)
+ #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false,
+ prefillSchedule: .serial) == 4)
+ // Lanes prefill serially: a saved lookahead keeps its schedule and one lane.
+ #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false,
+ prefillSchedule: .oneChunkLookahead) == Plan.defaultBatchLanes)
+ #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false) == Plan.defaultBatchLanes)
+ #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: true,
+ prefillSchedule: .serial) == nil)
+ for mode in ClusterGenerationMode.allCases where mode != .pipeline {
+ #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: mode, hasPrivateImages: false,
+ prefillSchedule: .serial) == nil)
+ }
+ // Every other lane adapter keeps its singleton default under either schedule.
+ for adapter in Plan.laneAdapters where adapter != .gemma4LayerStage {
+ for schedule in ClusterPrefillSchedule.allCases {
+ #expect(Plan.defaultBatchLanes(adapter: adapter, mode: .pipeline, hasPrivateImages: false,
+ prefillSchedule: schedule) == Plan.defaultBatchLanes)
+ }
+ }
+ // A cancelled Gemma lane retires alone, as every pipeline lane adapter's does.
+ #expect(Plan.lanesRetireAlone(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false,
+ lanes: Plan.gemma4PipelineBatchLanes))
+ }
+
@Test func otherModesAndFamiliesKeepTheirLanes() {
// GLM's pipeline still serves one request at a time.
#expect(Plan.defaultBatchLanes(adapter: .glm5NextLayerStage, mode: .pipeline, hasPrivateImages: false) == nil)
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift
index 4f228ab41f..8ded8dd4fa 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift
@@ -143,6 +143,8 @@ private struct StubTokenizer: MLXLMCommon.Tokenizer {
var tokenTable: [String: Int] = ["": 2, "<|eot|>": 7]
var eosTokenString: String? = ""
var failTemplate = false
+ /// Text for chosen ids; every other id decodes as "t".
+ var decodeTable: [Int: String] = [:]
func encode(text: String, addSpecialTokens: Bool) -> [Int] {
Array(repeating: 0, count: text.count)
@@ -150,7 +152,7 @@ private struct StubTokenizer: MLXLMCommon.Tokenizer {
/// Deterministic per-id text ("t") so logprob-entry conversion
/// (token string + UTF-8 bytes) is assertable.
func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String {
- tokenIds.map { "t\($0)" }.joined()
+ tokenIds.map { decodeTable[$0] ?? "t\($0)" }.joined()
}
func convertTokenToId(_ token: String) -> Int? { tokenTable[token] }
func convertIdToToken(_ id: Int) -> String? { nil }
@@ -438,6 +440,7 @@ private func makeBridge(
modelId: String = "gemma-4-27b-it",
eosTokenIds: Set = [2],
extraEOSTokens: [String] = [],
+ stopStringScope: CBv2StopStringScope? = nil,
defaultMaxTokens: Int = 4096,
kvBytesPerToken: Int = 0,
fixedRequestBytes: Int = 0,
@@ -456,6 +459,7 @@ private func makeBridge(
tokenizer: TokenizerHandle(tokenizer),
eosTokenIds: eosTokenIds,
extraEOSTokens: extraEOSTokens,
+ stopStringScope: stopStringScope,
defaultMaxTokens: defaultMaxTokens,
maxConcurrentRequests: 4,
kvBytesPerToken: kvBytesPerToken,
@@ -840,6 +844,59 @@ struct EngineV2MatchedStopSequenceTests {
#expect(unscoped.stopStringScope == nil)
}
+ @Test("a scoped report names the stop that matched, not one that only starts there")
+ func scopedReportNamesTheMatchingCandidate() {
+ let inside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true)
+ #expect(EngineV2Bridge.matchedStopSequence(
+ candidates: ["\n", "\nUser:"], generatedText: "r\n\nUser: hi", scope: inside
+ ) == "\nUser:", "a bare newline before the answer does not stop it")
+ let outside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil, parsesToolCalls: true)
+ #expect(EngineV2Bridge.matchedStopSequence(
+ candidates: ["Ar", scope: outside
+ ) == "A", "a stop never matches into a span")
+ }
+
+ @Test("a request's stop scope reaches the engine and the reported sequence")
+ func requestScopeReachesEngineAndReport() async {
+ // Gemma 4 with reasoning on: a period in the thought, "!" in the answer.
+ let tokenizer = StubTokenizer(decodeTable: [
+ 20: "<|channel>", 21: "thought\nIt is A.", 22: "", 23: "A!",
+ ])
+ let engine = ScriptedCBv2Engine(script: .stream([
+ .delta(text: "", tokens: [20, 21, 22, 23], logprobs: nil),
+ .finished(reason: .stop, usage: CBv2Usage(promptTokens: 5, completionTokens: 4)),
+ ]))
+ let bridge = makeBridge(engine: engine, tokenizer: tokenizer)
+ let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true)
+ let signal = EngineV2RequestUsageSignal()
+ _ = await record(await bridge.submitTokenized(
+ promptTokens: [1, 2, 3],
+ request: makeRequest(stop: .multiple([".", "!"])),
+ usageSignal: signal,
+ stopStringScope: scope
+ ))
+ #expect(engine.submitted.first?.stopStringScope == scope)
+ #expect(signal.matchedStopSequence == "!", "the thought's period did not stop it")
+ }
+
+ @Test("a request's scope replaces the model's, which applies otherwise")
+ func modelScopeIsTheDefault() async {
+ let harmony = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b")
+ let think = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true)
+ for (modelScope, requestScope, expected) in [
+ (harmony, nil, harmony), (nil, nil, nil), (harmony, think, think),
+ ] {
+ let engine = ScriptedCBv2Engine(script: .stream([
+ .finished(reason: .stop, usage: CBv2Usage(promptTokens: 5, completionTokens: 0)),
+ ]))
+ let bridge = makeBridge(engine: engine, stopStringScope: modelScope)
+ _ = await record(await bridge.submitTokenized(
+ promptTokens: [1, 2, 3], request: makeRequest(stop: .single(".")),
+ stopStringScope: requestScope))
+ #expect(engine.submitted.first?.stopStringScope == expected)
+ }
+ }
+
@Test("compares Unicode scalars exactly rather than canonically")
func unicodeScalarExactness() {
#expect(EngineV2Bridge.matchedStopSequence(
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift
index 21a81ef6fe..13821848c5 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift
@@ -47,6 +47,28 @@ struct NativeBlockRetirementBridgeTests {
return .committed(tokens: [64 + index], stopToken: nil, finishReason: index == 2 ? .length : nil)
}
}
+ /// Commits one block of output, then stops at the token limit.
+ private final class TextSession: CBv2NativeBlockSession {
+ let tokens: [Int]
+ let cancellation: CBv2NativeBlockCancellation
+ var index = 0, generatedTokenCount = 0
+ var retainedBytes: Int { 64 }
+ var activeTokenCount: Int { 1 + generatedTokenCount }
+ init(tokens: [Int], cancellation: CBv2NativeBlockCancellation) {
+ self.tokens = tokens; self.cancellation = cancellation
+ }
+ func cancel() {}
+ func advanceNative() throws -> CBv2NativeBlockStep {
+ defer { index += 1 }
+ if index == 0 { return .prefill(computedTokens: 1, complete: true) }
+ if cancellation.isCancelled { throw CancellationError() }
+ if index == 1 {
+ generatedTokenCount = tokens.count
+ return .committed(tokens: tokens, stopToken: nil, finishReason: nil)
+ }
+ return .committed(tokens: [], stopToken: nil, finishReason: .length)
+ }
+ }
private struct Result: Sendable { var text = "", error = ""; var cause: InferenceTerminalCause?; var completion = 0 }
private func collect(_ stream: AsyncStream) async -> Result {
var result = Result()
@@ -67,6 +89,33 @@ struct NativeBlockRetirementBridgeTests {
try #require(await predicate())
}
+ /// The native block decoder matches stops over the whole output, so a
+ /// request's reasoning scope is not sent there and the reported stop is
+ /// the one that matched.
+ @Test func nativeBlockRequestsCarryNoStopScope() async throws {
+ let tokenizer = Tokens()
+ let output = Array("<|channel>thought\nIt is A.Yes!".utf8).map(Int.init)
+ let engine = try CBv2NativeBlockEngine(tokenizer: tokenizer, kvBytesCapacity: 300,
+ shutdownGraceSeconds: 0, loopConfig: .init(stepTimeout: 60, watchdogInterval: 0.01),
+ reservationForRequest: { _ in 100 }, makeSession: { _, cancellation in
+ TextSession(tokens: output, cancellation: cancellation)
+ })
+ let budget = GlobalKVCacheBudget(capFraction: 1, activationReserveBytes: 0) {
+ .init(total: 8 << 30, active: 0, cache: 0, systemAvailable: 1_000)
+ }
+ let bridge = EngineV2Bridge(engine: engine, modelId: "native-fixture", tokenizer: TokenizerHandle(tokenizer),
+ eosTokenIds: [], defaultMaxTokens: 64, kvBytesPerToken: 1, kvBudget: budget)
+ let request = ChatCompletionRequest(model: "native-fixture", messages: [], temperature: 1, max_tokens: 64,
+ stop: .multiple([".", "!"]))
+ let signal = EngineV2RequestUsageSignal()
+ let result = await collect(await bridge.submitTokenized(promptTokens: [1], request: request,
+ requestId: "scoped", cacheEnabled: false, usageSignal: signal,
+ stopStringScope: ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true)))
+ #expect(result.text == "<|channel>thought\nIt is A" && result.error.isEmpty)
+ #expect(signal.matchedStopSequence == ".")
+ await bridge.shutdown()
+ }
+
@Test func watchdogReturnsTypedErrorWithoutRefundingBlockedNativeMemory() async throws {
try await exercise(cancelConsumer: false)
}
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift
new file mode 100644
index 0000000000..e420784478
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift
@@ -0,0 +1,170 @@
+// Copyright Β© 2026 Eigen Labs.
+
+import Foundation
+import MLXLMCommon
+import Testing
+
+@testable import ProviderCore
+
+/// A character outside the vocabulary is written as `<0xHH>` tokens. Client text must carry it
+/// wherever it falls: swift-transformers' `ByteFallbackDecoder` drops a trailing run, so Gemma 4
+/// lost a reply's last emoji, and a restart inside a run corrupted a long reply.
+@Suite("Local tokenizer byte fallback")
+struct LocalTokenizerByteFallbackTests {
+ private static let texts = [
+ "all zipped up π", "π", "ends κ°", "aπbπ", "ππ", "mixed δΈ and β then π©΅", "plain ascii",
+ ]
+ private static let promptCacheEnvironments: [[String: String]] = [[:], ["DARKBLOOM_TTFT_PROMPT_CACHE": "0"]]
+
+ /// A character-level tokenizer with Gemma 4's decoder sequence: ASCII has its own tokens and
+ /// everything else is byte tokens.
+ private func tokenizerDirectory(
+ decoder: [String: Any]? = nil, byteTokens: ClosedRange? = 0...255, literal: [String] = []
+ ) throws -> URL {
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("byte-fallback-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)
+ var vocabulary: [String: Int] = ["": 0, "": 1]
+ for value in 32...126 { vocabulary[String(UnicodeScalar(value)!)] = vocabulary.count }
+ if let byteTokens {
+ for value in byteTokens { vocabulary[String(format: "<0x%02X>", value)] = vocabulary.count }
+ }
+ for token in literal { vocabulary[token] = vocabulary.count }
+ let sequence: [String: Any] = [
+ "type": "Sequence",
+ "decoders": [
+ ["type": "Replace", "pattern": ["String": "β"], "content": " "] as [String: Any],
+ ["type": "ByteFallback"], ["type": "Fuse"],
+ ],
+ ]
+ let config: [String: Any] = [
+ "tokenizer_class": "GemmaTokenizer", "processor_class": "Gemma4Processor", "unk_token": "",
+ "clean_up_tokenization_spaces": false,
+ ]
+ let data: [String: Any] = [
+ "model": ["type": "BPE", "vocab": vocabulary, "merges": [String](), "unk_token": ""],
+ "added_tokens": [["id": 1, "content": "", "special": true] as [String: Any]],
+ "decoder": decoder ?? sequence,
+ ]
+ try JSONSerialization.data(withJSONObject: config).write(
+ to: directory.appendingPathComponent("tokenizer_config.json"))
+ try JSONSerialization.data(withJSONObject: data).write(to: directory.appendingPathComponent("tokenizer.json"))
+ return directory
+ }
+
+ /// The IDs the model generates for `text`, without going through the encoder.
+ private func ids(_ text: String, _ tokenizer: any MLXLMCommon.Tokenizer) throws -> [Int] {
+ var ids: [Int] = []
+ for scalar in text.unicodeScalars {
+ if scalar.isASCII {
+ ids.append(try #require(tokenizer.convertTokenToId(String(scalar))))
+ } else {
+ for byte in String(scalar).utf8 {
+ ids.append(try #require(tokenizer.convertTokenToId(String(format: "<0x%02X>", byte))))
+ }
+ }
+ }
+ return ids
+ }
+
+ private func streamed(_ ids: [Int], _ tokenizer: any MLXLMCommon.Tokenizer) -> String {
+ let detokenizer = DetokenizerV2(tokenizer: tokenizer)
+ var text = ""
+ for id in ids { text += detokenizer.append(id) }
+ return text + detokenizer.flush()
+ }
+
+ @Test("a decode keeps a trailing run", arguments: promptCacheEnvironments)
+ func decodeKeepsTrailingRun(environment: [String: String]) async throws {
+ let directory = try tokenizerDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let tokenizer = try await LocalTokenizerLoader(environment: environment).load(from: directory)
+ for text in Self.texts {
+ let tokens = try ids(text, tokenizer)
+ #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == text)
+ #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: true) == text)
+ }
+ }
+
+ @Test("a stream carries every character once", arguments: promptCacheEnvironments)
+ func streamCarriesEveryCharacter(environment: [String: String]) async throws {
+ let directory = try tokenizerDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let tokenizer = try await LocalTokenizerLoader(environment: environment).load(from: directory)
+ for text in Self.texts {
+ #expect(streamed(try ids(text, tokenizer), tokenizer) == text)
+ }
+ }
+
+ @Test("a reply of byte tokens alone keeps all of them")
+ func allByteReply() async throws {
+ let directory = try tokenizerDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let tokenizer = try await LocalTokenizerLoader().load(from: directory)
+ // Longer than any bound a walk might take, and a control character written as a byte.
+ let text = String(repeating: "κ°πδΈ", count: 100) + "\r"
+ let tokens = try text.unicodeScalars.flatMap { scalar in
+ try String(scalar).utf8.map { byte in
+ try #require(tokenizer.convertTokenToId(String(format: "<0x%02X>", byte)))
+ }
+ }
+ #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == text)
+ #expect(streamed(tokens, tokenizer) == text)
+ }
+
+ @Test("a segment restart does not land inside a run")
+ func restartInsideARun() async throws {
+ let directory = try tokenizerDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let tokenizer = try await LocalTokenizerLoader().load(from: directory)
+ // The segment's soft cap is 256 tokens: put the four bytes on every side of it, twice.
+ for padding in 248...258 {
+ let text = String(repeating: "a", count: padding) + "π" + String(repeating: "b", count: padding) + "π end"
+ #expect(streamed(try ids(text, tokenizer), tokenizer) == text)
+ }
+ }
+
+ @Test("a trailing special token does not hide a run")
+ func trailingSpecialToken() async throws {
+ let directory = try tokenizerDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let tokenizer = try await LocalTokenizerLoader().load(from: directory)
+ let eos = try #require(tokenizer.convertTokenToId(""))
+ let tokens = try ids("zipped π", tokenizer) + [eos]
+ #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: true) == "zipped π")
+ #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == "zipped π")
+ }
+
+ @Test("a run cut mid-character ends in one replacement character")
+ func cutMidCharacter() async throws {
+ let directory = try tokenizerDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let tokenizer = try await LocalTokenizerLoader().load(from: directory)
+ let tokens = Array(try ids("abπ", tokenizer).dropLast(2))
+ #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == "ab\u{FFFD}")
+ #expect(streamed(tokens, tokenizer) == "ab\u{FFFD}")
+ }
+
+ @Test("another decoder keeps its spelling of a literal byte token")
+ func otherDecoderKeepsSpelling() async throws {
+ let directory = try tokenizerDirectory(decoder: ["type": "Fuse"], byteTokens: nil, literal: ["<0x41>"])
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let tokenizer = try await LocalTokenizerLoader().load(from: directory)
+ let literal = try #require(tokenizer.convertTokenToId("<0x41>"))
+ #expect(tokenizer.decode(tokenIds: [literal], skipSpecialTokens: false) == "<0x41>")
+ #expect(tokenizer.decode(tokenIds: try ids("a", tokenizer) + [literal], skipSpecialTokens: false) == "a<0x41>")
+ }
+
+ @Test("the unknown token is not read as a byte")
+ func unknownTokenIsNotAByte() async throws {
+ // Only some byte tokens exist, so the others convert to the unknown ID.
+ let directory = try tokenizerDirectory(byteTokens: 0xF0...0xFF)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ // The probe reads whichever byte token a dictionary lists first, so load it more than once.
+ for _ in 0..<40 {
+ let tokenizer = try await LocalTokenizerLoader().load(from: directory)
+ let unknown = try #require(tokenizer.convertTokenToId(""))
+ #expect(tokenizer.decode(tokenIds: try ids("a", tokenizer) + [unknown], skipSpecialTokens: false) == "a")
+ }
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift
new file mode 100644
index 0000000000..119192c41a
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift
@@ -0,0 +1,112 @@
+// Copyright Β© 2026 Eigen Labs.
+
+import Foundation
+import MLXLMCommon
+import MLXLMServer
+import Testing
+
+@testable import ProviderCore
+
+@Suite("Reasoning stop scope")
+struct ReasoningStopScopeTests {
+ private func run(_ output: String, stops: [String], scope: CBv2StopStringScope?) -> String {
+ let holdback = StopHoldback(stopStrings: stops, scope: scope)
+ let scan = holdback.ingest(output)
+ return scan.stopped ? scan.text : scan.text + holdback.flush()
+ }
+
+ @Test("think parsers exclude reasoning and tool calls from where the prompt left off")
+ func thinkParsers() {
+ for parser in [ReasoningParserFormat.qwen3, .deepseekR1] {
+ #expect(
+ ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "", parsesToolCalls: true)
+ == CBv2StopStringScope(
+ excluding: [ReasoningStopScope.think, ReasoningStopScope.thinkToolCall],
+ startingInside: true))
+ for prefix in ["", nil] {
+ #expect(
+ ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: prefix, parsesToolCalls: true)
+ == CBv2StopStringScope(
+ excluding: [ReasoningStopScope.think, ReasoningStopScope.thinkToolCall]))
+ }
+ }
+ }
+
+ @Test("Gemma 4 excludes its thought channel and tool calls")
+ func gemma() {
+ #expect(
+ ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true)
+ == CBv2StopStringScope(excluding: [
+ .init(opener: "<|channel>", closers: [""]),
+ .init(opener: "<|tool_call>", closers: [""]),
+ ]))
+ }
+
+ @Test("without declared tools a literal tool tag in an answer is text, so stops still apply")
+ func toolTagsWithoutTools() {
+ let qwen = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil, parsesToolCalls: false)
+ #expect(qwen == CBv2StopStringScope(excluding: [ReasoningStopScope.think]))
+ #expect(
+ run("Use the tag. Close it. Done.", stops: ["."], scope: qwen)
+ == "Use the tag")
+ let gemma = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: false)
+ #expect(gemma == CBv2StopStringScope(excluding: [ReasoningStopScope.gemmaThought]))
+ #expect(
+ run("Use the <|tool_call> tag. Close it. Done.", stops: ["."], scope: gemma)
+ == "Use the <|tool_call> tag")
+ // Reasoning still never matches, with or without tools.
+ #expect(
+ run("One. Two.Three. Four.", stops: ["."], scope: qwen)
+ == "One. Two.Three")
+ }
+
+ @Test("with declared tools a stop never cuts a tool frame")
+ func toolTagsWithTools() {
+ let qwen = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil, parsesToolCalls: true)
+ #expect(
+ run("{\"a\": \"b.c\"}Done. More.", stops: ["."], scope: qwen)
+ == "{\"a\": \"b.c\"}Done")
+ }
+
+ @Test("Harmony keeps the model's scope; no parser keeps whole-output matching")
+ func otherParsers() {
+ for parser in [ReasoningParserFormat.harmony, ReasoningParserFormat.none, nil] {
+ for parsesToolCalls in [true, false] {
+ #expect(
+ ReasoningStopScope.scope(
+ reasoningParser: parser, reasoningPrefix: "", parsesToolCalls: parsesToolCalls) == nil)
+ }
+ }
+ }
+
+ @Test("a stop in a Qwen thinking prompt's reasoning no longer ends the request")
+ func qwenThinking() {
+ // The template prefilled "\n"; the model writes "\n\n" after "".
+ let output =
+ "Capital of Australia. Canberra.\n\nKeep it short.\n\n\n"
+ + "The capital of Australia is Canberra.\n\nIt is in the ACT."
+ let scope = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true)
+ #expect(run(output, stops: ["."], scope: nil) == "Capital of Australia")
+ #expect(
+ run(output, stops: ["."], scope: scope)
+ == "Capital of Australia. Canberra.\n\nKeep it short.\n\n\n"
+ + "The capital of Australia is Canberra")
+ #expect(
+ run(output, stops: ["\n\n"], scope: scope)
+ == "Capital of Australia. Canberra.\n\nKeep it short.\n\n\n"
+ + "The capital of Australia is Canberra.")
+ }
+
+ @Test("a stop in a Gemma 4 thought no longer ends the request")
+ func gemmaThinking() {
+ let output =
+ "<|channel>thought\nCapital of Australia. Canberra.\n\nKeep it short."
+ + "The capital of Australia is Canberra.\n\nIt is in the ACT."
+ let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true)
+ #expect(run(output, stops: ["."], scope: nil) == "<|channel>thought\nCapital of Australia")
+ #expect(
+ run(output, stops: ["\n\n"], scope: scope)
+ == "<|channel>thought\nCapital of Australia. Canberra.\n\nKeep it short."
+ + "The capital of Australia is Canberra.")
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairServingTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairServingTests.swift
index a20170de2f..f24dcdbf78 100644
--- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairServingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairServingTests.swift
@@ -38,13 +38,17 @@ final class InertWorkerEndpoint: ClusterWorkerEndpoint, @unchecked Sendable {
final class ScriptedPairBuilder: @unchecked Sendable {
private let lock = NSLock()
private var owners: [ScriptedPairOwner] = []
+ private var makes = 0
var hold: DispatchSemaphore?
/// Set on each built owner: its requests wait for one signal each.
var ownerHold: DispatchSemaphore?
var failure: Error?
var built: [ScriptedPairOwner] { lock.withLock { owners } }
+ /// Builds begun, including one still held.
+ var begun: Int { lock.withLock { makes } }
func make(_ start: NativePairMemberServingStart) throws -> any DistributedResidentExecutionOwner {
+ let hold = lock.withLock { () -> DispatchSemaphore? in makes += 1; return self.hold }
hold?.wait()
if let failure { throw failure }
let wire = start.identity
@@ -219,6 +223,77 @@ struct ClusterPairServingTests {
await fixture.loop.stopServingCommittedStart(epoch: next.membershipEpoch)
}
+ /// Production, 2026-11-01: after a peer loss the session's stop did not
+ /// complete within the session's own bounded wait; the session sent its
+ /// receipt anyway, and every later committed start was refused with "a
+ /// committed start is already served" until a restart. The session's stop
+ /// releases the start at once; the stale serve stands down by itself.
+ @Test func aStartWhoseServeCannotFinishDoesNotOutliveItsSession() async throws {
+ let fixture = try await ServingFixture.make()
+ try await fixture.loop.installClusterPairServing(fixture.context())
+ let hold = DispatchSemaphore(value: 0)
+ defer { hold.signal() }
+ fixture.builder.hold = hold
+ let first = try fixture.start()
+ let stale = Task { try await fixture.loop.serveCommittedStart(first) }
+ #expect(await clusterPairWait { fixture.builder.begun == 1 })
+ await fixture.loop.stopServingCommittedStart(epoch: first.membershipEpoch)
+ #expect(await fixture.loop.clusterPairServingSnapshot.epoch == nil)
+
+ // The coordinator's next committed start is served while the stale serve is still out.
+ fixture.builder.hold = nil
+ let next = try fixture.start(epoch: UUID())
+ try await fixture.loop.serveCommittedStart(next)
+ #expect(await fixture.loop.clusterPairServingSnapshot.slotEpoch == next.membershipEpoch)
+
+ // The stale serve comes back: it shuts its pair down and touches nothing of the next start.
+ hold.signal()
+ await #expect(throws: ClusterPairSlotError.self) { try await stale.value }
+ let snapshot = await fixture.loop.clusterPairServingSnapshot
+ #expect(snapshot.epoch == next.membershipEpoch && snapshot.slotEpoch == next.membershipEpoch && !snapshot.refusing)
+ let staleOwner = fixture.builder.built.first { $0.identity.membershipEpoch == first.membershipEpoch }
+ #expect(staleOwner?.shutdownCount == 1)
+ await fixture.loop.stopServingCommittedStart(epoch: next.membershipEpoch)
+ #expect(await fixture.loop.clusterPairServingSnapshot.epoch == nil)
+ }
+
+ /// The slot's drain (a request in flight) outlasts the session's wait: the
+ /// start is already released while the stop still waits for the drain.
+ @Test func theStartIsReleasedBeforeTheSlotsDrainEnds() async throws {
+ let fixture = try await ServingFixture.make()
+ try await fixture.loop.installClusterPairServing(fixture.context())
+ await fixture.loop.setClusterPairWarmupForTesting(timeoutSeconds: 30)
+ let hold = DispatchSemaphore(value: 0)
+ defer { hold.signal() }
+ fixture.builder.ownerHold = hold
+ let start = try fixture.start()
+ let serve = Task { try await fixture.loop.serveCommittedStart(start) }
+ #expect(await clusterPairWait { fixture.builder.built.first?.reserveCount == 1 })
+ let stop = Task { await fixture.loop.stopServingCommittedStart(epoch: start.membershipEpoch) }
+ #expect(await clusterPairWait { await fixture.loop.clusterPairServingSnapshot.epoch == nil })
+ #expect(fixture.builder.built.first?.shutdownCount == 0) // still draining
+ hold.signal()
+ await stop.value
+ try await serve.value
+ #expect(await fixture.loop.clusterPairSlotSnapshot.slots.isEmpty)
+ #expect(fixture.builder.built.first?.shutdownCount == 1)
+ }
+
+ /// The session's stop reached the host before its serve did: that start is never served.
+ @Test func aStartWhoseSessionAlreadyStoppedIsNeverServed() async throws {
+ let fixture = try await ServingFixture.make()
+ try await fixture.loop.installClusterPairServing(fixture.context())
+ let start = try fixture.start()
+ await fixture.loop.stopServingCommittedStart(epoch: start.membershipEpoch)
+ await #expect(throws: ClusterPairSlotError.self) { try await fixture.loop.serveCommittedStart(start) }
+ let snapshot = await fixture.loop.clusterPairServingSnapshot
+ #expect(snapshot.epoch == nil && snapshot.slotEpoch == nil && fixture.builder.built.isEmpty)
+ let next = try fixture.start(epoch: UUID())
+ try await fixture.loop.serveCommittedStart(next)
+ #expect(await fixture.loop.clusterPairServingSnapshot.slotEpoch == next.membershipEpoch)
+ await fixture.loop.stopServingCommittedStart(epoch: next.membershipEpoch)
+ }
+
@Test func onlyTheLeaderWithAContextServesAndAFailedPairLeavesNothing() async throws {
let leader = try await ServingFixture.make()
await #expect(throws: ClusterPairSlotError.self) { try await leader.loop.serveCommittedStart(try leader.start()) }
|