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..
", 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()) }