From 41dd24f49f919c7bbfd768712e519788fc6894ed Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:24:44 -0700 Subject: [PATCH 01/58] GPT-OSS: match client stop sequences in the Harmony final message only The engine matched `stop` against every generated character, including the private Harmony analysis. A sequence that appeared while gpt-oss reasoned ended the request before any answer: finish_reason "stop", reasoning only, empty content. On provider 0.10.4 with production gpt-oss-20b weights, stop ["."] did this to 36/36 requests and ["\n\n"] to 14/36 (0/36 without a stop); each cut reasoning is an exact prefix of its same-seed no-stop twin, which went on to answer. ModelEOSPolicy.stopStringScope gives GPT-OSS the Harmony final-channel scope (<|channel|>final ... <|message|> up to <|end|>/<|return|>/<|call|>/<|start|>). It travels with the EOS policy: EngineV2SlotFactory -> makeBridge -> EngineV2Bridge -> CBv2Request.stopStringScope, and the matched-sequence replay uses the same scope. Other models keep whole-output matching. Bumps libs/mlx-swift-lm to 38b90ed1 (fix/harmony-final-stop-scope), which adds the scope to StopHoldback. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gptoss-stop-in-final-channel.md | 9 +++++ docs/architecture/inference.md | 2 +- libs/mlx-swift-lm | 2 +- .../Bridge/EngineV2Bridge+StopSequence.swift | 17 ++++++++-- .../Bridge/EngineV2Bridge+Submission.swift | 3 +- .../Bridge/EngineV2Bridge+Translation.swift | 6 ++-- .../Engine/Bridge/EngineV2Bridge.swift | 5 +++ .../Engine/Factory/EngineV2Config.swift | 2 ++ .../Engine/Factory/EngineV2SlotFactory.swift | 1 + .../Prompting/ChatTemplateFixes.swift | 6 ++++ .../GPTOSSHarmonyTemplateFixes.swift | 9 +++++ .../Inference/Prompting/ModelEOSPolicy.swift | 10 ++++++ .../Engine/EngineV2BridgeTests.swift | 33 +++++++++++++++++++ .../MultiModelBatchSchedulerEngineTests.swift | 11 +++++++ 14 files changed, 109 insertions(+), 7 deletions(-) create mode 100644 changelog.d/gptoss-stop-in-final-channel.md diff --git a/changelog.d/gptoss-stop-in-final-channel.md b/changelog.d/gptoss-stop-in-final-channel.md new file mode 100644 index 0000000000..da591a38d6 --- /dev/null +++ b/changelog.d/gptoss-stop-in-final-channel.md @@ -0,0 +1,9 @@ +### GPT-OSS stop sequences apply to the answer only + +- A client `stop` sequence on GPT-OSS models such as `gpt-oss-20b` now + matches only the Harmony `final` message, the text returned as `content`. + It used to match the private analysis too, so a sequence that appeared + while the model reasoned (for example `"\n\n"` or `"."`) ended the request + before any answer: `finish_reason` `stop`, reasoning only, empty content. + Tool-call arguments are never cut either. Other models keep whole-output + matching. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 5e51121117..4f24a26f5d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1843,7 +1843,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 (`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; the reported sequence replays the same scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | | `min_p`, `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index aee6ebb683..38b90ed185 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit aee6ebb6835c62feda80000c83f81f2788cc9822 +Subproject commit 38b90ed185d883bd5f54c355b8eab9df5fd0919a diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift index 5ddaf77813..6fb0f4c4c7 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift @@ -1,4 +1,5 @@ import Foundation +import MLXLMCommon extension EngineV2Bridge { func matchedStopSequence( @@ -10,13 +11,25 @@ extension EngineV2Bridge { tokenIds: generatedTokens, skipSpecialTokens: false ) - return Self.matchedStopSequence(candidates: candidates, generatedText: generatedText) + return Self.matchedStopSequence( + candidates: candidates, generatedText: generatedText, scope: stopStringScope) } + /// The candidate that ended generation. A scoped model matched stops only + /// inside its scope, so a candidate seen elsewhere (Harmony analysis) did + /// not stop it. static func matchedStopSequence( candidates: [String], - generatedText: String + generatedText: String, + scope: CBv2StopStringScope? = nil ) -> String? { + if let scope { + let holdback = StopHoldback(stopStrings: candidates, scope: scope) + let scan = holdback.ingest(generatedText) + guard scan.stopped else { return nil } + let tail = generatedText.unicodeScalars.dropFirst(scan.text.unicodeScalars.count) + return candidates.first { !$0.isEmpty && tail.starts(with: $0.unicodeScalars) } + } let generatedScalars = Array(generatedText.unicodeScalars) var best: (position: Int, candidateIndex: Int, value: String)? for (candidateIndex, candidate) in candidates.enumerated() where !candidate.isEmpty { diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift index 39116e8c83..1abc162e03 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift @@ -246,7 +246,8 @@ extension EngineV2Bridge { samplingDefaults: samplingDefaults, // The same coordinator hint that gates the write also tells the // engine which fork boundary is worth staging. - prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens + prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens, + stopStringScope: stopStringScope ) cbv2Request.positionState = positionState ?? multimodal?.positionState cbv2Request.hybridPrefixIdentity = hybridPrefixIdentity diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift index 3a33336bb5..da8a5bd87c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift @@ -65,7 +65,8 @@ enum EngineV2Translation { multimodal: CBv2MultimodalInput? = nil, tokenConstraint: (any CBv2TokenConstraint)? = nil, samplingDefaults: EngineV2SamplingDefaults = .legacy, - prefixCheckpointTargetTokens: Int? = nil + prefixCheckpointTargetTokens: Int? = nil, + stopStringScope: CBv2StopStringScope? = nil ) -> CBv2Request { CBv2Request( id: id, @@ -79,7 +80,8 @@ enum EngineV2Translation { prefixCacheEnabled: cacheEnabled, multimodal: multimodal, tokenConstraint: tokenConstraint, - prefixCheckpointTargetTokens: cacheEnabled ? prefixCheckpointTargetTokens : nil + prefixCheckpointTargetTokens: cacheEnabled ? prefixCheckpointTargetTokens : nil, + stopStringScope: stopStringScope ) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift index eda037ee03..1d2eae904b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift @@ -106,6 +106,9 @@ public actor EngineV2Bridge { /// tokens) — `buildStopTokenIds` semantics, computed ONCE at bridge /// construction so B=1 and batched behavior stay identical. let stopTokenIds: Set + /// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`); + /// nil matches the whole generated text. + let stopStringScope: CBv2StopStringScope? /// Artifact sampling defaults resolved once at construction /// (`EngineV2SamplingDefaults.resolve`); `.legacy` for every family /// that has not been admitted. @@ -368,6 +371,7 @@ public actor EngineV2Bridge { tokenizer: TokenizerHandle, eosTokenIds: Set, extraEOSTokens: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, samplingDefaults: EngineV2SamplingDefaults = .legacy, defaultMaxTokens: Int = 4096, maxConcurrentRequests: Int = 4, @@ -428,6 +432,7 @@ public actor EngineV2Bridge { extraEOSTokens: extraEOSTokens, convertTokenToId: { [inner = tokenizer.inner] in inner.convertTokenToId($0) } ) + self.stopStringScope = stopStringScope self.samplingDefaults = samplingDefaults self.defaultMaxTokens = defaultMaxTokens self.maxConcurrentRequests = maxConcurrentRequests diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Config.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Config.swift index e587d969fc..4641bbfd99 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Config.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Config.swift @@ -154,6 +154,7 @@ public enum EngineV2Factory { tokenizer: TokenizerHandle, eosTokenIds: Set, extraEOSTokens: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, samplingDefaults: EngineV2SamplingDefaults = .legacy, defaultMaxTokens: Int = 4096, maxConcurrentRequests: Int = 4, @@ -204,6 +205,7 @@ public enum EngineV2Factory { tokenizer: tokenizer, eosTokenIds: eosTokenIds, extraEOSTokens: extraEOSTokens, + stopStringScope: stopStringScope, samplingDefaults: samplingDefaults, defaultMaxTokens: defaultMaxTokens, maxConcurrentRequests: maxConcurrentRequests, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift index ab3f5e7e95..faec07ae75 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift @@ -571,6 +571,7 @@ enum EngineV2SlotFactory { tokenizer: tokenizer, eosTokenIds: eosTokenIds, extraEOSTokens: snapshot.extraEOSTokens, + stopStringScope: ModelEOSPolicy.stopStringScope(modelId: modelId, modelType: modelType), samplingDefaults: samplingDefaults, defaultMaxTokens: sizing.defaultMaxTokens, maxConcurrentRequests: effectiveMaxConcurrentRequests, diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatTemplateFixes.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatTemplateFixes.swift index a7fbe46dd6..66ef982671 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatTemplateFixes.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatTemplateFixes.swift @@ -5,6 +5,7 @@ // after the model family so future fixes do not bleed across templates. import Foundation +import MLXLMCommon import MLXLMServer struct ChatTemplateFixContext: Sendable { @@ -132,6 +133,11 @@ enum ChatTemplateFixes { return ids } + static func stopStringScope(context: ChatTemplateFixContext) -> CBv2StopStringScope? { + GPTOSSHarmonyTemplateFix.applies(to: context) + ? GPTOSSHarmonyTemplateFix.finalChannelStopScope : nil + } + static func validateGenericToolHistory( _ messages: [[String: any Sendable]] ) throws { diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/GPTOSSHarmonyTemplateFixes.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/GPTOSSHarmonyTemplateFixes.swift index ed312169f1..de294d465c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/GPTOSSHarmonyTemplateFixes.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/GPTOSSHarmonyTemplateFixes.swift @@ -5,6 +5,7 @@ // templates without changing other model families. import Foundation +import MLXLMCommon enum GPTOSSHarmonyTemplateFix { static func applies(to context: ChatTemplateFixContext) -> Bool { @@ -37,6 +38,14 @@ enum GPTOSSHarmonyTemplateFix { Set(["<|return|>", "<|endoftext|>", "<|call|>"].compactMap(tokenToId)) } + /// Client stop strings apply to the final channel, the text clients + /// receive as `content`. Matching them in analysis ended requests before + /// any answer existed (finish_reason "stop", reasoning only); tool-call + /// arguments are not answer text either. + static let finalChannelStopScope = CBv2StopStringScope( + opener: "<|channel|>final", openerEnd: "<|message|>", + closers: ["<|end|>", "<|return|>", "<|call|>", "<|start|>"]) + private static func isHarmonyModelHint(_ value: String?) -> Bool { guard let value else { return false } let normalized = value.lowercased() diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ModelEOSPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ModelEOSPolicy.swift index 707593cce7..f7c5d80cf0 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ModelEOSPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ModelEOSPolicy.swift @@ -6,6 +6,7 @@ // slot construction has one scheduler-independent stop-token policy. import Foundation +import MLXLMCommon public enum ModelEOSPolicy { /// Return model-specific EOS tokens at the engine boundary. Most models @@ -24,4 +25,13 @@ public enum ModelEOSPolicy { tokenToId: tokenToId ) } + + /// Where client stop strings apply; nil keeps whole-output matching. + public static func stopStringScope( + modelId: String, + modelType: String? = nil + ) -> CBv2StopStringScope? { + ChatTemplateFixes.stopStringScope( + context: ChatTemplateFixContext(modelId: modelId, modelType: modelType)) + } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift index 5cb3ce2e73..b320bb793b 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift @@ -804,6 +804,39 @@ struct EngineV2MatchedStopSequenceTests { ) == nil) } + @Test("a scoped model reports only the stop that ended its answer") + func scopedMatchedSequence() { + let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b") + let analysis = "<|channel|>analysis<|message|>The answer: Canberra. Done.<|end|>" + #expect(EngineV2Bridge.matchedStopSequence( + candidates: ["."], + generatedText: analysis + "<|start|>assistant<|channel|>final<|message|>It is Canberra", + scope: scope + ) == nil, "a period in the analysis did not stop the request") + #expect(EngineV2Bridge.matchedStopSequence( + candidates: ["!", "."], + generatedText: analysis + "<|start|>assistant<|channel|>final<|message|>It is Canberra. More", + scope: scope + ) == ".") + } + + @Test("GPT-OSS requests carry the bridge's stop-string scope") + func translationCarriesStopScope() { + let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b") + let request = ChatCompletionRequest( + model: "gpt-oss-20b", messages: [ChatMessage(role: "user", content: "hi")], + stop: .multiple(["\n\n"])) + let scoped = EngineV2Translation.cbv2Request( + id: CBv2RequestID(1), promptTokens: [1], request: request, defaultMaxTokens: 16, + stopTokenIds: [], stopStringScope: scope) + #expect(scoped.stopStrings == ["\n\n"]) + #expect(scoped.stopStringScope == scope) + let unscoped = EngineV2Translation.cbv2Request( + id: CBv2RequestID(2), promptTokens: [1], request: request, defaultMaxTokens: 16, + stopTokenIds: []) + #expect(unscoped.stopStringScope == nil) + } + @Test("compares Unicode scalars exactly rather than canonically") func unicodeScalarExactness() { #expect(EngineV2Bridge.matchedStopSequence( diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift index 50875deaf8..f30f4074cd 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift @@ -622,6 +622,17 @@ func harmonyEOSUsesModelTypeForAliasedModels() { #expect(ids == [199999, 200002, 200012]) } +@Test("GPT-OSS client stop strings apply to the Harmony final channel only") +func gptOssStopStringsAreScopedToTheFinalChannel() { + let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b") + #expect(scope == CBv2StopStringScope( + opener: "<|channel|>final", openerEnd: "<|message|>", + closers: ["<|end|>", "<|return|>", "<|call|>", "<|start|>"])) + #expect(ModelEOSPolicy.stopStringScope(modelId: "local-alias", modelType: "gpt_oss") == scope) + #expect(ModelEOSPolicy.stopStringScope(modelId: "gemma-4-26b-qat-4bit") == nil) + #expect(ModelEOSPolicy.stopStringScope(modelId: "qwen3.6-35b-a3b-vl-mtp-mxfp8") == nil) +} + @Test("non-Harmony EOS set is unchanged") func nonHarmonyEOSIsUnchanged() { let ids = ModelEOSPolicy.effectiveEOSTokenIds( From ac39dada16ca0e37a8f38ae973ea27af1c1999ca Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:06:24 -0700 Subject: [PATCH 02/58] Gemma 4 and models: client stop sequences skip reasoning and tool calls With reasoning on, a client stop string matched the model's private reasoning too, so one that appeared while the model reasoned (for example "." or "\n\n") ended the request before any answer: finish_reason "stop", reasoning only, empty content. GPT-OSS got an answer-channel scope in the previous commit; Gemma 4 and parsers need the opposite shape. ReasoningStopScope picks the scope per request from its reasoning parser: - gemma4: exclude <|channel>... and <|tool_call>...; - qwen3/deepseek_r1: exclude ... and ... , starting inside when the prompt probe left a think block open (Qwen's "\n" prefill); - Harmony and no parser keep the model's scope. submitTokenized(stopStringScope:) overrides the bridge's model scope, the text, media and MiMo-media paths pass it (media now probes its prompt before submit), and the reported stop_sequence replays the request's scope. Pins mlx-swift-lm fix/reasoning-stop-scope-exclude (95e1d2b9). Recorded on provider 0.10.4 with gemma-4-26b-qat-4bit, reasoning on, 36 prompts at temperature 0: stop ["."] and ["\n\n"] each gave 36/36 empty answers, all proven cut inside the thought. With this change: 0/36 for every stop set, no answer holds a stop, and each "."/"\n\n" answer equals the full answer cut at its first stop with identical reasoning (36/36 each). Co-Authored-By: Claude Opus 5.5 --- .../reasoning-stop-outside-reasoning.md | 12 +++ docs/architecture/inference.md | 2 +- libs/mlx-swift-lm | 2 +- .../Engine/Bridge/EngineV2Bridge+Events.swift | 6 +- .../Bridge/EngineV2Bridge+StopSequence.swift | 11 +-- .../Bridge/EngineV2Bridge+Submission.swift | 8 +- .../Engine/Bridge/EngineV2Bridge.swift | 4 +- .../MultiModelBatchSchedulerEngine.swift | 32 +++++--- .../Prompting/ReasoningStopScope.swift | 39 +++++++++ .../Engine/EngineV2BridgeTests.swift | 47 ++++++++++- .../Prompting/ReasoningStopScopeTests.swift | 82 +++++++++++++++++++ 11 files changed, 220 insertions(+), 25 deletions(-) create mode 100644 changelog.d/reasoning-stop-outside-reasoning.md create mode 100644 provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift diff --git a/changelog.d/reasoning-stop-outside-reasoning.md b/changelog.d/reasoning-stop-outside-reasoning.md new file mode 100644 index 0000000000..f4ea63b319 --- /dev/null +++ b/changelog.d/reasoning-stop-outside-reasoning.md @@ -0,0 +1,12 @@ +### 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. +- Tool-call frames are never cut either, and whitespace before the answer's + first character (the blank line after ``) cannot complete a stop + sequence on its own. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 4f24a26f5d..b6ff026bcf 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1843,7 +1843,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 and tool-call spans per request instead, starting inside reasoning when the prompt opened a think block (`ReasoningStopScope`). The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | | `min_p`, `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 38b90ed185..95e1d2b9c3 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 38b90ed185d883bd5f54c355b8eab9df5fd0919a +Subproject commit 95e1d2b9c39849cad31fcf0a53b916ea6c7fc474 diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift index e2286bd6ab..a23470e478 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift @@ -12,6 +12,7 @@ extension EngineV2Bridge { continuation: AsyncStream.Continuation, holdsSharedReservation: Bool, stopSequences: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, logprobsChannel: EngineV2LogprobsChannel? = nil, usageSignal: EngineV2RequestUsageSignal? = nil, prefixCacheReceiptID: CBv2RequestID? = nil, @@ -28,6 +29,7 @@ extension EngineV2Bridge { id: id, events: events, continuation: continuation, holdsSharedReservation: holdsSharedReservation, stopSequences: stopSequences, + stopStringScope: stopStringScope, logprobsChannel: logprobsChannel, usageSignal: usageSignal, prefixCacheReceiptID: prefixCacheReceiptID, @@ -59,6 +61,7 @@ extension EngineV2Bridge { continuation: AsyncStream.Continuation, holdsSharedReservation: Bool, stopSequences: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, logprobsChannel: EngineV2LogprobsChannel? = nil, usageSignal: EngineV2RequestUsageSignal? = nil, prefixCacheReceiptID: CBv2RequestID? = nil, @@ -144,7 +147,8 @@ extension EngineV2Bridge { if reason == .stop || reason == .length { usageSignal?.record(matchedStopSequence: matchedStopSequence( candidates: stopSequences, - generatedTokens: generatedTokens + generatedTokens: generatedTokens, + scope: stopStringScope )) } // Out-of-band usage detail (logprobs-channel pattern): the diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift index 6fb0f4c4c7..fd94acb8a4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift @@ -4,7 +4,8 @@ import MLXLMCommon extension EngineV2Bridge { func matchedStopSequence( candidates: [String], - generatedTokens: [Int] + generatedTokens: [Int], + scope: CBv2StopStringScope? ) -> String? { guard !candidates.isEmpty, !generatedTokens.isEmpty else { return nil } let generatedText = tokenizer.inner.decode( @@ -12,12 +13,12 @@ extension EngineV2Bridge { skipSpecialTokens: false ) return Self.matchedStopSequence( - candidates: candidates, generatedText: generatedText, scope: stopStringScope) + candidates: candidates, generatedText: generatedText, scope: scope) } - /// The candidate that ended generation. A scoped model matched stops only - /// inside its scope, so a candidate seen elsewhere (Harmony analysis) did - /// not stop it. + /// The candidate that ended generation. A scoped request matched stops + /// only inside its scope, so a candidate seen elsewhere (Harmony analysis, + /// reasoning) did not stop it. static func matchedStopSequence( candidates: [String], generatedText: String, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift index 1abc162e03..87810208eb 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift @@ -58,6 +58,7 @@ extension EngineV2Bridge { hybridPrefixIdentity: CBv2HybridPrefixIdentity? = nil, mediaKind: EngineV2MediaKind? = nil, tokenConstraint: (any CBv2TokenConstraint)? = nil, + stopStringScope: CBv2StopStringScope? = nil, donationDemand: SSDCheckpointDonationDemand? = nil, promptWork: PromptWork? = nil, measurementPurpose: EngineMeasurementPurpose = .serving @@ -76,6 +77,7 @@ extension EngineV2Bridge { hybridPrefixIdentity: hybridPrefixIdentity, mediaKind: mediaKind, tokenConstraint: tokenConstraint, + stopStringScope: stopStringScope, donationDemand: donationDemand, firstContentDeadline: nil, promptWork: promptWork, measurementPurpose: measurementPurpose) @@ -124,6 +126,9 @@ extension EngineV2Bridge { hybridPrefixIdentity: CBv2HybridPrefixIdentity? = nil, mediaKind: EngineV2MediaKind? = nil, tokenConstraint: (any CBv2TokenConstraint)? = nil, + /// Where this request's stop strings apply (`ReasoningStopScope`); nil + /// keeps the model's scope (`ModelEOSPolicy.stopStringScope`). + stopStringScope: CBv2StopStringScope? = nil, /// Coordinator repeat-demand hint for the complete-checkpoint write /// gate; nil keeps the legacy write-every-checkpoint behaviour. donationDemand: SSDCheckpointDonationDemand? = nil, @@ -247,7 +252,7 @@ extension EngineV2Bridge { // The same coordinator hint that gates the write also tells the // engine which fork boundary is worth staging. prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens, - stopStringScope: stopStringScope + stopStringScope: stopStringScope ?? self.stopStringScope ) cbv2Request.positionState = positionState ?? multimodal?.positionState cbv2Request.hybridPrefixIdentity = hybridPrefixIdentity @@ -936,6 +941,7 @@ extension EngineV2Bridge { id: id, events: events, continuation: continuation, holdsSharedReservation: sharedKVReserved, stopSequences: cbv2Request.stopStrings, + stopStringScope: cbv2Request.stopStringScope, logprobsChannel: logprobsChannel, usageSignal: usageSignal, prefixCacheReceiptID: prefixCacheReceiptID, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift index 1d2eae904b..7aad822919 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift @@ -106,8 +106,8 @@ public actor EngineV2Bridge { /// tokens) — `buildStopTokenIds` semantics, computed ONCE at bridge /// construction so B=1 and batched behavior stay identical. let stopTokenIds: Set - /// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`); - /// nil matches the whole generated text. + /// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`) + /// unless a request brings its own; nil matches the whole generated text. let stopStringScope: CBv2StopStringScope? /// Artifact sampling defaults resolved once at construction /// (`EngineV2SamplingDefaults.resolve`); `.legacy` for every family diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 1207bdc816..30f58e376d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -711,6 +711,17 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // failures) stay correct as written. await mediaGate.release(requestId: mediaReqId) try checkFirstContentDeadline() + // Initialize the think parser from the rendered media + // prompt: reasoning for an open block, content for a + // pre-closed block (thinking-disabled media). The stop + // scope starts in the same state. + let reasoningPrefix = ReasoningPromptProbe.streamingPrefix( + reasoningParser: visionRequest.reasoningParser, + stream: visionRequest.stream, + promptTokens: visionPrepared.promptTokens, + modelType: modelType, + decodeTail: { tokenizer.inner.decode(tokenIds: $0, skipSpecialTokens: false) } + ) ?? contentSeed(parser: visionRequest.reasoningParser, stream: visionRequest.stream) // Qualified native media shares text's request-owned // parser. Other VLMs retain their legacy media behavior. let upstream = try await bridge.submitTokenized( @@ -733,6 +744,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { multimodal: visionPrepared.multimodalInput(), hybridPrefixIdentity: mediaPrefixIdentity, mediaKind: visionPrepared.mediaKind, + stopStringScope: ReasoningStopScope.scope( + reasoningParser: visionRequest.reasoningParser, + reasoningPrefix: reasoningPrefix), donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -747,18 +761,6 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { await bridge.cancel(requestId: visionRequestId) throw error } - // Initialize the think parser from the rendered media - // prompt: reasoning for an open block, content for a - // pre-closed block (thinking-disabled media). - try checkFirstContentDeadline() - let reasoningPrefix = ReasoningPromptProbe.streamingPrefix( - reasoningParser: visionRequest.reasoningParser, - stream: visionRequest.stream, - promptTokens: visionPrepared.promptTokens, - modelType: modelType, - decodeTail: { tokenizer.inner.decode(tokenIds: $0, skipSpecialTokens: false) } - ) ?? contentSeed(parser: visionRequest.reasoningParser, stream: visionRequest.stream) - try checkFirstContentDeadline() return try await makeDeadlineCheckedEventStream( upstream: upstream, cancelUpstream: { await bridge.cancel(requestId: visionRequestId) }, @@ -970,6 +972,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { logprobsChannel: engineV2Logprobs?.channel, usageSignal: requestUsage, tokenConstraint: tokenConstraint, + stopStringScope: ReasoningStopScope.scope( + reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix), donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -1099,7 +1103,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { request:Self.translate(openAIRequest:request,defaultMaxTokens:maximumOutput, logitBias:engineV2Sampling?.logitBias,seed:engineV2Sampling?.seed), requestId:id,cacheScope:cacheScope,cacheEnabled:false,usageSignal:requestUsage, - multimodal:native.request.multimodal,firstContentDeadline:firstContentDeadline,profile:profile, + multimodal:native.request.multimodal, + stopStringScope:ReasoningStopScope.scope(reasoningParser:request.reasoningParser,reasoningPrefix:nil), + firstContentDeadline:firstContentDeadline,profile:profile, measurementPurpose:measurementPurpose) // Install the ONE existing router/forwarder before any post-submit // cancellation veto. Its protected mode drains actual terminal/error. diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift new file mode 100644 index 0000000000..ee0eddee8d --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift @@ -0,0 +1,39 @@ +// Copyright © 2026 Eigen Labs. +// +// Client stop strings end the answer, never the reasoning before it. Matched +// against all generated text, a stop the model happened to write while it +// reasoned ended the request before any answer: finish_reason "stop", +// reasoning only, empty content. Each scope mirrors the request's reasoning +// parser, so text it returns as reasoning, and tool-call frames, never match. + +import Foundation +import MLXLMCommon +import MLXLMServer + +enum ReasoningStopScope { + static let think = CBv2StopStringScope.Span(opener: "", closers: [""]) + static let thinkToolCall = CBv2StopStringScope.Span( + opener: "", closers: [""]) + static let gemmaThought = CBv2StopStringScope.Span(opener: "<|channel>", closers: [""]) + static let gemmaToolCall = CBv2StopStringScope.Span( + opener: "<|tool_call>", closers: [""]) + + /// The scope for one request. `reasoningPrefix` is the prompt's + /// `ReasoningPromptProbe` state: an open think block means output starts + /// inside reasoning. nil keeps the model's scope (GPT-OSS's Harmony final + /// channel) or, without a reasoning parser, whole-output matching. + static func scope( + reasoningParser: ReasoningParserFormat?, reasoningPrefix: String? + ) -> CBv2StopStringScope? { + switch reasoningParser { + case .qwen3?, .deepseekR1?: + return CBv2StopStringScope( + excluding: [think, thinkToolCall], + startingInside: reasoningPrefix == ReasoningPromptProbe.thinkOpen) + case .gemma4?: + return CBv2StopStringScope(excluding: [gemmaThought, gemmaToolCall]) + default: + return nil + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift index b320bb793b..55d565c59e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift @@ -143,6 +143,8 @@ private struct StubTokenizer: MLXLMCommon.Tokenizer { var tokenTable: [String: Int] = ["": 2, "<|eot|>": 7] var eosTokenString: String? = "" var failTemplate = false + /// Text for chosen ids; every other id decodes as "t". + var decodeTable: [Int: String] = [:] func encode(text: String, addSpecialTokens: Bool) -> [Int] { Array(repeating: 0, count: text.count) @@ -150,7 +152,7 @@ private struct StubTokenizer: MLXLMCommon.Tokenizer { /// Deterministic per-id text ("t") so logprob-entry conversion /// (token string + UTF-8 bytes) is assertable. func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { - tokenIds.map { "t\($0)" }.joined() + tokenIds.map { decodeTable[$0] ?? "t\($0)" }.joined() } func convertTokenToId(_ token: String) -> Int? { tokenTable[token] } func convertIdToToken(_ id: Int) -> String? { nil } @@ -435,6 +437,7 @@ private func makeBridge( modelId: String = "gemma-4-27b-it", eosTokenIds: Set = [2], extraEOSTokens: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, defaultMaxTokens: Int = 4096, kvBytesPerToken: Int = 0, fixedRequestBytes: Int = 0, @@ -453,6 +456,7 @@ private func makeBridge( tokenizer: TokenizerHandle(tokenizer), eosTokenIds: eosTokenIds, extraEOSTokens: extraEOSTokens, + stopStringScope: stopStringScope, defaultMaxTokens: defaultMaxTokens, maxConcurrentRequests: 4, kvBytesPerToken: kvBytesPerToken, @@ -837,6 +841,47 @@ struct EngineV2MatchedStopSequenceTests { #expect(unscoped.stopStringScope == nil) } + @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) + 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: "") + 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/Prompting/ReasoningStopScopeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift new file mode 100644 index 0000000000..65e457d5ae --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift @@ -0,0 +1,82 @@ +// 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: "") + == CBv2StopStringScope( + excluding: [ReasoningStopScope.think, ReasoningStopScope.thinkToolCall], + startingInside: true)) + for prefix in ["", nil] { + #expect( + ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: prefix) + == 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) + == CBv2StopStringScope(excluding: [ + .init(opener: "<|channel>", closers: [""]), + .init(opener: "<|tool_call>", closers: [""]), + ])) + } + + @Test("Harmony keeps the model's scope; no parser keeps whole-output matching") + func otherParsers() { + for parser in [ReasoningParserFormat.harmony, ReasoningParserFormat.none, nil] { + #expect(ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "") == 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: "") + #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) + #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.") + } +} From 5e56f05157f79f934c31487536800a3cbfabb688 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:46:57 -0700 Subject: [PATCH 03/58] Stop scope: native block engine stays unscoped; report the stop that matched From the review pass: - The native block engine (diffusion Gemma) builds its stop matcher without a scope, so it still matches the whole output. Its requests now carry no scope either, so the reported stop_sequence is the one that matched instead of nil. - A scoped report could name a candidate that only starts where the matching one does: "\n" for "\nUser:" right after , or a stop reaching into a span. It now names the first candidate that alone stops at the same place. - Pins mlx-swift-lm b5d4c754 (simpler excluded-span release, identical behavior). Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 +- libs/mlx-swift-lm | 2 +- .../Bridge/EngineV2Bridge+StopSequence.swift | 11 +++-- .../Bridge/EngineV2Bridge+Submission.swift | 6 ++- .../Engine/EngineV2BridgeTests.swift | 12 +++++ .../NativeBlockRetirementBridgeTests.swift | 49 +++++++++++++++++++ 6 files changed, 75 insertions(+), 7 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index b6ff026bcf..562fc16deb 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1843,7 +1843,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. Gemma 4 and `` parsers exclude their reasoning and tool-call spans per request instead, starting inside reasoning when the prompt opened a think block (`ReasoningStopScope`). The reported sequence replays the request's 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 and tool-call spans per request instead, starting inside reasoning when the prompt opened a think block (`ReasoningStopScope`). 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`, `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 95e1d2b9c3..b5d4c75495 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 95e1d2b9c39849cad31fcf0a53b916ea6c7fc474 +Subproject commit b5d4c754953c621c7fd27f787e32718d4078c2dc diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift index fd94acb8a4..c038b63c5a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift @@ -25,11 +25,14 @@ extension EngineV2Bridge { scope: CBv2StopStringScope? = nil ) -> String? { if let scope { - let holdback = StopHoldback(stopStrings: candidates, scope: scope) - let scan = holdback.ingest(generatedText) + let scan = StopHoldback(stopStrings: candidates, scope: scope).ingest(generatedText) guard scan.stopped else { return nil } - let tail = generatedText.unicodeScalars.dropFirst(scan.text.unicodeScalars.count) - return candidates.first { !$0.isEmpty && tail.starts(with: $0.unicodeScalars) } + // The first candidate that alone stops at the same place: one that + // merely starts there may not count (whitespace before an answer). + return candidates.first { + !$0.isEmpty + && StopHoldback(stopStrings: [$0], scope: scope).ingest(generatedText) == scan + } } let generatedScalars = Array(generatedText.unicodeScalars) var best: (position: Int, candidateIndex: Int, value: String)? diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift index 87810208eb..6aa9e87851 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift @@ -252,7 +252,11 @@ extension EngineV2Bridge { // The same coordinator hint that gates the write also tells the // engine which fork boundary is worth staging. prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens, - stopStringScope: stopStringScope ?? self.stopStringScope + // The native block engine's decoder matches stops over the whole + // output, so its requests carry no scope and the reported stop + // agrees with the one that matched. + stopStringScope: ownedEngine is CBv2NativeBlockEngine + ? nil : stopStringScope ?? self.stopStringScope ) cbv2Request.positionState = positionState ?? multimodal?.positionState cbv2Request.hybridPrefixIdentity = hybridPrefixIdentity diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift index 55d565c59e..8a39de94a2 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift @@ -841,6 +841,18 @@ struct EngineV2MatchedStopSequenceTests { #expect(unscoped.stopStringScope == nil) } + @Test("a scoped report names the stop that matched, not one that only starts there") + func scopedReportNamesTheMatchingCandidate() { + let inside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "") + #expect(EngineV2Bridge.matchedStopSequence( + candidates: ["\n", "\nUser:"], generatedText: "r\n\nUser: hi", scope: inside + ) == "\nUser:", "a bare newline before the answer does not stop it") + let outside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil) + #expect(EngineV2Bridge.matchedStopSequence( + candidates: ["Ar", scope: outside + ) == "A", "a stop never matches into a span") + } + @Test("a request's stop scope reaches the engine and the reported sequence") func requestScopeReachesEngineAndReport() async { // Gemma 4 with reasoning on: a period in the thought, "!" in the answer. diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift index 4aef6707df..fb1087619b 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() @@ -66,6 +88,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))) + #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) } From 46f7ae9c5d35ca5be5296596c8faec4f02b06cd1 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:04:15 -0700 Subject: [PATCH 04/58] Pin the merged mlx-swift-lm (#369) and the MLX stack it builds on libs/mlx-swift-lm moves to main 25bcd63f, the squash merge of Layr-Labs/mlx-swift-lm#369 (the Harmony final-channel stop scope this PR depends on). SDK main calls mlx-swift APIs newer than the pinned M5 hotfix (MLXFast fencedInputs), so the stack moves with it to the revision SDK main declares, as #1596 did: libs/mlx-swift c633d221 (nested mlx 72dffa2d, mlx-c 2ac897e3) and libs/mlx 72dffa2d. All three are on their repos' main. 72dffa2d carries the NAX head-dim split attention JIT fix (mlx main 6bc9de5b), the same get_steel_attention_nax_kernel change as the 0.10.3 hotfix 31f550af. Provider adaptations for the new SDK enum cases, behavior-preserving: - MLXServerGenerationEvent.logprobs is token metadata, handled like .info by the GLM and JSON answer-format observers (the provider streams logprobs through its own channel and emits no such events today). - MLXOpenAIServiceError.responseFormatCutOffByMaxTokens is the case the SDK split out of invalidResponseFormatOutput for a structured answer cut off by max_tokens; it keeps that case's 422 and retryable classification. Verified on M5 Max: Gemma 4 26B QAT serves an 8,204-token prompt (the 0.10.2 crash path) with an 8,192-token prefix hit on repeat; gpt-oss-20b stop ["."] still returns "The capital of Australia is Canberra". Co-Authored-By: Claude Opus 5.5 --- libs/mlx | 2 +- libs/mlx-swift | 2 +- libs/mlx-swift-lm | 2 +- .../Inference/Engine/InferenceErrorClassifier.swift | 2 +- .../Inference/Prompting/GLM5NextResponseFormat.swift | 2 +- .../ProviderCore/Inference/Prompting/JSONAnswerFormat.swift | 2 +- .../Sources/ProviderCore/ProviderLoop+ErrorMapping.swift | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/libs/mlx b/libs/mlx index 31f550af4d..72dffa2dbb 160000 --- a/libs/mlx +++ b/libs/mlx @@ -1 +1 @@ -Subproject commit 31f550af4df734c1296143b556dad624db3985fc +Subproject commit 72dffa2dbbdce95601fd84f5e8b6d7b4ec97a11b diff --git a/libs/mlx-swift b/libs/mlx-swift index 4926d3d977..c633d221d6 160000 --- a/libs/mlx-swift +++ b/libs/mlx-swift @@ -1 +1 @@ -Subproject commit 4926d3d977d691d2828231d8808058c57c63c874 +Subproject commit c633d221d627898502046714dcca677d9374a1ab diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 38b90ed185..25bcd63f18 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 38b90ed185d883bd5f54c355b8eab9df5fd0919a +Subproject commit 25bcd63f187b96ecf55796c93e104d20c9852d6a diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift index 9f5ed4be4c..76230786cd 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift @@ -39,7 +39,7 @@ func classifyTypedInferenceErrorReason(_ error: Error) -> InferenceErrorReason? } if let serviceError = error as? MLXOpenAIServiceError { switch serviceError { - case .invalidResponseFormatOutput, .multipleToolCallsNotAllowed: + case .invalidResponseFormatOutput, .responseFormatCutOffByMaxTokens, .multipleToolCallsNotAllowed: // Response-format validation and parallel-tool enforcement inspect // sampled model output. Another sample/provider can comply, so // these share the retryable non-provider-fault reason above. diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift index 2ae6daa37f..9f282a1b49 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift @@ -98,7 +98,7 @@ struct GLM5NextResponseFormatOutput { content += parsed.content guard let reasoning = parsed.reasoningContent, !reasoning.isEmpty else { return nil } return .parsed(.init(content: "", reasoningContent: reasoning)) - case .toolCall, .toolCallDelta, .info: + case .toolCall, .toolCallDelta, .info, .logprobs: return event } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift index a93497091e..2e8bb5ba9f 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift @@ -78,7 +78,7 @@ struct JSONAnswerOutput { switch event { case .content(let text): content += text case .parsed(let parsed): content += parsed.content - case .toolCall, .toolCallDelta, .info: break + case .toolCall, .toolCallDelta, .info, .logprobs: break } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift index ba44ca7431..024bcedf20 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift @@ -246,7 +246,7 @@ extension ProviderLoop { } if let svcErr = error as? MLXOpenAIServiceError { switch svcErr { - case .invalidResponseFormatOutput, .multipleToolCallsNotAllowed: + case .invalidResponseFormatOutput, .responseFormatCutOffByMaxTokens, .multipleToolCallsNotAllowed: return 422 case .embeddingsNotConfigured: return 501 From 2185dfe93cb60aa95ece16449f30d936b26dcb2a Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:37:56 -0700 Subject: [PATCH 05/58] Handle the SDK's .logprobs event in provider test switches The re-pinned mlx-swift-lm adds MLXServerGenerationEvent.logprobs. Seven test helpers switch exhaustively over events; each treats it like its existing non-content cases (.info / skipped). No assertion changes. Co-Authored-By: Claude Opus 5.5 --- .../Inference/Engine/EngineV2ProductionWiringTests.swift | 2 +- .../Inference/Live/Gemma/GemmaToolCallLiveTests.swift | 2 +- .../Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift | 2 ++ .../Inference/Tools/FlintAnswerStopTests.swift | 1 + .../Inference/Tools/FlintResponseFormatTests.swift | 2 +- .../Inference/Tools/QwenJSONAnswerServingTests.swift | 2 +- .../Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift | 1 + 7 files changed, 8 insertions(+), 4 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift index 5ba94ab9b2..157337c61e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift @@ -310,7 +310,7 @@ private func recordServerStream( events.append(.parsed(parsed)) case .info(let info): events.append(.info(prompt: info.promptTokens, completion: info.completionTokens)) - case .toolCall, .toolCallDelta: + case .toolCall, .toolCallDelta, .logprobs: continue } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift index c2510f1f03..1bd15374ec 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift @@ -261,7 +261,7 @@ struct GemmaToolCallLiveTests { case .toolCall(let call): calls.append(call) case .content(let text): visible += text case .parsed(let parsed): visible += parsed.content - case .info: break + case .info, .logprobs: break case .toolCallDelta: Issue.record("a named tool_choice call is never streamed") } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift index 97864fb0de..126037d353 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift @@ -391,6 +391,8 @@ private enum Qwen36ProductionCanary { if let call = delta.completed { result.toolCalls.append(call) } case .info(let info): result.info = info + case .logprobs: + break } } return result diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift index 0eb4a9b83f..353513fcdf 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift @@ -127,6 +127,7 @@ private struct FlintStreamOutcome { case .toolCall(let call): calls.append(call) case .toolCallDelta(let delta): if let call = delta.completed { calls.append(call) } case .info(let info): self.info = info + case .logprobs: break } } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift index 513ce9b551..7f097a8a3c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift @@ -359,7 +359,7 @@ struct FlintResponseFormatOutputTests { case .content(let text): outcome.content += text case .toolCall: outcome.calls += 1 case .toolCallDelta(let delta): if delta.completed != nil { outcome.calls += 1 } - case .info: break + case .info, .logprobs: break } } } catch { outcome.error = error } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift index 2bc354f374..1e9786d650 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift @@ -104,7 +104,7 @@ private struct QwenAnswerOutcome { case .content(let text): parser.parse(text).forEach { apply($0) } case .parsed(let parsed): apply(parsed) case .info(let info): self.info = info - case .toolCall, .toolCallDelta: break + case .toolCall, .toolCallDelta, .logprobs: break } } diff --git a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift index ff2fe52951..d883ce4a82 100644 --- a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift @@ -34,6 +34,7 @@ final class NemotronSuperLocalOutputTests: XCTestCase { return "F:" + call.function.name + String(decoding: try encoder.encode(call.function.arguments), as: UTF8.self) case .info: return "I" + case .logprobs: return "L" case .toolCallDelta: XCTFail("the Super output holds calls until validation; it never streams fragments") return "D" From 2841c6fe59741189d352a6bde934291a53f2aaa4 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:10:42 -0700 Subject: [PATCH 06/58] ci: fresh run for Release Integrity Attempt 2 of run 40756992782 failed test_cli_result_write_failure_preserves_original_error_and_findings: the test inherits the runner's GITHUB_RUN_ATTEMPT=2, so the budget runner reports MANUAL_SCAN_RERUN_DISABLED. Attempt 1 on the same tree passed. No code change. Co-Authored-By: Claude Opus 5.5 From 16d59d9ce686d918d4feec704090c28fd57788f2 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:46:33 -0700 Subject: [PATCH 07/58] Gemma 4 replies keep characters written as byte tokens swift-transformers' ByteFallbackDecoder releases <0xHH> tokens only when a later token arrives, so a decode ending in them drops them and shows nothing pending. Gemma 4 writes characters outside its vocabulary that way: a reply ending in one lost it, and DetokenizerV2 could restart its segment inside a run and corrupt the character. LocalTokenizerBridge.decode now releases a trailing run itself. Token IDs, sampling, model state and cache keys do not change; only the text decoded from the same tokens does. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-byte-fallback-flush.md | 5 + docs/architecture/inference.md | 9 ++ docs/developer/test.md | 11 ++ .../Prompting/LocalTokenizerLoader.swift | 38 ++++- .../LocalTokenizerByteFallbackTests.swift | 151 ++++++++++++++++++ 5 files changed, 213 insertions(+), 1 deletion(-) create mode 100644 changelog.d/gemma-byte-fallback-flush.md create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift diff --git a/changelog.d/gemma-byte-fallback-flush.md b/changelog.d/gemma-byte-fallback-flush.md new file mode 100644 index 0000000000..d0e5cc655e --- /dev/null +++ b/changelog.d/gemma-byte-fallback-flush.md @@ -0,0 +1,5 @@ +### Gemma 4 replies keep characters outside its vocabulary + +- A Gemma 4 reply that ended in a character its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost that character: `all zipped up 🗜` came back as `all zipped up `. 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. +- Token IDs, sampling, model state and cache keys do not change. Only the text decoded from the same tokens does. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it, and a byte token's `logprobs` text is U+FFFD or its ASCII character instead of empty. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..00fa10685d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1558,6 +1558,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`): diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..ef91bc75fe 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -549,6 +549,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. diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift index 43d41bb0f4..234b3ee2c1 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift @@ -70,12 +70,15 @@ private struct LocalTokenizerBridge: @unchecked Sendable, MLXLMCommon.Tokenizer, private let chatTemplate: String? private let modelType: String? let promptTokenCache: PromptTokenCache? + /// Byte values by token ID, when the decoder holds `<0xHH>` tokens back. + private let heldBackBytes: [Int: UInt8] init( _ upstream: any Tokenizers.Tokenizer, chatTemplate: String?, modelType: String?, promptCacheConfigurations: PromptTokenCache.Configurations?, environment: [String: String] ) { self.upstream = upstream + heldBackBytes = Self.byteTokens(heldBackBy: upstream) self.chatTemplate = chatTemplate.map { NemotronTemplateFilters.bindingFilters( in: normalizeSwiftJinjaTemplate($0), modelType: modelType) @@ -98,8 +101,41 @@ private struct LocalTokenizerBridge: @unchecked Sendable, MLXLMCommon.Tokenizer, upstream.encode(text: text, addSpecialTokens: addSpecialTokens) } + /// swift-transformers' `ByteFallbackDecoder` releases `<0xHH>` tokens only when a later + /// token arrives, so a decode ending in them drops them and shows nothing pending: Gemma 4 + /// lost a reply's last character outside its vocabulary, and `DetokenizerV2` could restart + /// its segment inside one. A partial run reads as U+FFFD, which `DetokenizerV2` holds back. func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { - upstream.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens) + let text = upstream.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens) + guard !heldBackBytes.isEmpty else { return text } + var bytes: [UInt8] = [] + // With `skipSpecialTokens` upstream drops special tokens before its decoder runs, so one + // inside or after the run does not end it. + for id in tokenIds.reversed() { + if let byte = heldBackBytes[id] { + bytes.append(byte) + } else if !skipSpecialTokens || !upstream.decode(tokens: [id], skipSpecialTokens: true).isEmpty { + break + } + } + return bytes.isEmpty ? text : text + String(decoding: bytes.reversed(), as: UTF8.self) + } + + /// The `<0xHH>` tokens of a decoder that holds them back: a lone one decodes to nothing. + /// Empty for a decoder that spells or releases them, so a fixed upstream turns this off. + private static func byteTokens(heldBackBy upstream: any Tokenizers.Tokenizer) -> [Int: UInt8] { + var bytes: [Int: UInt8] = [:] + for value in UInt8.min...UInt8.max { + let token = String(format: "<0x%02X>", value) + // A token outside the vocabulary converts to the unknown ID. + if let id = upstream.convertTokenToId(token), upstream.convertIdToToken(id) == token { + bytes[id] = value + } + } + guard let probe = bytes.keys.first, + upstream.decode(tokens: [probe], skipSpecialTokens: false).isEmpty + else { return [:] } + return bytes } func convertTokenToId(_ token: String) -> Int? { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift new file mode 100644 index 0000000000..51104f39d3 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift @@ -0,0 +1,151 @@ +// 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 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) } + 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") + } +} From b1c3d66843e466759583f3c276196294ced97840 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:53:24 -0700 Subject: [PATCH 08/58] Byte-fallback tests and changelog after independent verification Tests only and the changelog, no source change: a reply of byte tokens alone longer than any walk bound, a control character written as a byte, and the unknown-token test loads the tokenizer repeatedly because the probe reads whichever byte token a dictionary lists first. The changelog now states the stop-string exception, the streamed logprobs entries, logprobs bytes and /detokenize. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-byte-fallback-flush.md | 7 +++--- .../LocalTokenizerByteFallbackTests.swift | 25 ++++++++++++++++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/changelog.d/gemma-byte-fallback-flush.md b/changelog.d/gemma-byte-fallback-flush.md index d0e5cc655e..3f22c7588c 100644 --- a/changelog.d/gemma-byte-fallback-flush.md +++ b/changelog.d/gemma-byte-fallback-flush.md @@ -1,5 +1,6 @@ ### Gemma 4 replies keep characters outside its vocabulary -- A Gemma 4 reply that ended in a character its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost that character: `all zipped up 🗜` came back as `all zipped up `. 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. -- Token IDs, sampling, model state and cache keys do not change. Only the text decoded from the same tokens does. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it, and a byte token's `logprobs` text is U+FFFD or its ASCII character instead of empty. +- 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/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift index 51104f39d3..e420784478 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift @@ -96,6 +96,22 @@ struct LocalTokenizerByteFallbackTests { } } + @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() @@ -144,8 +160,11 @@ struct LocalTokenizerByteFallbackTests { // 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) } - 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") + // 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") + } } } From 94d7a0b06fbbb68598734842e761ec9ef57d3c22 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:37:00 -0700 Subject: [PATCH 09/58] Share one expert dispatch across Gemma prompt tokens and decode rows Bumps libs/mlx-swift-lm to ef43498b9 (branch feat/gemma4-batched-prompt-experts on 7933a0fa). Registered Gemma stages now compute a prompt frame's expert blocks in one unsorted dispatch per operation, instead of one subgraph per prompt token (about six launches per token per layer since the 2026-10-23 token expert policy). Batch-decode rows share the same call. Every (token, expert) pair is still an M=1 gather_qmv product, and the top-8 reduction keeps its one-row col_reduce_small layout. Each token therefore keeps its bytes, and the exact Gemma arithmetic receipt (gemma4-bf16-token-expert-reduction-v1) and the cache identities it separates are unchanged. Evidence (docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md): - Gemma4PrefillExpertTests on CPU: bytes equal at 7-512 tokens and decode rows 2/3/8, at 4 and 8 bits. - M5 Ultra GPU: bytes equal for 1-2048 rows at the production kernel classes, and at hidden 2816 / width 704 / 128 experts. - Synthetic expert layer: 2,048 tokens 349.9 -> 36.8 ms. - Gemma4BatchDecodeTests, Gemma4BatchArithmeticAgreementTests, GemmaPrefillArithmeticTests, GemmaPrefixChunkTests and ResidentAdmissionGemma4Tests pass. Not validated: pair throughput, full-model numerics, other GPU generations. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-pipeline-speed.md | 3 + docs/architecture/hardware-support.md | 4 +- docs/architecture/inference.md | 31 +++++-- docs/developer/test.md | 19 ++-- ...026-11-01-gemma-pipeline-prompt-experts.md | 89 +++++++++++++++++++ docs/reports/README.md | 3 +- libs/mlx-swift-lm | 2 +- 7 files changed, 134 insertions(+), 17 deletions(-) create mode 100644 changelog.d/gemma-pipeline-speed.md create mode 100644 docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md new file mode 100644 index 0000000000..ab2c331010 --- /dev/null +++ b/changelog.d/gemma-pipeline-speed.md @@ -0,0 +1,3 @@ +### 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 350 ms to about 37 ms; pair throughput is not yet measured. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index c91f96c2e6..4340fa6664 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-10-31 +> Last updated: 2026-11-01 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 @@ -1117,6 +1117,8 @@ Registered Gemma prompt projections use an explicit singleton-token reduction policy for supported BF16 affine packing, as described in [inference](inference.md#gemma-prompt-projection-reductions). The exact arithmetic receipt separates older rectangular-projection results and cache identities. +The prompt's expert blocks share one unsorted dispatch per operation and keep +each token's bytes, so the receipt is unchanged. Component tests do not qualify a complete model, both rank orders, or prompt throughput. Keep existing cross-chip failures and require fresh full-artifact numerical and timing evidence for both scoped prompt policies. Attention and diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..89a983bc4c 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -4475,7 +4475,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 unsorted +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. @@ -4857,17 +4859,30 @@ 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`) that keeps their assignments +unsorted. MLX selects `gather_qmv` from the bits, dtype and the N and K widths +alone, and the top-8 reduction's `col_reduce_small` thread layout depends only +on the hidden width, so each token's bytes 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 diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..ea56b6a9a2 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -2217,13 +2217,20 @@ 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 unsorted expert call carrying every token's routes +in order, 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 +unsorted call with each row's one-row bytes. 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, 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/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..f40da4abcb --- /dev/null +++ b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md @@ -0,0 +1,89 @@ +# 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 unsorted 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 with their expert assignments kept in row order: + +- every (row, expert) pair is still an M=1 gathered product. MLX selects + `gather_qmv` from the bits, dtype and the N and K widths alone, and its grid + gives each row its own threadgroups; +- the top-8 weighted reduction keeps its one-row `col_reduce_small` thread + layout, which 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 unsorted expert call | +| 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 | +| Sensitivity: the shared call against the earlier sorted rectangular call at 512 and 2,048 rows | M5 Ultra GPU | bytes differ, as expected | + +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. + +| Expert block, 4-bit | 512 tokens | 2,048 tokens | +|---|---:|---:| +| Per-token subgraphs (before) | 74.6 ms | 349.9 ms | +| Shared unsorted dispatch (after) | 9.8 ms | 36.8 ms | +| Sorted rectangle (the prompt path before 2026-10-23) | 1.6 ms | 3.6 ms | + +| 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 s before and take about 1.0 s after, ignoring attention and norms. +That would lift the stage's projection-bound prompt rate from about 360 to +about 2,000 tokens per second. The M=1 policy still costs about 9x 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..28707b07fe 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 unsorted 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/mlx-swift-lm b/libs/mlx-swift-lm index 7933a0faad..ef43498b90 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 7933a0faad62559a010a1126241c61a1822315d9 +Subproject commit ef43498b90ec6b395ac4d41b7149ac383ad22c5a From 5a4c94f6487b29694c087f9dbbe2b487d47d3b50 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:37:34 -0700 Subject: [PATCH 10/58] State Gemma 4's expert routing for the placement prior Gemma4PlacementFamily now states expertRouting (8 of 128 experts per layer, from Gemma4StageGeometry) and names the experts.switch_glu banks as routed experts. Gemma layouts carry routedExperts: 12,846,366,720 bytes (QAT 4-bit) and 24,265,359,360 bytes (8-bit). ClusterHardwarePrior then reads 2,424,219,708 weight bytes per QAT 4-bit token instead of every layer byte. That matches the exact-header audit of 2026-09-20, and the old figure was about 6x too high. The three Gemma golden layouts gain the block. The 12 golden plan digests change only by the layout the plan echoes; cut 15 pipeline and both recorded pairs' ranks are unchanged. GemmaRoutedExpertChecks builds the QAT 4-bit layout from the retained real headers and requires it to equal the golden layout. PlacementChecks: 1422 checks pass. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-pipeline-speed.md | 1 + docs/architecture/inference.md | 13 +++++ docs/developer/test.md | 6 ++- .../Metadata/Gemma4PlacementFamily.swift | 10 ++++ .../Gemma4/Metadata/Gemma4StageGeometry.swift | 5 +- .../GemmaRoutedExpertChecks.swift | 49 +++++++++++++++++++ .../PlacementChecks/Golden/expected.json | 12 ++--- .../Golden/layouts/gemma-4-26b-8bit.json | 2 +- .../Golden/layouts/gemma-4-26b-qat-4bit.json | 2 +- .../Golden/layouts/gemma-4-26b.json | 2 +- .../pairs/m3ultra-m5ultra/expected.json | 12 ++--- .../Tests/PlacementChecks/Main.swift | 1 + 12 files changed, 98 insertions(+), 17 deletions(-) create mode 100644 libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md index ab2c331010..91c723ecb1 100644 --- a/changelog.d/gemma-pipeline-speed.md +++ b/changelog.d/gemma-pipeline-speed.md @@ -1,3 +1,4 @@ ### 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 350 ms to about 37 ms; pair throughput is not yet measured. +- The planner's hardware prior counts 8 of Gemma 4's 128 experts per token instead of every expert byte. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 89a983bc4c..511a20992f 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4498,6 +4498,19 @@ 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 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 diff --git a/docs/developer/test.md b/docs/developer/test.md index ea56b6a9a2..9c6a070660 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -25,7 +25,11 @@ 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 prior to read +2,424,219,708 weight bytes per token. 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 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/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift new file mode 100644 index 0000000000..1322a06a42 --- /dev/null +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift @@ -0,0 +1,49 @@ +import DarkbloomClusterPlacement +import DarkbloomClusterProtocol +import Foundation + +/// Gemma 4 26B routes each token to 8 of a layer's 128 experts. The QAT +/// 4-bit layout built here from the artifact's retained real tensor headers +/// (`StageMetadataChecks/Inputs`) must equal its golden layout, routed experts +/// included, and the hardware prior must read 8/128 of those banks per token: +/// 2,424,219,708 bytes, the figure the exact-header audit of 2026-09-20 +/// recorded, instead of every layer byte. +func checkGemmaRoutedExperts(golden: URL, _ checks: PlacementChecks) throws { + let inputs = golden.deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("StageMetadataChecks/Inputs", isDirectory: true) + var tensors: [ClusterPlacementStoredTensor] = [] + let headers = try FileManager.default.contentsOfDirectory(atPath: inputs.path) + .filter { $0.hasSuffix(".safetensors.header.json") }.sorted() + for file in headers { + let header = try JSONSerialization.jsonObject(with: Data(contentsOf: inputs.appendingPathComponent(file))) + as? [String: Any] ?? [:] + for (name, value) in header where name != "__metadata__" { + guard let entry = value as? [String: Any], let dtype = entry["dtype"] as? String, + let shape = entry["shape"] as? [Int], let offsets = entry["data_offsets"] as? [Int], + offsets.count == 2, offsets[1] > offsets[0] else { + throw ProbeError("Malformed retained Gemma header entry: \(name)") + } + tensors.append(.init(name: name, byteCount: offsets[1] - offsets[0], dtype: dtype, shape: shape)) + } + } + let layout = try ClusterPlacementLayouts.layout( + configuration: Data(contentsOf: inputs.appendingPathComponent("config.json")), tensors: tensors, + manifest: Data(contentsOf: inputs.appendingPathComponent("manifest.json"))) + let expected = try ClusterModelLayout.decode( + Data(contentsOf: golden.appendingPathComponent("layouts/gemma-4-26b-qat-4bit.json"))) + checks.require("Gemma QAT 4-bit: the layout from the retained real headers equals its golden layout, routed experts included", + headers.count == 3 && layout == expected) + let experts = layout.routedExperts + checks.require("Gemma QAT 4-bit routes 8 of 128 experts; its expert banks hold 12,846,366,720 bytes, no tensor-parallel share", + experts?.routing == ClusterExpertRouting(selected: 8, experts: 128) && experts?.loadedBytes == 12_846_366_720 + && experts?.tensorParallelDividedBytes == nil) + checks.require("Gemma QAT 4-bit decode reads 2,424,219,708 weight bytes per token (8/128 of the expert banks)", + ClusterHardwarePrior.decodeBytesPerToken(layout) == 2_424_219_708) + // The 8-bit artifact's golden layout carries the same routing over its 8-bit banks. + for name in ["gemma-4-26b-8bit", "gemma-4-26b"] { + let eight = try ClusterModelLayout.decode(Data(contentsOf: golden.appendingPathComponent("layouts/\(name).json"))) + checks.require("\(name): 8 of 128 routed experts over 24,265,359,360 bytes of 8-bit banks", + eight.routedExperts?.routing == ClusterExpertRouting(selected: 8, experts: 128) + && eight.routedExperts?.loadedBytes == 24_265_359_360) + } +} diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json index 8bd6c48808..9e71e90567 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json @@ -43,9 +43,9 @@ }, "gemma-4-26b": { "cut": 15, - "handOffPlanSHA256": "d18c86e08d609efff04dba63a250d8a26580ff9bc0fe3854b2399961cc8711a9", + "handOffPlanSHA256": "660cb1537bea8a3af6709fa7e82fe8f59a197c54200be814083be361c8410aa7", "mode": "pipeline_v1", - "planSHA256": "4a7acb8341eb99036e819e651b6eb0a91f7d17256192b06c1864c1fdb938eeb4", + "planSHA256": "4773f5dda0b6eab7234e2345227ce08f7f1e5e75e1be6872a6709dea650e7da6", "ranks": [ { "device": "mac-a", @@ -64,9 +64,9 @@ }, "gemma-4-26b-8bit": { "cut": 15, - "handOffPlanSHA256": "4c7e27371b3173548670079e804af65e7229ab812146d9a9d3b5a532ea96d511", + "handOffPlanSHA256": "92f2a8f617a28b13fc68ba89a34a7870e953e17ccdb004d9a0087e2030e63dd6", "mode": "pipeline_v1", - "planSHA256": "8c0e0dc6c7781fe37db90ea37f423fa8b9c370bfea8010a3e2531d00cc41ca8b", + "planSHA256": "98018701fbd5f5049ab44f105fe0ab2f0edb1b7dc63443cedd08597bbbdf63c2", "ranks": [ { "device": "mac-a", @@ -85,9 +85,9 @@ }, "gemma-4-26b-qat-4bit": { "cut": 15, - "handOffPlanSHA256": "2b8dc675c45902362c5c01aa93149de0472c2afec72f00232f240278d6ede4df", + "handOffPlanSHA256": "d134439b21431a48404e2af363824fccf6e02053d771a5b7a67ae7599a6af3a5", "mode": "pipeline_v1", - "planSHA256": "d6bc775b447fc25abc13db52b72b7d0c17b47a0b87f356f0cd57f86d5aa7e21c", + "planSHA256": "ef31103798080a01f959ba00f07a56b5d80cbacf4f16634b9313007d776c31fa", "ranks": [ { "device": "mac-a", diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json index b1778ac039..b13a8ab341 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json @@ -1 +1 @@ -{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b_8bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} +{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":24265359360,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b_8bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json index 1668d30971..2eb3687281 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json @@ -1 +1 @@ -{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785","boundaryBytesPerToken":5632,"configurationSHA256":"29910322dd085f45c8f95c6c0f1611b20f722d6f6c8394321b34817e98a972fa","egress":{"largestTensorBytes":369098752,"loadedBytes":415241728,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1140925536,"requestWorkBytes":0,"storedBytes":1140925536,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":369098752,"loadedBytes":415236096,"requestWorkBytes":0,"storedBytes":415236096,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b_qat_4bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} +{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785","boundaryBytesPerToken":5632,"configurationSHA256":"29910322dd085f45c8f95c6c0f1611b20f722d6f6c8394321b34817e98a972fa","egress":{"largestTensorBytes":369098752,"loadedBytes":415241728,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1140925536,"requestWorkBytes":0,"storedBytes":1140925536,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":369098752,"loadedBytes":415236096,"requestWorkBytes":0,"storedBytes":415236096,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":12846366720,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b_qat_4bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json index 0f7b245b87..7007a83d71 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json @@ -1 +1 @@ -{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} +{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":24265359360,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json index e275189a6c..bdcb4a2f53 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json @@ -43,9 +43,9 @@ }, "gemma-4-26b": { "cut": 15, - "handOffPlanSHA256": "2420b14ee7687f033f5a58b7fa9c325ae6121af03b4cd4be0f5f41a016e2c436", + "handOffPlanSHA256": "6dbd01083d074d1aa44f08f1d25603e93145492395501e6f9a1f6c1766247a00", "mode": "pipeline_v1", - "planSHA256": "ad764d50791a75f5c9c1a9f407276e1c717fb6f5e6847e8ea82380f5b0cdbf79", + "planSHA256": "dbc808e3abc53b12d32170bdbb964cbc478e129050f06b0d843a8880a164d5d5", "ranks": [ { "device": "mac-a", @@ -64,9 +64,9 @@ }, "gemma-4-26b-8bit": { "cut": 15, - "handOffPlanSHA256": "cbaef9455f5c272fe17a847a206a173ce94c84f9c5ebadde7a9b0f43f1ebc6e5", + "handOffPlanSHA256": "9608c7ee6e2b22cb943a557b68cf734c22c6ecc4f93a07f8a0b26104cc191cb3", "mode": "pipeline_v1", - "planSHA256": "042a04d32603765619f97b7044c24c9d846a4bde9e741830d39648504c73ad27", + "planSHA256": "4edd4f8c73fb0e0eadb07f432ffc2644c42212b7c53aa29a041482e6fad7a625", "ranks": [ { "device": "mac-a", @@ -85,9 +85,9 @@ }, "gemma-4-26b-qat-4bit": { "cut": 15, - "handOffPlanSHA256": "ea678c6cf760925bd0ac3ec68359692b856dee2e6f67a0ee51d25fb3fe52abdb", + "handOffPlanSHA256": "db53aeb719616838b61b304b734aaaa284fac2ba3b18ccbc6b9063604f2cf1b4", "mode": "pipeline_v1", - "planSHA256": "b4c956fee4903ca1e6c6a81b54d0409d531ec446b12dd644ff0690734455ff6c", + "planSHA256": "c5b174e249c69c9f7eacef02029a1c80125dc7fa9e7832e60fa96c2d44571ccb", "ranks": [ { "device": "mac-a", diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift index 1c51a219b2..71af6d3349 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift @@ -63,6 +63,7 @@ import Foundation try checkForcedMode(inputs, checks) try checkAutoChoice(inputs, golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) try checkGLMTensorParallel(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) + try checkGemmaRoutedExperts(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) try checkServedModes(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) try checkPipelineSpeculativeHolding(URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) try checkQwenPipelineSpeculative(URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) From a3d7407608c94f987b592e78b23376eeaf015b57 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:39:13 -0700 Subject: [PATCH 11/58] Serve four lanes by default on serial-prefill Gemma 4 pipelines Coordinator-registered Gemma pipeline pairs served one request at a time: nothing on the native-member path sets a width, and every pipeline lane adapter defaulted to one. DistributedInstalledPlan.defaultBatchLanes now gives a text-only Gemma 4 pipeline whose saved setup prefills serially gemma4PipelineBatchLanes (4), following GLM tensor parallel's installed default: - decode rows keep their one-request arithmetic (Gemma4BatchDecodeScope, bound by Gemma4BatchArithmeticAgreement), and each prompt frame runs alone on its request's chunk grid; - each lane is charged its whole request state on every rank and admitted against live memory (reserveLane); a lane that does not fit is refused alone, retryably; - paged KV reserves pages per request, so the width allocates nothing at load, and the activation floor is unchanged (one prompt frame per step). Lanes prefill serially, so a setup saved with one_chunk_lookahead_v1 keeps its schedule and one lane. A planned batch width already requires serial prefill. Every other adapter, a saved width and the owner's DARKBLOOM_CLUSTER_BATCH_LANES behave as before. Tests: DistributedInstalledLanesTests (all adapters and schedules), DistributedInstalledCancellationTests, ClusterPairSlotOwnerLanesTests and DistributedAutomaticBatchPlannerTests (34 tests). ClusterInstalledSessionChecks check a Gemma fixture's default reaching the rank and a lookahead fixture keeping one lane. Not validated: multi-lane joining, cancellation and output agreement on the real pair. Raising the default is an owner decision after those runs. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-pipeline-speed.md | 1 + docs/architecture/hardware-support.md | 6 +++ docs/architecture/inference.md | 33 ++++++++++++++-- docs/developer/test.md | 7 +++- docs/provider/two-mac-cluster.md | 5 ++- .../Installed/DistributedInstalledPlan.swift | 38 ++++++++++++++----- .../InstalledBatchLanesCheck.swift | 17 +++++++++ .../InstalledFixture.swift | 4 +- .../InstalledSessionCheck.swift | 4 +- .../DistributedInstalledLanesTests.swift | 26 +++++++++++++ 10 files changed, 124 insertions(+), 17 deletions(-) diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md index 91c723ecb1..156ce1d906 100644 --- a/changelog.d/gemma-pipeline-speed.md +++ b/changelog.d/gemma-pipeline-speed.md @@ -1,4 +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 350 ms to about 37 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/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 4340fa6664..0dcd9d98ce 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1124,6 +1124,12 @@ throughput. Keep existing cross-chip failures and require fresh full-artifact numerical and timing evidence for both scoped prompt policies. Attention and full-model composition retain their independent qualification requirements. +A serial-prefill Gemma 4 pipeline serves four lanes by default +([Gemma pipeline lanes](inference.md#gemma-pipeline-lanes)). Each lane is +charged its whole request state on every rank and admitted against live +memory. The measured activation floor still applies: prompt frames run one at +a time and decode rows add only M=1 work. + ### Additional TP resident allocations TP layouts may carry allocator-bounded resident allocations outside their text diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 511a20992f..6bf40eb455 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -123,7 +123,9 @@ 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 serves its installed +default lanes instead ([Gemma pipeline lanes](#gemma-pipeline-lanes)). +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 @@ -3042,7 +3044,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 (a serial-prefill +Gemma 4 pipeline serves [four](#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`). @@ -3093,7 +3096,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 @@ -4498,6 +4502,29 @@ 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 | 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 | +| No load-time allocation | The paged pool reserves pages per request, not per lane (`CBv2StageKVHost`) | +| Activation floor | Unchanged: one prompt frame runs per step, and decode rows add only M=1 work | +| 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 diff --git a/docs/developer/test.md b/docs/developer/test.md index 9c6a070660..f65e53f735 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1874,8 +1874,11 @@ 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 four default lanes, 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, diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index d8688b78b8..7bbcbd1c84 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -1,6 +1,6 @@ # Two Macs as one provider (guided setup) -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Two Apple Silicon Macs joined by one Thunderbolt 5 cable serve a model together: each Mac holds part of its layers, and the pair serves as one provider. Setting @@ -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 four 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/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift index 6369d1c732..a417011024 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift @@ -264,8 +264,9 @@ struct DistributedInstalledPlan: Sendable { "DARKBLOOM_CLUSTER_LOAD_DIGESTS": ["1", "tensors"], ] - /// The pair's batch lanes: the adapter's default in the selected mode - /// (`defaultBatchLanes(adapter:mode:hasPrivateImages:)`), unless the owner's + /// The pair's batch lanes: the adapter's default in the selected mode and + /// prefill schedule (`defaultBatchLanes(adapter:mode:hasPrivateImages:runtimeModelID:prefillSchedule:)`), + /// unless the setup saved a priced width or the owner's /// environment names 1...8 (1 serves one request at a time). A malformed /// override explicitly keeps one lane, so a sanitized child cannot restore /// a wider family default. Nil where the @@ -277,7 +278,8 @@ struct DistributedInstalledPlan: Sendable { func batchLanes(_ environment: [String: String] = ProcessInfo.processInfo.environment) -> Int? { guard let adapter = ClusterRuntimeAdapter(rawValue: capability.adapterID), let lanes = Self.defaultBatchLanes(adapter: adapter, mode: configuration.selectedGenerationMode, - hasPrivateImages: capability.hasPrivateImages, runtimeModelID: capability.runtimeModelID) else { + hasPrivateImages: capability.hasPrivateImages, runtimeModelID: capability.runtimeModelID, + prefillSchedule: configuration.selectedPrefillSchedule) else { return nil } // The assistant quote admits exactly this capacity. A diagnostic @@ -313,7 +315,10 @@ struct DistributedInstalledPlan: Sendable { /// The lanes a pair of `adapter` serves by default in `mode`, or nil when /// its workers serve one request at a time there. /// - Pipeline: the lane adapters (`laneAdapters`), text only, at - /// `defaultBatchLanes`. + /// `defaultBatchLanes`; Gemma 4 with serial prefill at + /// `gemma4PipelineBatchLanes`. Lanes prefill serially, so a setup that + /// saved the one-chunk lookahead keeps it and one lane. A nil schedule + /// names no setup and takes the family-neutral default. /// - Qwen tensor parallel (every registered TP row, dense or routed /// experts): one by default; a priced saved width or explicit local /// diagnostic may select its native 2...8 lane owner. @@ -324,8 +329,11 @@ struct DistributedInstalledPlan: Sendable { /// path as a request alone (`GLM5NextTensorParallelMedia`), so the /// capability's image candidate does not change the lanes. static func defaultBatchLanes(adapter: ClusterRuntimeAdapter, mode: ClusterGenerationMode, - hasPrivateImages: Bool, runtimeModelID: String? = nil) -> Int? { + hasPrivateImages: Bool, runtimeModelID: String? = nil, + prefillSchedule: ClusterPrefillSchedule? = nil) -> Int? { switch mode { + case .pipeline where !hasPrivateImages && adapter == .gemma4LayerStage && prefillSchedule == .serial: + gemma4PipelineBatchLanes case .pipeline where !hasPrivateImages && laneAdapters.contains(adapter): defaultBatchLanes case .tensorParallel where tensorParallelLaneAdapters.contains(adapter): tensorParallelBatchLanes case .tensorParallel where servesQwenTensorLanes(adapter: adapter, runtimeModelID: runtimeModelID) && !hasPrivateImages: @@ -343,11 +351,23 @@ struct DistributedInstalledPlan: Sendable { /// Concurrent requests a lane-serving pair batches by default. Both /// owners serve them (`ClusterOwnerLeaseState.lanes`), and the leader's /// session, bridge and local API admit as many; more requests wait in the - /// API's queue. The default stays one while the repaired joining and - /// cancellation paths undergo model-specific multi-lane qualification. - /// Earlier pair measurements (Qwen 3.5 35B A3B, 2026-10-19) preceded - /// those repairs and do not qualify the current loop. + /// API's queue. The default stays one (Gemma 4's serial pipeline aside) + /// while the repaired joining and cancellation paths undergo + /// model-specific multi-lane qualification. Earlier pair measurements + /// (Qwen 3.5 35B A3B, 2026-10-19) preceded those repairs and do not + /// qualify the current loop. static let defaultBatchLanes = 1 + /// Concurrent requests a serial-prefill Gemma 4 pipeline serves by + /// default, coordinator-registered pairs included. Each decode row keeps + /// its one-request arithmetic (`Gemma4BatchDecodeScope`, bound by + /// `Gemma4BatchArithmeticAgreement`) and each prompt frame runs alone on + /// its request's own chunk grid, so a lane costs no request its own + /// tokens. Each lane is charged its whole request state on every rank + /// and admitted against live memory; a lane the host cannot hold is + /// refused alone, retryably. Paged KV reserves pages per request, not per + /// lane, so the width adds no load-time allocation. Four of the priced + /// pipeline widths (2, 4, 8) until the pair measures more. + static let gemma4PipelineBatchLanes = 4 /// Concurrent requests GLM tensor parallel serves by default: the /// protocol's lane cap (`ClusterWorkerLaneSession`, `ClusterWorkerPair`). /// Its lanes run one request's unit after another (each bitwise alone), so diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift index 41956de4b2..ce784144a1 100644 --- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift +++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift @@ -201,6 +201,23 @@ extension InstalledSessionCheck { registered: ("registered_gemma4_26b_qat_4bit", "registered_gemma4_26b_qat_4bit_greedy_generation_v1", "fixture/gemma"), adapter: .gemma4LayerStage) let gemmaPrepared = try gemma.prepare() + // A serial-prefill Gemma pipeline, coordinator-registered or not, serves its four default lanes. + try require(gemmaPrepared.plan.configuration.selectedPrefillSchedule == .serial + && gemmaPrepared.plan.batchLanes([:]) == DistributedInstalledPlan.gemma4PipelineBatchLanes + && gemmaPrepared.plan.lanesRetireAlone([:]), "Gemma serial pipeline default lanes differ") + let gemmaDefault = gemmaPrepared.plan.nativeEnvironment(matrix: gemmaPrepared.matrixURL, + ownerEnvironment: try observed(gemmaPrepared.plan.localOwnerConfiguration(ownerEnvironment: [:]))) + try require(gemmaDefault[key] == String(DistributedInstalledPlan.gemma4PipelineBatchLanes), + "Gemma default lanes did not reach the rank") + // A saved one-chunk lookahead keeps its schedule: lanes prefill serially, so it keeps one lane. + let lookahead = try InstalledFixture.make(root: f.root.appendingPathComponent("lane-gemma-lookahead"), + probe: f.probe, owner: probe, worker: f.worker, + registered: ("registered_gemma4_26b_qat_4bit", "registered_gemma4_26b_qat_4bit_greedy_generation_v1", "fixture/gemma"), + adapter: .gemma4LayerStage, prefillSchedule: .oneChunkLookahead) + let lookaheadPlan = try lookahead.prepare().plan + try require(lookaheadPlan.configuration.selectedPrefillSchedule == .oneChunkLookahead + && lookaheadPlan.batchLanes([:]) == 1 && !lookaheadPlan.lanesRetireAlone([:]), + "Gemma lookahead pipeline gained default lanes") for lanes in [1, 2, 4, 8] { let child = try observed(gemmaPrepared.plan.localOwnerConfiguration(ownerEnvironment: [key: String(lanes)])) let native = gemmaPrepared.plan.nativeEnvironment(matrix: gemmaPrepared.matrixURL, ownerEnvironment: child) diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift index 37e14e873a..af24383ab6 100644 --- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift +++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift @@ -22,7 +22,7 @@ struct InstalledFixture: Sendable { registered: (model: String, profile: String, publicID: String) = ("registered_qwen35_9b", "registered_qwen35_9b_greedy_generation_v1", "fixture/public-model"), adapter: ClusterRuntimeAdapter = .qwen35Dense, standsForRegisteredArtifact: Bool = true, - batchLanes: Int? = nil) throws -> Self { + batchLanes: Int? = nil, prefillSchedule: ClusterPrefillSchedule? = nil) throws -> Self { try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) let model = root.appendingPathComponent("model", isDirectory: true) try FileManager.default.createDirectory(at: model, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) @@ -58,6 +58,7 @@ struct InstalledFixture: Sendable { .init(rank:0,sourceLayerStart:0,sourceLayerEnd:4,stagePlanSHA256:pin("1"),constructionConfigurationSHA256:pin("2")), .init(rank:1,sourceLayerStart:4,sourceLayerEnd:32,stagePlanSHA256:pin("3"),constructionConfigurationSHA256:pin("4"))])], arithmeticPolicyID:adapter.arithmeticPolicyID,arithmeticPolicySHA256:pin("5"), + supportedPrefillSchedules:prefillSchedule == nil ? [.serial] : ClusterPrefillSchedule.allCases, supportedGenerationModes:advertisedModes) let capBytes = try ClusterRuntimeCapabilityCodec.encode(cap), capHash = hash(capBytes) try capBytes.write(to: model.appendingPathComponent("fixture-capability.json")) @@ -76,6 +77,7 @@ struct InstalledFixture: Sendable { "tokenizerFiles":named.filter{$0.1 != "config"}.map{["path":$0.0,"sha256":hash($0.2),"purpose":$0.1 == "template" ? "chatTemplate":"tokenizer"]}] if let generationMode { object["generationMode"]=generationMode } if let batchLanes { object["batchLanes"] = batchLanes } + if let prefillSchedule { object["prefillSchedule"] = prefillSchedule.rawValue } if pairing { let approval:[String:Any]=["id":"installed-fixture-approval","model":"fixture/public-model","generation":1, "plan_sha256":pin("f"),"artifact_sha256":artifact,"native_runtime_sha256":binary,"metallib_sha256":pin("6"), diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift index 5c90dfd238..60a9c05081 100644 --- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift +++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift @@ -981,7 +981,9 @@ final class EndpointBox: @unchecked Sendable { /// values every rank is given (the pair driver's own values), under budgets /// derived from the setup; GPT-OSS and Gemma 4 included. static func adaptersOnTheInstalledPath(_ f:InstalledFixture) throws { - let gemma=["MLX_GATHER_QMM_EXPERT_SLICES":"trust","MLX_GEMMA4_FUSED_WEIGHTED_UNSORT":"1"] + // A serial-prefill Gemma pipeline also names its default lanes. + let gemma=["MLX_GATHER_QMM_EXPERT_SLICES":"trust","MLX_GEMMA4_FUSED_WEIGHTED_UNSORT":"1", + DistributedInstalledPlan.batchLanesSwitch:String(DistributedInstalledPlan.gemma4PipelineBatchLanes)] let cases:[(String,ClusterRuntimeAdapter,String,[String:String],String?)]=[ ("a35",.qwen35RoutedExperts,"registered_qwen35_35b_a3b",["MLX_GATHER_QMM_EXPERT_SLICES":"trust"],"phase_split_v1"), ("a36",.qwen35RoutedExperts,"registered_qwen36_35b_a3b",["MLX_GATHER_QMM_EXPERT_SLICES":"trust"],"phase_split_v1"), diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift index db85eb8163..1ae33e2183 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift @@ -33,6 +33,32 @@ struct DistributedInstalledLanesTests { } } + @Test func gemmaSerialPipelineServesFourLanesAndLookaheadKeepsOne() { + #expect(Plan.gemma4PipelineBatchLanes == 4) + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false, + prefillSchedule: .serial) == 4) + // Lanes prefill serially: a saved lookahead keeps its schedule and one lane. + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false, + prefillSchedule: .oneChunkLookahead) == Plan.defaultBatchLanes) + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false) == Plan.defaultBatchLanes) + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: true, + prefillSchedule: .serial) == nil) + for mode in ClusterGenerationMode.allCases where mode != .pipeline { + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: mode, hasPrivateImages: false, + prefillSchedule: .serial) == nil) + } + // Every other lane adapter keeps its singleton default under either schedule. + for adapter in Plan.laneAdapters where adapter != .gemma4LayerStage { + for schedule in ClusterPrefillSchedule.allCases { + #expect(Plan.defaultBatchLanes(adapter: adapter, mode: .pipeline, hasPrivateImages: false, + prefillSchedule: schedule) == Plan.defaultBatchLanes) + } + } + // A cancelled Gemma lane retires alone, as every pipeline lane adapter's does. + #expect(Plan.lanesRetireAlone(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false, + lanes: Plan.gemma4PipelineBatchLanes)) + } + @Test func otherModesAndFamiliesKeepTheirLanes() { // GLM's pipeline still serves one request at a time. #expect(Plan.defaultBatchLanes(adapter: .glm5NextLayerStage, mode: .pipeline, hasPrivateImages: false) == nil) From 562eaf89aa3c578995818af3f18e49f2ea8eb02f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:52:05 -0700 Subject: [PATCH 12/58] Group Gemma's shared expert rows by expert for weight locality Bumps libs/mlx-swift-lm to 211512fd (feat/gemma4-batched-prompt-experts). The shared expert call now groups a frame's assignments by expert, so consecutive threadgroups read the same weights. It still does not give the gathers the sorted hint, so every pair stays an M=1 gather_qmv product, and the rows return to token order before the unchanged reduction. Each token's bytes and the receipt are unchanged. Evidence: GPU equality at the production kernel classes and at production geometry; Gemma4PrefillExpertTests, Gemma4BatchDecodeTests, Gemma4BatchArithmeticAgreementTests and GemmaPrefillArithmeticTests (CPU, 9 tests); and Gemma4StagePagedSyntheticTests (GPU, lanes join and leave). On a synthetic production-geometry expert layer (4-bit, 2,048 tokens) the shared call went 37.2 -> 30.8 ms; the per-token graph took 414.3 ms in the same run. The report and docs say so. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-pipeline-speed.md | 2 +- docs/architecture/hardware-support.md | 4 +- docs/architecture/inference.md | 14 ++++--- docs/developer/test.md | 7 ++-- ...026-11-01-gemma-pipeline-prompt-experts.md | 41 ++++++++++++------- docs/reports/README.md | 2 +- libs/mlx-swift-lm | 2 +- 7 files changed, 43 insertions(+), 29 deletions(-) diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md index 156ce1d906..171b5279d8 100644 --- a/changelog.d/gemma-pipeline-speed.md +++ b/changelog.d/gemma-pipeline-speed.md @@ -1,5 +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 350 ms to about 37 ms; pair throughput is not yet measured. +- 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/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 0dcd9d98ce..7a599859d6 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1117,8 +1117,8 @@ Registered Gemma prompt projections use an explicit singleton-token reduction policy for supported BF16 affine packing, as described in [inference](inference.md#gemma-prompt-projection-reductions). The exact arithmetic receipt separates older rectangular-projection results and cache identities. -The prompt's expert blocks share one unsorted dispatch per operation and keep -each token's bytes, so the receipt is unchanged. +The prompt's expert blocks share one dispatch per operation and keep each +token's bytes, so the receipt is unchanged. Component tests do not qualify a complete model, both rank orders, or prompt throughput. Keep existing cross-chip failures and require fresh full-artifact numerical and timing evidence for both scoped prompt policies. Attention and diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 6bf40eb455..2f6f79b02d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4479,8 +4479,8 @@ 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 -retains singleton request shapes. The rows' routed experts share one unsorted -call that keeps each row's singleton bytes +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. @@ -4903,10 +4903,12 @@ 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`) that keeps their assignments -unsorted. MLX selects `gather_qmv` from the bits, dtype and the N and K widths -alone, and the top-8 reduction's `col_reduce_small` thread layout depends only -on the hidden width, so each token's bytes equal those of its own one-token +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 selects `gather_qmv` from the +bits, dtype and the N and K widths alone. 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)). diff --git a/docs/developer/test.md b/docs/developer/test.md index f65e53f735..2865718615 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -2226,11 +2226,12 @@ unchanged tied head. `Gemma4PrefillExpertTests` executes the actual Gemma decode shared MLP and sparse expert block with the attention output isolated to zero; it assembles an independent projection/expert oracle from one-token expert calls while preserving the original rectangular normalization and elementwise -operations. It requires one unsorted expert call carrying every token's routes -in order, with the oracle's bytes, at 7 to 512 tokens. A separate expert-only composition +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, and a decode check requires 2, 3 and 8 independent rows to share one -unsorted call with each row's one-row bytes. Ordinary and verification paths +call with each row's one-row bytes. 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. With `GEMMA4_EXPERT_ROWS_GPU=1` the suite also diff --git a/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md index f40da4abcb..98e55973dd 100644 --- a/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md +++ b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md @@ -3,7 +3,7 @@ > Last updated: 2026-11-01 This record covers the change to the registered Gemma 4 stages' prompt expert -blocks: they now share one unsorted dispatch per operation instead of building +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. @@ -22,13 +22,16 @@ prompt throughput had been measured for it. ## Change `SwitchGLU.callAndWeightedReduceRows` (mlx-swift-lm) projects all rows of a -frame in one call with their expert assignments kept in row order: +frame in one call: -- every (row, expert) pair is still an M=1 gathered product. MLX selects - `gather_qmv` from the bits, dtype and the N and K widths alone, and its grid - gives each row its own threadgroups; -- the top-8 weighted reduction keeps its one-row `col_reduce_small` thread - layout, which depends only on the hidden width. +- 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 + selects `gather_qmv` from the bits, dtype and the N and K widths alone, + 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 @@ -38,11 +41,12 @@ call. | 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 unsorted expert call | +| `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 | | 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 @@ -59,11 +63,18 @@ One layer with random packed weights at the registered geometry: experts at 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) | 74.6 ms | 349.9 ms | -| Shared unsorted dispatch (after) | 9.8 ms | 36.8 ms | -| Sorted rectangle (the prompt path before 2026-10-23) | 1.6 ms | 3.6 ms | +| 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 | |---|---:|---:| @@ -71,10 +82,10 @@ carry contention noise. | 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 s before and take about 1.0 s after, ignoring attention and norms. -That would lift the stage's projection-bound prompt rate from about 360 to -about 2,000 tokens per second. The M=1 policy still costs about 9x the -rectangle. Closing that gap needs a multi-row `qmv` kernel that keeps qmv's +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 diff --git a/docs/reports/README.md b/docs/reports/README.md index 28707b07fe..5200bb7ed9 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -4,7 +4,7 @@ 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 unsorted dispatch with the same bytes: CPU and M5 Ultra GPU equality evidence and synthetic one-layer timings; no pair or qualification result. +- [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/mlx-swift-lm b/libs/mlx-swift-lm index ef43498b90..211512fdc9 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit ef43498b90ec6b395ac4d41b7149ac383ad22c5a +Subproject commit 211512fdc98bce9c41177866b9151c741473c23e From fdabade31a5433186c022d5be270925df7368ba3 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:04:05 -0700 Subject: [PATCH 13/58] perf(cluster): MiMo pipeline decode in 100-operation command buffers MiMo stage decode now 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. That covers plain and compact decode frames, phase-split and alone-route decode (MiMoLayerStageSession.decode), lane steps (decodeBatch) and pipeline_mtp_v1 rounds, drafts included (MiMoMTPGeneration.runProducer/runConsumer). Prefill keeps the rank's 16-operation guard and MLX's per-chip size bound. Each routed layer's expert launch takes a whole 1 GiB bank, so under those limits a decode step committed a buffer every few launches. Only commit points move. MiMoDecodeCommandBufferTests drives two random stages as the session does (tiny BF16, and quantized like the registered row: MXFP4 experts, affine 8-bit projections, K/V widths 192/128) on ordinary caches, request-owned pages and two lanes, with a verify window rolled back on both stages. Residuals, logits rows and every cache and page array are byte-equal under the guard and the decode limits. Memory: MLX keeps up to ten command buffers in flight, so a whole stage step can now be in flight. MiMoRequestStateBudget charges every full-attention layer's decode-row scores at once (decodeRows: 1, or the verify window). The LOAD quote is unchanged; requests with prompts shorter than that window are charged slightly more. Planner: MiMoPlacementFamily states its routing (8 of 256 experts, the mlp.switch_mlp banks and scales). The hardware prior then reads 10,767,036,288 bytes a decode step instead of 166,600,109,952. The prior prices tensor parallel only, so MiMo plans are unchanged. The golden layout gains routedExperts. The four golden plan digests change only by the layout the plan echoes; MiMoRoutedExpertChecks proves that, and that without the block the plans are the recorded ones byte for byte. Not validated: the registered weights, the real pair and any speed. On one Mac a synthetic 8-layer stage stepped about 13% slower under the decode limits (encode-bound, KB-sized launches). The real pair A/B decides. Co-Authored-By: Claude Opus 5.5 --- changelog.d/mimo-pipeline-decode-buffers.md | 14 ++ docs/architecture/hardware-support.md | 6 +- docs/architecture/inference.md | 44 +++- docs/developer/test.md | 30 ++- .../Generation/MiMoLayerStageSession.swift | 21 +- .../Models/MiMo/MTP/MiMoMTPGeneration.swift | 29 ++- .../MiMo/Metadata/MiMoPlacementFamily.swift | 11 + .../Metadata/MiMoRequestStateBudget.swift | 16 +- .../MiMo/Resident/MiMoResidentAdmission.swift | 2 +- .../MiMoDecodeCommandBufferTests.swift | 215 ++++++++++++++++++ .../MiMoPagedAdmissionTests.swift | 2 +- .../MiMoResidentAdmissionTests.swift | 21 ++ .../PlacementChecks/Golden/expected.json | 4 +- .../mimo-v2.6-flash-mopd-2026-09-28-r1.json | 2 +- .../pairs/m3ultra-m5ultra/expected.json | 4 +- .../Tests/PlacementChecks/Main.swift | 1 + .../MiMoRoutedExpertChecks.swift | 75 ++++++ 17 files changed, 475 insertions(+), 22 deletions(-) create mode 100644 changelog.d/mimo-pipeline-decode-buffers.md create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoDecodeCommandBufferTests.swift create mode 100644 libs/darkbloom-cluster/Tests/PlacementChecks/MiMoRoutedExpertChecks.swift diff --git a/changelog.d/mimo-pipeline-decode-buffers.md b/changelog.d/mimo-pipeline-decode-buffers.md new file mode 100644 index 0000000000..fcc19cdbf2 --- /dev/null +++ b/changelog.d/mimo-pipeline-decode-buffers.md @@ -0,0 +1,14 @@ +### 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 covers every full-attention layer's decode + scores at once, which the larger command buffers can keep alive together. The + LOAD quote is unchanged; requests with prompts shorter than that window 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. MiMo has no + tensor-parallel plan yet, so MiMo placements are unchanged. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index c91f96c2e6..338d70ee7b 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-10-31 +> Last updated: 2026-11-01 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 @@ -1050,6 +1050,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 also holds each of its full-attention layers' +scores for the decode rows at once, because decode command buffers 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 diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..702162367b 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -4775,6 +4775,48 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Reside and `MiMoV26IndependentHistoryCache.swift`. See [MiMo independent-history checks](../developer/test.md#mimo-independent-history-batch-checks). +### 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`), so under +the decode limits a whole stage step can be in flight at once. A request's +workspace therefore holds every full-attention layer's scores for its decode +rows at the same time (`MiMoRequestStateBudget.estimate`, `decodeRows`: one row, +or the verify window's `depth + 1`). It never charges less than one prompt +frame's scores on one layer. Gathered page views are already charged for every +layer (`MiMoPagedKVAllowance.pages`). The decode speed effect on the registered +model is 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. MiMo has no tensor-parallel plan, so its pipeline plans are +unchanged. + ### Gemma paged prefix restoration Installed plain Gemma pipelines retain the paged KV default at every supported diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..20f95f38d0 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -2186,6 +2186,34 @@ 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. 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 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..`) cannot complete a stop - sequence on its own. +- With tools declared, tool-call frames are not cut either. Without declared + tools a literal tool tag in an answer is text, 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/inference.md b/docs/architecture/inference.md index 14d92783c4..6bd6d29fdf 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -2119,7 +2119,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. Gemma 4 and `` parsers exclude their reasoning and tool-call spans per request instead, starting inside reasoning when the prompt opened a think block (`ReasoningStopScope`). 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`) | `[]` | +| `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`). Without declared tools 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 | — | diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 7eed4bc348..e1e4b213b8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -820,7 +820,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { mediaKind: visionPrepared.mediaKind, stopStringScope: ReasoningStopScope.scope( reasoningParser: visionRequest.reasoningParser, - reasoningPrefix: reasoningPrefix), + reasoningPrefix: reasoningPrefix, + parsesToolCalls: toolHandler != nil), donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -1041,7 +1042,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { usageSignal: requestUsage, tokenConstraint: tokenConstraint, stopStringScope: ReasoningStopScope.scope( - reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix), + reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix, + parsesToolCalls: toolHandler != nil), donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -1424,7 +1426,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { logitBias:engineV2Sampling?.logitBias,seed:engineV2Sampling?.seed), requestId:id,cacheScope:cacheScope,cacheEnabled:false,usageSignal:requestUsage, multimodal:native.request.multimodal, - stopStringScope:ReasoningStopScope.scope(reasoningParser:request.reasoningParser,reasoningPrefix:nil), + stopStringScope:ReasoningStopScope.scope(reasoningParser:request.reasoningParser,reasoningPrefix:nil,parsesToolCalls:toolHandler != nil), firstContentDeadline:firstContentDeadline,profile:profile, measurementPurpose:measurementPurpose) // Install the ONE existing router/forwarder before any post-submit diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift index ee0eddee8d..80bb50c6c3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift @@ -4,7 +4,9 @@ // against all generated text, a stop the model happened to write while it // reasoned ended the request before any answer: finish_reason "stop", // reasoning only, empty content. Each scope mirrors the request's reasoning -// parser, so text it returns as reasoning, and tool-call frames, never match. +// parser, so text it returns as reasoning never matches. Tool-call frames don't +// either when the request parses tool calls; without declared tools a literal +// tool tag in an answer is text the client receives, so stops still apply. import Foundation import MLXLMCommon @@ -22,16 +24,18 @@ enum ReasoningStopScope { /// `ReasoningPromptProbe` state: an open think block means output starts /// inside reasoning. nil keeps the model's scope (GPT-OSS's Harmony final /// channel) or, without a reasoning parser, whole-output matching. + /// `parsesToolCalls` is whether the request has a tool stream handler. static func scope( - reasoningParser: ReasoningParserFormat?, reasoningPrefix: String? + reasoningParser: ReasoningParserFormat?, reasoningPrefix: String?, parsesToolCalls: Bool ) -> CBv2StopStringScope? { switch reasoningParser { case .qwen3?, .deepseekR1?: return CBv2StopStringScope( - excluding: [think, thinkToolCall], + excluding: parsesToolCalls ? [think, thinkToolCall] : [think], startingInside: reasoningPrefix == ReasoningPromptProbe.thinkOpen) case .gemma4?: - return CBv2StopStringScope(excluding: [gemmaThought, gemmaToolCall]) + return CBv2StopStringScope( + excluding: parsesToolCalls ? [gemmaThought, gemmaToolCall] : [gemmaThought]) default: return nil } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift index 4a5aebc122..8ded8dd4fa 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift @@ -846,11 +846,11 @@ struct EngineV2MatchedStopSequenceTests { @Test("a scoped report names the stop that matched, not one that only starts there") func scopedReportNamesTheMatchingCandidate() { - let inside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "") + let inside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true) #expect(EngineV2Bridge.matchedStopSequence( candidates: ["\n", "\nUser:"], generatedText: "r\n\nUser: hi", scope: inside ) == "\nUser:", "a bare newline before the answer does not stop it") - let outside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil) + let outside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil, parsesToolCalls: true) #expect(EngineV2Bridge.matchedStopSequence( candidates: ["Ar", scope: outside ) == "A", "a stop never matches into a span") @@ -867,7 +867,7 @@ struct EngineV2MatchedStopSequenceTests { .finished(reason: .stop, usage: CBv2Usage(promptTokens: 5, completionTokens: 4)), ])) let bridge = makeBridge(engine: engine, tokenizer: tokenizer) - let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil) + let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true) let signal = EngineV2RequestUsageSignal() _ = await record(await bridge.submitTokenized( promptTokens: [1, 2, 3], @@ -882,7 +882,7 @@ struct EngineV2MatchedStopSequenceTests { @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: "") + let think = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true) for (modelScope, requestScope, expected) in [ (harmony, nil, harmony), (nil, nil, nil), (harmony, think, think), ] { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift index d63307e4ed..13821848c5 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift @@ -110,7 +110,7 @@ struct NativeBlockRetirementBridgeTests { 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))) + 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() diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift index 65e457d5ae..119192c41a 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift @@ -19,13 +19,13 @@ struct ReasoningStopScopeTests { func thinkParsers() { for parser in [ReasoningParserFormat.qwen3, .deepseekR1] { #expect( - ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "") + 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) + ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: prefix, parsesToolCalls: true) == CBv2StopStringScope( excluding: [ReasoningStopScope.think, ReasoningStopScope.thinkToolCall])) } @@ -35,17 +35,47 @@ struct ReasoningStopScopeTests { @Test("Gemma 4 excludes its thought channel and tool calls") func gemma() { #expect( - ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil) + 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] { - #expect(ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "") == nil) + for parsesToolCalls in [true, false] { + #expect( + ReasoningStopScope.scope( + reasoningParser: parser, reasoningPrefix: "", parsesToolCalls: parsesToolCalls) == nil) + } } } @@ -55,7 +85,7 @@ struct ReasoningStopScopeTests { 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: "") + let scope = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true) #expect(run(output, stops: ["."], scope: nil) == "Capital of Australia") #expect( run(output, stops: ["."], scope: scope) @@ -72,7 +102,7 @@ struct ReasoningStopScopeTests { 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) + 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) From 7d085fe0e7341240eac67fd43772fd3ee953ea4a Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:54:24 -0800 Subject: [PATCH 22/58] docs: the stop scope depends on a tool handler, not only on declared tools tool_choice none and generic vision media with tools have no handler, and MiMo always has one. Comment and docs only. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 4 ++-- .../ProviderCore/Inference/Prompting/ReasoningStopScope.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 6bd6d29fdf..57cc7d6d88 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -2119,7 +2119,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. 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`). Without declared tools 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`) | `[]` | +| `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 | — | diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift index 80bb50c6c3..0162d04e6e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift @@ -5,8 +5,8 @@ // reasoned ended the request before any answer: finish_reason "stop", // reasoning only, empty content. Each scope mirrors the request's reasoning // parser, so text it returns as reasoning never matches. Tool-call frames don't -// either when the request parses tool calls; without declared tools a literal -// tool tag in an answer is text the client receives, so stops still apply. +// either when the request parses tool calls; otherwise a literal tool tag in an +// answer is text the client receives, so stops still apply. import Foundation import MLXLMCommon From 31fe79c7506c014ea1c288a0ed6539e1d90bcb90 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:54:24 -0800 Subject: [PATCH 23/58] docs: freshness stamp for the Gemma decode section Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 156bbdac12..01d78a0f03 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` From e62928b943a19c537f490e28ccaaad5db42e1034 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:11:15 -0800 Subject: [PATCH 24/58] cluster: regression tests for a committed start that outlives its session The production GLM-5.3-Flash pair (2026-11-01 03:37Z) stopped serving for 13 hours: after a peer loss the leader's session ended while its stop was still waiting, and every later committed start was refused with "a committed start is already served". These tests drive the leader's real serve/stop state machine with a scripted pair: - a session that ends while its serve cannot finish must release the start for the next one, and the stale serve must stand down; - the start is released while the slot's drain still runs; - a start whose session already stopped is never served. They fail on origin/master and pass with the fix that follows. Co-Authored-By: Claude Opus 5.5 --- .../ClusterPairServingTests.swift | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) 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()) } From 660610221b5ee34a7d0224365e4e6855bcdadc6e Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:11:15 -0800 Subject: [PATCH 25/58] cluster: release a committed start when its session ends The leader's one-start token (clusterPairServingEpoch) was cleared only once the session's stop had retired the pair slot, and never while a serve was still forming. After a peer loss or fence, the slot's drain or the serve could outlast the session's bounded wait (stopServing gives up at the grant's cleanup deadline); the session sent its release receipt anyway, and the token outlived it. Nothing else cleared it, so every later committed start was refused until a restart. The session's stop now releases the token at once and records the epoch as ended. Every stop call still waits for the slot to retire before the receipt. A serve re-checks that it still holds its start after each suspension and stands down (shuts its owner down, retires what it published) without touching a newer start. The stopped and forming flags are gone: the token is the ownership. The slot-level guard against two published slots is unchanged. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-serving-epoch.md | 11 +++++ docs/reference/cluster-control-protocol.md | 3 +- .../Coordinator/NativePairMemberServing.swift | 3 +- .../ProviderLoop+ClusterPairServing.swift | 48 +++++++++++-------- .../Sources/ProviderCore/ProviderLoop.swift | 9 ++-- 5 files changed, 46 insertions(+), 28 deletions(-) create mode 100644 changelog.d/cluster-pair-serving-epoch.md diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md new file mode 100644 index 0000000000..1c3ce62979 --- /dev/null +++ b/changelog.d/cluster-pair-serving-epoch.md @@ -0,0 +1,11 @@ +### Two-Mac pairs recover after a lost rank + +- A two-Mac pair no longer stays unable to serve after it loses a rank, is + fenced, or has a request cancelled before it started. The leader released + its committed start only after the old pair slot had fully drained. When the + drain outlasted the session's own wait, the leader refused every later start + with "a committed start is already served" until the provider was restarted. +- The leader now releases a start as soon as its session ends, and an + unfinished serve of that start stands down without touching the next one. + The release receipt still waits for the slot to retire. A pair still never + serves two slots at once. diff --git a/docs/reference/cluster-control-protocol.md b/docs/reference/cluster-control-protocol.md index 7331c8e124..b7a9efd5ea 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. After a lost rank or a fence, the next committed start is served once the old slot has retired, even if a serve or the slot's drain outlasts the session's bounded wait. A start whose session already stopped is never served | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart` | **What a real member does in this build.** The installed owner (`darkbloom cluster worker-owner --stdio`) admits a start the coordinator diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift index 5f2fb22126..2709a0cc76 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift @@ -48,7 +48,8 @@ public protocol NativePairMemberServingHost: AnyObject, Sendable { func serveCommittedStart(_ start: NativePairMemberServingStart) async throws /// The session is ending: retire what `serveCommittedStart` published for /// this epoch (or stop a serve still under way) and return once it is - /// retired. Idempotent; an unknown epoch does nothing. + /// retired. The epoch is released at once, so a later start never waits + /// on this one's cleanup, and is never served afterwards. Idempotent. func stopServingCommittedStart(epoch: UUID) async } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift index 6163b503fd..732d6f10df 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift @@ -136,10 +136,13 @@ extension ProviderLoop: NativePairMemberServingHost { guard let context = clusterPairServing, start.rank == 0 else { throw ClusterPairSlotError.notServing("this member serves no committed start") } - guard clusterPairServingEpoch == nil else { throw ClusterPairSlotError.notServing("a committed start is already served") } let epoch = start.membershipEpoch - clusterPairServingEpoch = epoch; clusterPairServingStopped = false; clusterPairServingForming = true - defer { clusterPairServingForming = false } + // Its session's stop can reach this actor before its serve does. + guard epoch != clusterPairServingEndedEpoch else { + throw ClusterPairSlotError.notServing("the committed start already ended") + } + guard clusterPairServingEpoch == nil else { throw ClusterPairSlotError.notServing("a committed start is already served") } + clusterPairServingEpoch = epoch let owner: any DistributedResidentExecutionOwner do { owner = try await Task.detached { try context.makeOwner(start) }.value } catch { @@ -147,9 +150,10 @@ extension ProviderLoop: NativePairMemberServingHost { recordClusterPairIncident(.activationLaunchFailed, error: error, context: context, start: start) endClusterPairServing(epoch); throw error } - // A stop that arrived while the pair formed wins: nothing publishes. - guard clusterPairServingEpoch == epoch, !clusterPairServingStopped else { - await owner.shutdown(); endClusterPairServing(epoch) + // A stop that arrived while the pair formed wins: nothing publishes, + // and the next start may already hold the member. + guard clusterPairServingEpoch == epoch else { + await owner.shutdown() throw ClusterPairSlotError.notServing("the committed start ended while the pair formed") } let wire = start.identity @@ -169,25 +173,27 @@ extension ProviderLoop: NativePairMemberServingHost { modelDirectory: context.modelDirectory, pairTelemetry: telemetry) do { try await publishClusterPairSlot(specification, owner: owner) } catch { await owner.shutdown(); endClusterPairServing(epoch); throw error } - clusterPairServingForming = false // A stop during the publication hops retires what was just published. - if clusterPairServingStopped { await stopServingCommittedStart(epoch: epoch) } + if clusterPairServingEpoch != epoch { await retireCommittedStartSlot(epoch) } } public func stopServingCommittedStart(epoch: UUID) async { - guard clusterPairServingEpoch == epoch else { return } - clusterPairServingStopped = true - // The session sends its release receipt once this returns, so the - // slot retires first, even while the serve still forms the pair (its - // publication and warmup canary can take minutes). Retirement is - // idempotent and the publication stops at a retired slot. - if let handle = clusterPairSlot, handle.membershipEpoch == epoch { - await retireClusterPairSlot(handle.id, reason: "committed start ended") - } - // A serve still forming sees the stop and ends the start itself; - // ending it here would let the next start begin under it. - guard !clusterPairServingForming else { return } + // The start ends with its session, now: not when the slot's drain or + // a serve still under way ends, which can outlast the session's own + // bounded wait (its receipt then lets the coordinator commit the next + // start). A serve that lost its start stands down by itself. + clusterPairServingEndedEpoch = epoch endClusterPairServing(epoch) + // The session sends its release receipt once this returns, so every + // call waits until the slot retired, even while the serve still forms + // the pair (its publication and warmup canary can take minutes). + // Retirement is idempotent and the publication stops at a retired slot. + await retireCommittedStartSlot(epoch) + } + + private func retireCommittedStartSlot(_ epoch: UUID) async { + guard let handle = clusterPairSlot, handle.membershipEpoch == epoch else { return } + await retireClusterPairSlot(handle.id, reason: "committed start ended") } /// One incident about a committed start this leader serves (S24), with @@ -206,6 +212,6 @@ extension ProviderLoop: NativePairMemberServingHost { /// Clears the served epoch, once, for this epoch only. func endClusterPairServing(_ epoch: UUID) { guard clusterPairServingEpoch == epoch else { return } - clusterPairServingEpoch = nil; clusterPairServingStopped = false; clusterPairServingForming = false + clusterPairServingEpoch = nil } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 3d8265a633..fce440f8f8 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -725,13 +725,12 @@ public actor ProviderLoop { /// When the pair slot's engine was first seen wedged ("crashed"), for the /// supervisor's liveness guard (S18). internal var clusterPairWedgedSince: ContinuousClock.Instant? - /// The leader's serving context for committed starts (S10), and the one - /// start it serves: its epoch, whether the session asked it to stop, and - /// whether the pair is still forming. + /// The leader's serving context for committed starts (S10), the one + /// start it serves (held from its serve until its session's stop), and + /// the last start whose session stopped, which is never served after. internal var clusterPairServing: ClusterPairServingContext? internal var clusterPairServingEpoch: UUID? - internal var clusterPairServingStopped = false - internal var clusterPairServingForming = false + internal var clusterPairServingEndedEpoch: UUID? /// The follower member's link serving of its committed starts; retained /// here because the session control holds its serving host weakly. internal var clusterPairFollower: DistributedMemberLinkFollower? From 85feca41d6f1a2df095f0a998df0f077a4d86d30 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:27:08 -0800 Subject: [PATCH 26/58] cluster: regression tests for the pair engine's cancellation deadlock Mac B's member (production GLM pair, 2026-11-01) sampled 2,245 of 2,245 times in one stack: retireClusterPairSlot -> EngineV2Bridge.shutdown -> swift_task_cancelImpl (holding the pump task's status lock) -> the stream's onTermination in DistributedCBv2Engine.admit -> DispatchQueue.sync, while the engine queue, publishing the pair's peer loss to that pump (readyCapacity -> stop -> publishFailure -> yield), waited for the same lock. Both tests drive the real engine with a fabricated owner whose step on the engine queue can be held: - a readiness check holds the queue while the suspended consumer is cancelled and the owner invalidates; the check then reports the peer lost (the production cycle, through the stream's onTermination); - a refused reservation's release holds the queue while the submission waiting for its retirement is cancelled (the same lock order through the admission cancellation). Every wait is bounded and polled, so a deadlock fails the test instead of hanging the suite. Both fail on origin/master and pass with the fix. Co-Authored-By: Claude Opus 5.5 --- ...ributedCBv2CancellationDeadlockTests.swift | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift new file mode 100644 index 0000000000..4de08f43a6 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift @@ -0,0 +1,192 @@ +import Foundation +import MLXLMCommon +import Testing +@testable import ProviderCore + +/// Production, 2026-11-01: retiring a pair slot (`EngineV2Bridge.shutdown`) +/// cancelled a request's stream consumer while the engine queue published the +/// pair's peer loss to that consumer. Cancellation runs its handlers holding +/// the task's status lock; the stream's termination waited for the engine +/// queue, and the queue waited for that lock to resume the consumer. Every +/// wait here is bounded and polled, so a regression fails instead of hanging. +/// Fabricated owner only: no model, GPU or peer process. +@Suite(.timeLimit(.minutes(1))) +struct DistributedCBv2CancellationDeadlockTests { + @Test func cancellingAConsumerWhileItsPeerLossIsPublishedCannotDeadlock() async throws { + let owner = HeldReadinessOwner() + let engine = try DistributedCBv2Engine(owner: owner, expectedIdentity: owner.base.identity, + profile: distributedTestProfile(), detokenizers: DistributedTestDetokenizers()) + let stream = try engine.submit(distributedTestRequest(maxTokens: 8)) + let lease = owner.base.last + let probe = DeadlockProbe() + // The consumer (the bridge's pump) takes a token, then waits in the stream. + let consumer = Task { + var events = stream.makeAsyncIterator() + _ = await events.next() + probe.mark("first token") + while await events.next() != nil {} + probe.mark("consumer ended") + } + #expect(lease.send(.token(4))) + #expect(await probe.wait("first token", seconds: 5)) + try await Task.sleep(for: .milliseconds(200)) + + // The next token holds the engine queue in its readiness check, which + // then reports the peer lost: a failure published to the consumer. + let release = owner.holdNextReadiness(probe) + DispatchQueue.global().async { _ = lease.send(.token(5)); probe.mark("token returned") } + #expect(await probe.wait("queue held", seconds: 5)) + // Meanwhile the owner invalidates and the slot's retirement cancels the consumer. + DispatchQueue.global().async { owner.base.losePeer(); probe.mark("invalidation returned") } + DispatchQueue.global().async { consumer.cancel(); probe.mark("cancel returned") } + _ = await probe.wait("cancel returned", seconds: 1) + release.signal() + + var ended = true + for mark in ["cancel returned", "token returned", "invalidation returned", "consumer ended"] { + let reached = await probe.wait(mark, seconds: 5) + #expect(reached, "\(mark): the consumer's cancellation and the engine queue deadlocked") + ended = ended && reached + } + // A deadlocked engine is left as it is: its queue would hang the suite. + guard ended else { return } + #expect(lease.cancelCount == 1) // the peer loss took the failure path, once + lease.acknowledge() + await engine.shutdown() + #expect(lease.releaseCount == 1) + #expect(owner.base.shutdownCount == 1) + } + + /// The same lock order through the admission cancellation: a submission + /// that waits for its refused reservation's retirement is cancelled while + /// the engine queue retires it and resumes that submission. + @Test func cancellingASubmissionWhileItsRetirementResumesItCannotDeadlock() async throws { + let owner = HeldReadinessOwner() + let clock = DistributedTestClock() + let engine = try DistributedCBv2Engine(owner: owner, expectedIdentity: owner.base.identity, + profile: distributedTestProfile(), detokenizers: DistributedTestDetokenizers(), clock: clock.clock) + owner.base.onReserve = { clock.advance(.seconds(5)) } // refused after reserve: the deadline passed + let probe = DeadlockProbe() + let submission = Task { + _ = try? await engine.submit(distributedTestRequest(), + firstTokenDeadline: distributedTestDeadline(clock.now.advanced(by: .seconds(3)))) + probe.mark("submission ended") + } + let end = ContinuousClock.now.advanced(by: .seconds(5)) + while (owner.base.reserveCount == 0 || owner.base.last.cancelCount == 0) && ContinuousClock.now < end { + try await Task.sleep(for: .milliseconds(5)) + } + let lease = owner.base.last + #expect(lease.cancelCount == 1) + try await Task.sleep(for: .milliseconds(200)) // the submission now waits for the retirement + + // The retirement holds the engine queue while it releases the + // reservation, then resumes the submission; the caller cancels meanwhile. + let release = owner.holdNextRelease(probe) + lease.acknowledge() + #expect(await probe.wait("queue held", seconds: 5)) + DispatchQueue.global().async { submission.cancel(); probe.mark("cancel returned") } + _ = await probe.wait("cancel returned", seconds: 1) + release.signal() + + var ended = true + for mark in ["cancel returned", "submission ended"] { + let reached = await probe.wait(mark, seconds: 5) + #expect(reached, "\(mark): the submission's cancellation and the engine queue deadlocked") + ended = ended && reached + } + guard ended else { return } + #expect(lease.releaseCount == 1) + #expect(lease.startCount == 0) + await engine.shutdown() + #expect(owner.base.shutdownCount == 1) + } +} + +/// Marks set from any thread, awaited by polling: no cooperative thread ever +/// waits on a queue that may be deadlocked. +private final class DeadlockProbe: @unchecked Sendable { + private let lock = NSLock() + private var marks = Set() + + func mark(_ name: String) { _ = lock.withLock { marks.insert(name) } } + + func wait(_ name: String, seconds: Double) async -> Bool { + let end = ContinuousClock.now.advanced(by: .milliseconds(Int(seconds * 1000))) + while !lock.withLock({ marks.contains(name) }) && ContinuousClock.now < end { + try? await Task.sleep(for: .milliseconds(5)) + } + return lock.withLock { marks.contains(name) } + } +} + +/// One held step: it marks the probe, then waits (bounded) for the test. +private final class HeldStep: @unchecked Sendable { + private let lock = NSLock() + private var next: (probe: DeadlockProbe, release: DispatchSemaphore)? + + func arm(_ probe: DeadlockProbe) -> DispatchSemaphore { + let release = DispatchSemaphore(value: 0) + lock.withLock { next = (probe, release) } + return release + } + + /// True when this call was the held one. + func pass() -> Bool { + let held = lock.withLock { () -> (probe: DeadlockProbe, release: DispatchSemaphore)? in + defer { next = nil } + return next + } + guard let held else { return false } + held.probe.mark("queue held") + _ = held.release.wait(timeout: .now() + 30) + return true + } +} + +/// The fabricated owner with one step held where the engine calls it on its +/// queue: a readiness check (`readyCapacity`), which then reports the peer +/// lost, or a reservation's release (`retire`). +private final class HeldReadinessOwner: DistributedResidentExecutionOwner, @unchecked Sendable { + let base = DistributedTestOwner() + private let readinessStep = HeldStep() + private let releaseStep = HeldStep() + + func holdNextReadiness(_ probe: DeadlockProbe) -> DispatchSemaphore { readinessStep.arm(probe) } + func holdNextRelease(_ probe: DeadlockProbe) -> DispatchSemaphore { releaseStep.arm(probe) } + + func readiness() -> DistributedResidentReadiness? { + if readinessStep.pass() { base.losePeer(notify: false) } + return base.readiness() + } + func setReadinessInvalidationHandler(_ handler: @escaping @Sendable () -> Void) { + base.setReadinessInvalidationHandler(handler) + } + func projectFirstToken(_ request: CBv2Request, admission: CBv2FirstTokenDeadlineAdmission) -> CBv2FirstTokenProjectedWork { + base.projectFirstToken(request, admission: admission) + } + func reserve(_ request: CBv2Request, identity: DistributedResidentIdentity, + profileID: String, capacityLimit: Int) throws -> any DistributedResidentRequestLease { + HeldReleaseLease(try base.reserve(request, identity: identity, profileID: profileID, + capacityLimit: capacityLimit), release: releaseStep) + } + func shutdown() async { await base.shutdown() } +} + +/// The fabricated lease, its release held when the owner armed it. +private final class HeldReleaseLease: DistributedResidentRequestLease, @unchecked Sendable { + private let inner: any DistributedResidentRequestLease + private let release: HeldStep + + init(_ inner: any DistributedResidentRequestLease, release: HeldStep) { self.inner = inner; self.release = release } + + var identity: DistributedResidentIdentity { inner.identity } + var requestID: CBv2RequestID { inner.requestID } + var reservedBytes: Int { inner.reservedBytes } + var bytesInUse: Int { inner.bytesInUse } + func start(emit: @escaping @Sendable (DistributedResidentEvent) -> Bool) throws { try inner.start(emit: emit) } + func cancel() { inner.cancel() } + func requestCleanStop() -> Bool { inner.requestCleanStop() } + func waitUntilRetired() async { await inner.waitUntilRetired() } + func releaseResources() { _ = release.pass(); inner.releaseResources() } +} From d062a1b3d9ddc29f312782303e273c94bbb8e74f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:27:27 -0800 Subject: [PATCH 27/58] cluster: never wait for the pair engine's queue from a cancellation DistributedCBv2Engine ran three closures from task cancellation or from a detached task with a blocking DispatchQueue.sync onto its serial queue: - the request stream's onTermination, which AsyncStream runs from the consumer task's cancellation handler, holding that task's status lock; - the admission cancellation armed in admit, run from submit's withTaskCancellationHandler, under the same kind of lock; - the retirement task, which blocked a cooperative thread. The engine queue in turn resumes those tasks (every stream yield and the retirement latch), which needs the task's status lock. When a pair slot retired (EngineV2Bridge.shutdown cancelling its pumps) while the queue published the pair's peer loss to the same pump, each side held what the other waited for, and the retirement never ended. onQueueWithoutWaiting runs inline on the queue (so a cancellation consumed during reserve still stops the request before it starts) and otherwise hops with queue.async. The retirement task hops with queue.async. Event delivery (the lease's emit), the owner's invalidation and the public calls keep their synchronous queue order. Two engine tests that read the result of a termination right after it now flush the queue first. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-serving-epoch.md | 17 ++++++++++------- docs/architecture/inference.md | 16 +++++++++++++++- docs/reference/cluster-control-protocol.md | 2 +- .../DistributedCBv2Engine+Admission.swift | 14 +++++++++----- .../Engine/DistributedCBv2Engine.swift | 8 ++++++++ .../DistributedCBv2DeadlineTests.swift | 1 + .../DistributedCBv2EngineTests.swift | 1 + 7 files changed, 45 insertions(+), 14 deletions(-) diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md index 1c3ce62979..54506e12e1 100644 --- a/changelog.d/cluster-pair-serving-epoch.md +++ b/changelog.d/cluster-pair-serving-epoch.md @@ -1,11 +1,14 @@ ### Two-Mac pairs recover after a lost rank - A two-Mac pair no longer stays unable to serve after it loses a rank, is - fenced, or has a request cancelled before it started. The leader released - its committed start only after the old pair slot had fully drained. When the - drain outlasted the session's own wait, the leader refused every later start - with "a committed start is already served" until the provider was restarted. -- The leader now releases a start as soon as its session ends, and an - unfinished serve of that start stands down without touching the next one. - The release receipt still waits for the slot to retire. A pair still never + fenced, or has a request cancelled before it started. +- 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 every later start with "a committed start is already served". + The release receipt still waits for the slot to retire, and a pair still never serves two slots at once. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..f8a2eea150 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 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. diff --git a/docs/reference/cluster-control-protocol.md b/docs/reference/cluster-control-protocol.md index b7a9efd5ea..64ebe8c2d5 100644 --- a/docs/reference/cluster-control-protocol.md +++ b/docs/reference/cluster-control-protocol.md @@ -204,7 +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. After a lost rank or a fence, the next committed start is served once the old slot has retired, even if a serve or the slot's drain outlasts the session's bounded wait. A start whose session already stopped is never served | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart` | +| 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. After a lost rank or a fence, the next committed start is served once the old slot has retired, even if a serve or the slot's drain outlasts the session's bounded wait. A start whose session already stopped is never served. The slot's engine never waits for its queue from a cancellation or a stream's termination, so cancelling a request while its peer loss is published cannot deadlock the retirement | `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/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift index d4478d00ae..edcf91c9d2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift @@ -44,21 +44,25 @@ extension DistributedCBv2Engine { admissionStartedAt: admissionStartedAt, reservedAt: clock.now()) actives[state.generation] = state observe(state, phase: .reserved) + // Both run from task cancellation: they never wait for the queue (a + // cancellation already consumed here, during reserve, still runs at once). cancellation?.arm { [weak self, weak state] in guard let self, let state else { return } - self.onQueue { self.stop(state, reason: .cancelled) } + self.onQueueWithoutWaiting { self.stop(state, reason: .cancelled) } } continuation.onTermination = { [weak self, generation = state.generation] _ in - self?.onQueue { - guard self?.actives[generation] != nil else { return } - self?.stop(state, reason: .cancelled) + guard let self else { return } + self.onQueueWithoutWaiting { + guard self.actives[generation] != nil else { return } + self.stop(state, reason: .cancelled) } } // Always retain the engine and lease until acknowledgement, even if the // consumer drops the stream or the owner throws after partially starting. + // A cooperative thread never waits for the queue. Task { [self, state] in await state.lease.waitUntilRetired() - onQueue { retire(state) } + queue.async { [self] in retire(state) } } var refused = false let admittedAt = clock.now() diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift index 8171ad022c..88ae9490f5 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift @@ -74,6 +74,14 @@ public final class DistributedCBv2Engine: CBv2Engine, @unchecked Sendable { return try queue.sync(execute: body) } + /// `onQueue` for a caller that must never wait for the queue: a task's + /// cancellation handler, and a stream's termination that cancellation runs. + /// Those run holding the task's status lock, which the queue needs to resume + /// that task (every `yield` to its stream): waiting here deadlocked both. + func onQueueWithoutWaiting(_ body: @escaping @Sendable () -> Void) { + if DispatchQueue.getSpecific(key: queueKey) != nil { body() } else { queue.async(execute: body) } + } + public func cancel(_ id: CBv2RequestID) { onQueue { guard let state = actives.values.first(where: { $0.request.id == id }) else { return } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift index ee222dadbe..cb29c6e22c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift @@ -200,6 +200,7 @@ struct DistributedCBv2DeadlineTests { _ = await distributedCollect(first) let second = try engine.submit(distributedTestRequest(maxTokens: 1)) oldTermination?(.cancelled) + engine.onQueue {} // the termination reaches the queue without waiting for it #expect(owner.last.cancelCount == 0) owner.last.send(.token(5)) owner.last.acknowledge() diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift index c3444e20ef..e6710ecbe7 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift @@ -392,6 +392,7 @@ struct DistributedCBv2EngineTests { let consumer = Task { await distributedCollect(stream) } consumer.cancel() _ = await consumer.value + engine.onQueue {} // the stream's termination reaches the queue without waiting for it #expect(owner.last.cancelCount == 1) #expect(owner.last.releaseCount == 0) #expect(engine.capacity().activeRequests == 1) From 0124b7fa3db24b02788e8dc5827e49ddab71e1f9 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:03:35 -0800 Subject: [PATCH 28/58] cluster: make the pair serving fix's docs and comments precise Refactor pass over the cancellation-deadlock and serving-epoch fix. No behavior change: comments, one reference row and the changelog fragment. - Changelog: name the condition a pair could not recover from (it lost a rank while its slot was stopping) and what the operator saw, instead of implying every lost rank, fence or cancelled request left it stuck. - cluster-control-protocol: the next committed start is accepted while the old slot retires, but its slot cannot publish until then (the row read as if the start waited for it). The engine's queue invariant now links its one home in architecture/inference.md instead of restating it. - NativePairMemberServingHost.stopServingCommittedStart: a later start can begin during the retirement; it no longer says the start never waits. - onQueueWithoutWaiting: the queue resumes those tasks through a stream yield or their retirement, so waiting can deadlock. - stopServingCommittedStart: the retirement closes the slot's admission before it suspends, so a released start never admits work. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-serving-epoch.md | 14 ++++++++------ docs/reference/cluster-control-protocol.md | 2 +- .../Coordinator/NativePairMemberServing.swift | 4 ++-- .../Distributed/Engine/DistributedCBv2Engine.swift | 6 +++--- .../ProviderLoop+ClusterPairServing.swift | 3 ++- 5 files changed, 16 insertions(+), 13 deletions(-) diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md index 54506e12e1..c267c91d93 100644 --- a/changelog.d/cluster-pair-serving-epoch.md +++ b/changelog.d/cluster-pair-serving-epoch.md @@ -1,7 +1,9 @@ -### Two-Mac pairs recover after a lost rank +### Two-Mac pairs recover after losing a rank during a stop -- A two-Mac pair no longer stays unable to serve after it loses a rank, is - fenced, or has a request cancelled before it started. +- 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 @@ -9,6 +11,6 @@ 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 every later start with "a committed start is already served". - The release receipt still waits for the slot to retire, and a pair still never - serves two slots at once. + 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/docs/reference/cluster-control-protocol.md b/docs/reference/cluster-control-protocol.md index 64ebe8c2d5..6c5ad44d4f 100644 --- a/docs/reference/cluster-control-protocol.md +++ b/docs/reference/cluster-control-protocol.md @@ -204,7 +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. After a lost rank or a fence, the next committed start is served once the old slot has retired, even if a serve or the slot's drain outlasts the session's bounded wait. A start whose session already stopped is never served. The slot's engine never waits for its queue from a cancellation or a stream's termination, so cancelling a request while its peer loss is published cannot deadlock the retirement | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift`, `onQueueWithoutWaiting` | +| 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/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift index 2709a0cc76..3740de188d 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift @@ -48,8 +48,8 @@ public protocol NativePairMemberServingHost: AnyObject, Sendable { func serveCommittedStart(_ start: NativePairMemberServingStart) async throws /// The session is ending: retire what `serveCommittedStart` published for /// this epoch (or stop a serve still under way) and return once it is - /// retired. The epoch is released at once, so a later start never waits - /// on this one's cleanup, and is never served afterwards. Idempotent. + /// retired. The epoch is released at once, so a later start can begin + /// during that retirement, and is never served afterwards. Idempotent. func stopServingCommittedStart(epoch: UUID) async } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift index 88ae9490f5..62c71a93e2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift @@ -75,9 +75,9 @@ public final class DistributedCBv2Engine: CBv2Engine, @unchecked Sendable { } /// `onQueue` for a caller that must never wait for the queue: a task's - /// cancellation handler, and a stream's termination that cancellation runs. - /// Those run holding the task's status lock, which the queue needs to resume - /// that task (every `yield` to its stream): waiting here deadlocked both. + /// cancellation handler, or a stream's termination that cancellation runs. + /// Those hold the task's status lock, which the queue needs to resume that + /// task (a `yield` to its stream, its retirement), so waiting can deadlock. func onQueueWithoutWaiting(_ body: @escaping @Sendable () -> Void) { if DispatchQueue.getSpecific(key: queueKey) != nil { body() } else { queue.async(execute: body) } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift index 732d6f10df..f46e6bc827 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift @@ -181,7 +181,8 @@ extension ProviderLoop: NativePairMemberServingHost { // The start ends with its session, now: not when the slot's drain or // a serve still under way ends, which can outlast the session's own // bounded wait (its receipt then lets the coordinator commit the next - // start). A serve that lost its start stands down by itself. + // start). A serve that lost its start stands down by itself, and the + // retirement below closes the slot's admission before it suspends. clusterPairServingEndedEpoch = epoch endClusterPairServing(epoch) // The session sends its release receipt once this returns, so every From b749184e0ea815a685bae6019c2693509fd9701d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:04:21 -0800 Subject: [PATCH 29/58] Save a Qwen tensor-parallel pair's widest admitted width at placement The guided setup now reads the owner's complete LOAD quote at widths 2, 4, 6 and 8 and saves, on both Macs, the widest at which the chosen placement (leader and split unchanged) fits both Macs now under that width's quote: the predicate an automatic replacement is held to. The pair then serves concurrent requests from its first load. A local pair no longer waits for a drained replacement, and a pair saved for coordinator pairing, which never widens after approval, no longer serves a burst one request at a time. - ClusterPlacementTensorBatchQuote.applyWidth prices a width's quote in place of the singleton's, for the same request envelope, chunk and assistant. - ClusterPlacementTensorWidth re-plans the chosen placement at 8, 6, 4 and 2; ClusterPlacementFlow.decide saves the width it finds and reports its memory. - The replacement's predicate is ClusterPlacementCandidate.admitted for both; DistributedAutomaticBatchFactory.replacementWidths proposes only widths wider than the running one. - LOAD quotes, measured floors and live admission are unchanged. No approval, roster, committed-start or runtime-facts digest names the width; only each Mac's saved setup does. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-default-lanes.md | 19 ++ docs/architecture/hardware-support.md | 7 +- docs/architecture/inference.md | 79 +++++- docs/reference/configuration.md | 10 +- .../ClusterPlacementTensorBatchQuote.swift | 17 ++ .../ClusterSetupWizardLiveOperations.swift | 36 ++- .../Console/ClusterSetupWizardPlanning.swift | 15 +- .../Installed/DistributedInstalledPlan.swift | 10 +- .../DistributedAutomaticBatchFactory.swift | 28 +- .../DistributedAutomaticBatchPlanner.swift | 6 +- .../Placement/ClusterPlacementFlow.swift | 15 +- .../ClusterPlacementTensorWidth.swift | 49 ++++ .../Tests/ClusterPlacementChecks/run.sh | 1 + .../ClusterApprovalFixture.swift | 8 +- ...rPlacementTensorWidthRegisteredTests.swift | 173 ++++++++++++ .../ClusterPlacementTensorWidthTests.swift | 256 ++++++++++++++++++ 16 files changed, 676 insertions(+), 53 deletions(-) create mode 100644 changelog.d/qwen27-tp-default-lanes.md create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthRegisteredTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift diff --git a/changelog.d/qwen27-tp-default-lanes.md b/changelog.d/qwen27-tp-default-lanes.md new file mode 100644 index 0000000000..5195f462ab --- /dev/null +++ b/changelog.d/qwen27-tp-default-lanes.md @@ -0,0 +1,19 @@ +### Qwen tensor-parallel pairs serve concurrent requests from their first load + +- The guided cluster setup now saves a width for a Qwen tensor-parallel pair: + the widest of 8, 6, 4 and 2 concurrent requests that both Macs admit now under + that width's complete load quote. The pair serves that many requests at once + from its first load. Before, it served one: a local pair widened only after a + burst, through a drained reload that the burst waited for, and a pair served + through Darkbloom never widened. +- On two idle Macs, Qwen3.8-27B without the speculative assistant saves 8 from + 48 GB a Mac (4 at 32 or 36 GB). With the assistant, which serves local + clusters only, it saves 8 from 96 GB a Mac and less on smaller Macs. When no + width fits, the setup serves one request at a time as before. +- Memory safety is unchanged: both Macs still reserve the saved width's whole + quote at load and admit each request alone. A local pair planned narrower + still widens under queued demand; a pair saved at 8 is never reloaded for it. +- A pair served through Darkbloom keeps its saved width beside its approval. No + approval, registration or committed-start digest changes. Existing setups keep + their saved bytes and their one-request width until they are planned again, + as after an update. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index c91f96c2e6..a5f083e70e 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-10-31 +> Last updated: 2026-11-01 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 @@ -1193,7 +1193,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 a6bf854a24..8c6d490eed 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -77,7 +77,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, @@ -5014,8 +5017,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 @@ -5124,8 +5128,8 @@ every selected token is unchanged. 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 @@ -5187,6 +5191,71 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Ten `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. 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 | 4 | 1 | +| 36 GiB | 4 | 2 | +| 48 GiB | 8 | 4 | +| 64 GiB | 8 | 6 | +| 96 GiB and larger | 8 | 8 | + +At eight lanes, each rank of an equal split reserves 28,555,198,464 bytes at +LOAD without the assistant and 48,378,347,520 bytes with it; with its weights +and loading headroom it needs 42,084,887,040 and 65,642,146,304 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`). + ### Qwen27 tensor-parallel native context The registered Qwen3.8 27B row advertises the limits the single-Mac product diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 0aa1e29379..f079a77953 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Provider CLI and native-runtime environment variables, compiled defaults and reading symbols. Secrets are named, never valued. Unless specified otherwise, values are read at process start. @@ -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 saves it on both Macs for a Qwen TP placement: the widest of 8, 6, 4 and 2 both Macs admit now under that width's complete LOAD quote, omitted when none does. A setup saved for coordinator pairing keeps it unchanged 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,8 @@ 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 asks for the quote at each of these widths and saves +the widest both Macs admit now. GLM defaults remain unchanged. Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift`. ### Qwen27 saved mode compatibility 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/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift index be47f2ab48..7d01fac55a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift @@ -595,7 +595,7 @@ final class LiveContext: @unchecked Sendable { let manifest = ClusterSetupModelFolders.readManifest(directory.appendingPathComponent("manifest.json")) ?? Data() let assistantQuote: Result? var targetFallback: Result? = nil - var discoveredWidening: ClusterPlacementTensorBatchQuote?, fallbackWidening: ClusterPlacementTensorBatchQuote? + var discoveredWidths: [ClusterPlacementTensorBatchQuote] = [], fallbackWidths: [ClusterPlacementTensorBatchQuote] = [] if !settings.privateImageQualification, case .success(let admittedValue) = capability, ClusterPlacementTensorBatchQuote.runtimeModelIDs.contains(admittedValue.record.runtimeModelID) { @@ -605,6 +605,17 @@ final class LiveContext: @unchecked Sendable { ? ClusterPlacementRequestLimits.chunkTokens(runtimeModelID: admitted.runtimeModelID, artifactSHA256: admitted.artifactSHA256, layoutMaximum: measured.maximumChunkTokens, capabilityMaximum: admitted.profile.maximumChunkTokens).tokens : description.chunkTokens + // The same owner's complete quote at every wider width, each of the singleton's own request and + // assistant: the plan saves the widest both Macs admit now, and the two-lane one also steers the + // retained split (capacity changes keep the shares). A width the helper does not quote is not offered. + func widths(of singleton: ClusterPlacementTensorBatchQuote?, mode: MTPMode) -> [ClusterPlacementTensorBatchQuote] { + guard let singleton else { return [] } + return ClusterPlacementBatchScope.tensorParallelWidths.compactMap { lanes in + try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory, + publicModelID: model.modelID, capability: admitted, mode: mode, chunkTokens: chunk, + deadline: deadline(), lanes: lanes) + }.filter { $0.request == singleton.request && $0.assistant?.policy == singleton.assistant?.policy } + } if mtpMode != .off, SpecDecArtifactFunnel.killSwitchEnabled(environment: ProcessInfo.processInfo.environment), let policy = settings.tensorAssistants[model.modelID] { assistantQuote = .success(try ClusterPlacementTensorAssistantSelection.read(tool: tool, @@ -617,31 +628,26 @@ final class LiveContext: @unchecked Sendable { modelDirectory: directory, publicModelID: model.modelID, capability: admitted, mode: discovery, chunkTokens: chunk, deadline: deadline()) assistantQuote = discovered.map { .success($0) } - // Capacity changes keep the shares, so the first widening's complete - // quote steers the initial split; without it the choice is speed-only. - if discovered != nil { - discoveredWidening = try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, - modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: discovery, chunkTokens: chunk, deadline: deadline(), lanes: 2) - } + discoveredWidths = widths(of: discovered, mode: discovery) // Only a discovered assistant may give way to the ordinary target (`assistantOrTarget`). if discovered?.assistant != nil { + var target: ClusterPlacementTensorBatchQuote? do { - targetFallback = try ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, + target = try ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: .off, chunkTokens: chunk, deadline: deadline()).map { .success($0) } + mode: .off, chunkTokens: chunk, deadline: deadline()) + targetFallback = target.map { .success($0) } } catch { targetFallback = .failure(ClusterSetupFailure(error)) } - fallbackWidening = try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, - modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: .off, chunkTokens: chunk, deadline: deadline(), lanes: 2) + fallbackWidths = widths(of: target, mode: .off) } } } catch { assistantQuote = .failure(ClusterSetupFailure(error)) } } else { assistantQuote = nil } return .init(model: model, layout: layout, capability: capability, tokenizerFiles: ClusterSetupPlanning.tokenizerFiles(manifest: manifest), tensorAssistantQuote: assistantQuote, - targetFallbackQuote: targetFallback, tensorWideningQuote: discoveredWidening, - targetFallbackWideningQuote: fallbackWidening) + targetFallbackQuote: targetFallback, tensorWideningQuote: discoveredWidths.first { $0.lanes == 2 }, + targetFallbackWideningQuote: fallbackWidths.first { $0.lanes == 2 }, + tensorWidthQuotes: discoveredWidths, targetFallbackWidthQuotes: fallbackWidths) } // The profiles are kept for the serving leader's per-request route; the speed // records of requests this pair served join the measurements (the next plan). diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift index 111da1b1df..166037f442 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift @@ -26,6 +26,10 @@ enum ClusterSetupPlanning { /// the retained split. Absent, the split is chosen by speed alone. var tensorWideningQuote: ClusterPlacementTensorBatchQuote? = nil var targetFallbackWideningQuote: ClusterPlacementTensorBatchQuote? = nil + /// The same owners' complete quotes at the wider widths: the setup + /// saves the widest both Macs admit now (`ClusterPlacementTensorWidth`). + var tensorWidthQuotes: [ClusterPlacementTensorBatchQuote] = [] + var targetFallbackWidthQuotes: [ClusterPlacementTensorBatchQuote] = [] } typealias PlacementDecision = (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?) @@ -143,12 +147,15 @@ enum ClusterSetupPlanning { func widening(_ quote: ClusterPlacementTensorBatchQuote?) -> ClusterPlacementTensorBatchQuote? { quote == nil ? nil : quote == discovered ? reading.tensorWideningQuote : reading.targetFallbackWideningQuote } + func widths(_ quote: ClusterPlacementTensorBatchQuote?) -> [ClusterPlacementTensorBatchQuote] { + quote == nil ? [] : quote == discovered ? reading.tensorWidthQuotes : reading.targetFallbackWidthQuotes + } let selected = try assistantOrTarget(discovered, fallback: try? reading.targetFallbackQuote?.get()) { quote in try ClusterPlacementFlow.decide(description: pair, capability: capability.record, localMemberID: localMemberID, localProfile: localProfile, peerProfile: peerProfile, layout: layout, measurements: measurements, - tensorAssistantQuote: quote, tensorWideningQuote: widening(quote), leader: sessionLeader, - served: served, link: link, shareProbes: probes, incumbentMode: incumbent) + tensorAssistantQuote: quote, tensorWideningQuote: widening(quote), tensorWidthQuotes: widths(quote), + leader: sessionLeader, served: served, link: link, shareProbes: probes, incumbentMode: incumbent) } var decided = selected.decision let assistantQuote = selected.quote, fellBack = discovered != nil && selected.quote != discovered @@ -157,8 +164,8 @@ enum ClusterSetupPlanning { decided = try ClusterPlacementFlow.decide(description: pair.withPorts(.conventional), capability: capability.record, localMemberID: localMemberID, localProfile: localProfile, peerProfile: peerProfile, layout: layout, measurements: measurements, tensorAssistantQuote: assistantQuote, - tensorWideningQuote: widening(assistantQuote), leader: sessionLeader, - served: served, link: link, shareProbes: probes, incumbentMode: incumbent) + tensorWideningQuote: widening(assistantQuote), tensorWidthQuotes: widths(assistantQuote), + leader: sessionLeader, served: served, link: link, shareProbes: probes, incumbentMode: incumbent) if fellBack { decided.lines = [assistantDoesNotFit] + decided.lines } } guard let chosen = decided.result.chosen else { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift index 6369d1c732..1d15f04ad0 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift @@ -315,8 +315,10 @@ struct DistributedInstalledPlan: Sendable { /// - Pipeline: the lane adapters (`laneAdapters`), text only, at /// `defaultBatchLanes`. /// - Qwen tensor parallel (every registered TP row, dense or routed - /// experts): one by default; a priced saved width or explicit local - /// diagnostic may select its native 2...8 lane owner. + /// experts): one for a setup saved without a width. Guided placement + /// saves the widest width both Macs admit now under its LOAD quote + /// (`ClusterPlacementTensorWidth`); that saved width or an explicit + /// local diagnostic selects the native 2...8 lane owner. /// - Other tensor parallel: GLM (`GLM5NextTensorParallelResidentRuntime`'s lane /// loop), at `tensorParallelBatchLanes`. Each lane keeps its request's /// own arithmetic, so a request's tokens are those it gets alone. A @@ -346,7 +348,9 @@ struct DistributedInstalledPlan: Sendable { /// API's queue. The default stays one while the repaired joining and /// cancellation paths undergo model-specific multi-lane qualification. /// Earlier pair measurements (Qwen 3.5 35B A3B, 2026-10-19) preceded - /// those repairs and do not qualify the current loop. + /// those repairs and do not qualify the current loop. A Qwen TP width is + /// saved at placement instead, priced by the owner's LOAD quote; a + /// default here would be held to no quote. static let defaultBatchLanes = 1 /// Concurrent requests GLM tensor parallel serves by default: the /// protocol's lane cap (`ClusterWorkerLaneSession`, `ClusterWorkerPair`). diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchFactory.swift index a5acf743fa..28b3b6ceaa 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchFactory.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchFactory.swift @@ -4,9 +4,11 @@ import DarkbloomClusterPlacement import DarkbloomClusterProtocol import DarkbloomClusterProcess -/// The local API's same-model scaling policy. Initial singleton placement is -/// unchanged. Only queued demand can propose a separately priced native batch; -/// every side effect remains inside the host's deferred post-release factory. +/// The local API's same-model scaling policy. Only queued demand can propose a +/// separately priced native batch wider than the running one; every side effect +/// remains inside the host's deferred post-release factory. A Qwen TP setup is +/// planned at the widest width both Macs admit now (`ClusterPlacementTensorWidth`), +/// so this is the fallback for a pair planned narrower. public actor DistributedAutomaticBatchFactory { private let providerConfiguration: URL private let paths: ClusterUserPaths @@ -25,19 +27,15 @@ public actor DistributedAutomaticBatchFactory { public func replacement(for demand: DistributedLocalBatchDemand) async throws -> DistributedLocalBatchReplacement? { // An explicit diagnostic choice keeps its meaning. This path never // changes an installed coordinator-approved native member contract. + let widths = Self.replacementWidths(for: demand) guard environment[DistributedInstalledPlan.batchLanesSwitch] == nil, environment[ClusterForcedModeSetting.environmentName] == nil, environment[ClusterHandOffModes.environmentName] == nil, - demand.waitingRequests > 0, demand.currentCapacity < 8, + !widths.isEmpty, let adapter = ClusterRuntimeAdapter.registering(runtimeModelID: demand.runtimeModelID), [.qwen35Dense, .qwen35RoutedExperts, .qwen35PrismHadamard, .nemotronH, .gemma4LayerStage, .gptossLayerStage, .mimoV26LayerStage].contains(adapter), let child = ClusterService.publishedLive()?.child, - child.running, child.pid == getpid(), child.configurationSHA256 != nil else { return nil } - let total = min(8, max(0, demand.activeRequests)) + min(8, demand.waitingRequests) - let widths = ClusterPlacementBatchScope.candidateWidths(waitingRequests: total, - tensorParallel: ClusterPlacementTensorBatchQuote.runtimeModelIDs.contains(demand.runtimeModelID)) - .filter { $0 > demand.currentCapacity } - guard !widths.isEmpty, attempts.begin() else { return nil } + child.running, child.pid == getpid(), child.configurationSHA256 != nil, attempts.begin() else { return nil } let planner = DistributedAutomaticBatchPlanner(providerConfiguration: providerConfiguration, paths: paths) let reference = try ClusterConfigurationStore.installedReference(providerConfiguration: providerConfiguration) guard child.configurationSHA256 == reference.sha256 else { return nil } @@ -65,6 +63,16 @@ public actor DistributedAutomaticBatchFactory { makeSession: { try await transition.prepareReplacement() }, restorePreviousSession: { try await transition.restorePrevious() }) } + + /// The widths queued demand may propose, widest first: only wider than the running capacity, so a pair whose + /// placement saved its widest admitted width is never drained for a width it already serves. + static func replacementWidths(for demand: DistributedLocalBatchDemand) -> [Int] { + guard demand.waitingRequests > 0, demand.currentCapacity < 8 else { return [] } + let total = min(8, max(0, demand.activeRequests)) + min(8, demand.waitingRequests) + return ClusterPlacementBatchScope.candidateWidths(waitingRequests: total, + tensorParallel: ClusterPlacementTensorBatchQuote.runtimeModelIDs.contains(demand.runtimeModelID)) + .filter { $0 > demand.currentCapacity } + } } /// Pair-control adoption after native release. The host serializes these two diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchPlanner.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchPlanner.swift index ece6f476af..4aae29cf23 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchPlanner.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/DistributedAutomaticBatchPlanner.swift @@ -61,11 +61,11 @@ struct DistributedAutomaticBatchPlanner { /// An automatic replacement cannot promise that unrelated memory will /// disappear. A present-fit preview uses the same bilateral predicate as - /// the mandatory post-release recheck; hardware possibility alone is not + /// the mandatory post-release recheck and a saved width at placement + /// (`ClusterPlacementTensorWidth`); hardware possibility alone is not /// current admission. static func accepts(_ candidate: ClusterPlacementCandidate, requireNow: Bool) -> Bool { - candidate.possible && candidate.withinGPUWorkingSet - && (!requireNow || candidate.ranks.allSatisfy { $0.fit == .now }) + candidate.admitted(requireNow: requireNow) } /// Preview only, for a request-owned TP owner whose replacement keeps its diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift index 4464993892..086fd21480 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift @@ -60,6 +60,7 @@ public enum ClusterPlacementFlow { batchScope: ClusterPlacementBatchScope? = nil, tensorAssistantQuote: ClusterPlacementTensorBatchQuote? = nil, tensorWideningQuote: ClusterPlacementTensorBatchQuote? = nil, + tensorWidthQuotes: [ClusterPlacementTensorBatchQuote] = [], regime: ClusterPlacementPolicy.Regime = .rested, leader: String? = nil, served: [ClusterServedSpeedRecords.Entry] = [], link: ClusterLinkCosts = .unmeasured, @@ -275,7 +276,13 @@ public enum ClusterPlacementFlow { policy.modesReason = policy.modesReason ?? "a capacity change keeps the running tensor-parallel shares" policy.requiredTensorShares = incumbentTensorShares } - let result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link) + var result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link) + // A singleton tensor placement saves the widest width its owner's quotes admit on both Macs now. + var batchLanes = batchScope?.lanes + if batchScope == nil, tensorAssistantQuote != nil, !tensorWidthQuotes.isEmpty { + try ClusterPlacementTensorWidth.size(&result, lanes: &batchLanes, quotes: tensorWidthQuotes, + devices: devices, layout: layout, policy: policy, link: link) + } var lines = (forced.map(ClusterForcedModeSetting.lines) ?? []) + (benchCap.map(ClusterPlannerBenchCap.lines(capBytes:)) ?? []) + (benchChip.map(ClusterBenchChip.lines(chipName:)) ?? []) + servedLines @@ -299,8 +306,8 @@ public enum ClusterPlacementFlow { + "This pair's own figure replaces it once the pair has served the same placement both with and without the rounds.") } if let note = granted.note { lines.append("Pair serving"); lines.append(" " + note) } - if let batchScope { - lines += ["Concurrent request memory", " \(batchScope.lanes) independent histories, charged at the quoted request bound on both Macs. Stage-rate predictions remain single-request estimates; no batch speed is inferred from the lane count."] + if let batchLanes { + lines += ["Concurrent request memory", " \(batchLanes) independent histories, charged at the quoted request bound on both Macs. Stage-rate predictions remain single-request estimates; no batch speed is inferred from the lane count."] } if records.restrictsShapes { lines.append("Diverged placements") @@ -330,7 +337,7 @@ public enum ClusterPlacementFlow { lines.append(" Request deadline " + deadline.basis + ".") } let value = try ClusterPlacementSetup.synthesize(description: described, capability: capability, - chosen: chosen, batchLanes: batchScope?.lanes, tensorAssistant: assistant?.policy) + chosen: chosen, batchLanes: batchLanes, tensorAssistant: assistant?.policy) lines.append("What happens next") lines += value.narration(localMemberID: localMemberID).map { " " + $0 } setup = value diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift new file mode 100644 index 0000000000..08285168bd --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift @@ -0,0 +1,49 @@ +import DarkbloomClusterPlacement +import DarkbloomClusterProtocol + +/// The width a request-owned Qwen TP placement saves (`ClusterConfiguration.batchLanes`), so a pair serves concurrent +/// requests from its first load instead of after a drained replacement, and a pair saved for coordinator pairing, +/// which never widens afterwards, serves them at all. The widest of the owner's quoted widths at which the chosen +/// placement, its leader and split unchanged, fits both Macs now under that width's complete LOAD quote: the predicate +/// a replacement is held to (`ClusterPlacementCandidate.admitted`). When none fits, the setup saves no width and keeps +/// the family default. +enum ClusterPlacementTensorWidth { + /// `result` becomes the widest admitted width's plan and `lanes` that width; both stay as they are when none + /// fits. Never inlined, so the plans it makes stay off the caller's frame, which a deep planner stack shares. + @inline(never) + static func size(_ result: inout ClusterPlacementResult, lanes: inout Int?, quotes: [ClusterPlacementTensorBatchQuote], + devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy, + link: ClusterLinkCosts) throws { + guard let sized = try widest(result, quotes: quotes, devices: devices, layout: layout, policy: policy, link: link) else { return } + result = sized.result; lanes = sized.lanes + } + + static func widest(_ singleton: ClusterPlacementResult, quotes: [ClusterPlacementTensorBatchQuote], + devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy, + link: ClusterLinkCosts) throws -> (lanes: Int, result: ClusterPlacementResult)? { + // A split the setup can save: equal, or integer weights. + guard let chosen = singleton.chosen, chosen.mode == .tensorParallel, chosen.shares == nil || chosen.tensorShares != nil, + policy.tensorParallelBatchQuote?.lanes == 1, let leader = chosen.ranks.first?.device else { return nil } + for quote in quotes.sorted(by: { $0.lanes > $1.lanes }) { + var widened = policy + try quote.applyWidth(to: &widened, layout: layout) + widened.modes = [.tensorParallel]; widened.schedules = [chosen.prefillSchedule] + widened.modesReason = widened.modesReason ?? "its concurrent requests are sized on the chosen tensor-parallel placement" + widened.leader = leader; widened.requiredTensorShares = chosen.tensorShares ?? [1, 1] + let result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: widened, link: link) + guard let wide = result.chosen, wide.mode == .tensorParallel, wide.ranks.map(\.device) == chosen.ranks.map(\.device), + wide.tensorShares == chosen.tensorShares, wide.admitted(requireNow: true) else { continue } + return (quote.lanes, result) + } + return nil + } +} + +extension ClusterPlacementCandidate { + /// Possible and inside the GPU working set and, with `requireNow`, every rank fits what its Mac admits now: + /// hardware possibility alone is not current admission. A saved width and an automatic replacement + /// (`DistributedAutomaticBatchPlanner.accepts`) are held to it alike. + func admitted(requireNow: Bool) -> Bool { + possible && withinGPUWorkingSet && (!requireNow || ranks.allSatisfy { $0.fit == .now }) + } +} diff --git a/provider-swift/Tests/ClusterPlacementChecks/run.sh b/provider-swift/Tests/ClusterPlacementChecks/run.sh index 4ac7ce3d18..33731c0298 100755 --- a/provider-swift/Tests/ClusterPlacementChecks/run.sh +++ b/provider-swift/Tests/ClusterPlacementChecks/run.sh @@ -42,6 +42,7 @@ xcrun swiftc -j 4 "${task_flags[@]}" -D DARKBLOOM_CLUSTER_FIXTURE_ARTIFACTS -par "$task_provider/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairQualificationRecords.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementSetup.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift" \ + "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterForcedModeSetting.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlannerBenchCap.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Installed/ClusterBenchChip.swift" \ diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift index c8c7660c87..7284c3f6d9 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift @@ -30,10 +30,11 @@ final class ClusterApprovalMacs: @unchecked Sendable { static let chip = ClusterChipClass(chipName: "Apple M3 Ultra") /// What both Macs' setups place: the Qwen3.5 9B pipeline, or Qwen3.8 27B in tensor parallel as the guided setup - /// saves it, with or without the model's embedded speculative assistant (`ClusterConfiguration.tensorAssistant`). + /// saves it, with or without the model's embedded speculative assistant (`ClusterConfiguration.tensorAssistant`) + /// and the width its placement saved (`ClusterConfiguration.batchLanes`). enum Shape { case pipeline - case qwen27TensorParallel(assistant: ClusterQwenTensorAssistantPolicy?) + case qwen27TensorParallel(assistant: ClusterQwenTensorAssistantPolicy?, lanes: Int? = nil) } let root: URL @@ -152,9 +153,10 @@ final class ClusterApprovalMacs: @unchecked Sendable { "linkControl": ["schema": ClusterLinkControlAttachment.schemaName, "port": 47999, "linkEpoch": record.link.linkEpoch, "edgeID": record.link.edgeID, "secretFile": secret.path], "tokenizerFiles": [["path": "tokenizer.json", "sha256": h("6"), "purpose": "tokenizer"]]] - if case .qwen27TensorParallel(let assistant) = shape { + if case .qwen27TensorParallel(let assistant, let lanes) = shape { configuration["generationMode"] = ClusterGenerationMode.tensorParallel.rawValue if let assistant { configuration["tensorAssistant"] = assistant.object } + if let lanes { configuration["batchLanes"] = lanes } } let input = mac.scratch.appendingPathComponent("setup.json"), capabilityInput = mac.scratch.appendingPathComponent("capability.json") try JSONSerialization.data(withJSONObject: configuration, options: [.sortedKeys]).write(to: input) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthRegisteredTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthRegisteredTests.swift new file mode 100644 index 0000000000..b960d4433c --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthRegisteredTests.swift @@ -0,0 +1,173 @@ +import DarkbloomClusterPlacement +@testable import DarkbloomClusterRuntime +import DarkbloomClusterProtocol +import Foundation +import Testing +@testable import ProviderCore + +/// The width the registered Qwen3.8 27B saves on idle pairs of each size: its retained headers, LOAD's own quote at +/// every width (`ClusterPlacementArtifact.tensorBatchQuote`, as `tensor-batch-scope` derives it) and the guided step's +/// own decision (`ClusterPlacementFlow.decide`), plain (a pair served through Darkbloom) and with the depth-3 assistant +/// (a local pair). The vision tower's resident bytes are left out, as the served layout leaves them. Header metadata +/// only: no model, no GPU. +struct ClusterPlacementTensorWidthRegisteredTests { + private struct Retained: Decodable { + struct Tensor: Decodable { let name: String; let shape: [Int]; let sourceDType: String; let byteCount: Int } + struct Profile: Decodable { let configuration: Data; let canonicalTensors: [Tensor] } + let twentySeven: Profile + } + private struct Assistant: Decodable { + struct Tensor: Decodable { let name: String; let shape: [Int]; let dtype: String; let byteCount: Int } + let tensors: [Tensor] + } + private static let gib = 1 << 30 + private static func bound(_ bytes: Int) -> Int { ((bytes + 16_383) / 16_384) * 16_384 } + private static func hash(_ c: Character) -> String { String(repeating: String(c), count: 64) } + + /// An idle Mac of `physicalGiB`, as the placement checks construct one (`SyntheticMac.idle`): wired 3 % (at least + /// 2.5 GiB), other programs 4 % (at least 3 GiB), 1 GiB of file cache, the rest free. + private static func idle(_ physicalGiB: Double) throws -> ClusterDeviceProfile { + let page = 16_384 + func pages(_ value: Double) -> Int { Int((value * Double(gib) / Double(page)).rounded()) } + let wiredGiB = max(2.5, physicalGiB * 0.03), otherGiB = max(3, physicalGiB * 0.04) + let physical = pages(physicalGiB), wired = pages(wiredGiB), free = pages(physicalGiB - wiredGiB - otherGiB - 1) + let cache = pages(1), pageable = physical - wired, anonymous = max(0, pageable - free - cache) + let observation = QwenDenseStageLoadOSObservation(startedNanoseconds: 900, completedNanoseconds: 1_000, + timestampUTC: "2026-11-01T00:00:00Z", physicalMemoryBytes: physical * page, pageSizeBytes: page, + kernelFreePages: free, freePages: free, inactivePages: cache + anonymous / 2, speculativePages: 0, + actualFreeBytes: free * page, estimatedReclaimableBytes: (free + cache + anonymous / 2) * page, pressureLevel: 1, + swapUsedBytes: 0, activePages: anonymous - anonymous / 2, fileBackedPages: cache, anonymousPages: anonymous, + wiredPages: wired, purgeablePages: 0, compressorPages: 0, kernelFileCacheMinimumPages: nil, + inactiveFileBackedPages: cache, inactiveAnonymousPages: anonymous / 2, compressionPages: 0, swapoutPages: 0, + liveCompressionPages: 0) + let bytes = physical * page, workingSet = bytes / 4 * 3 + var profile = try ClusterDeviceProfile(chip: "Synthetic", performanceCores: 8, efficiencyCores: 4, gpuCores: nil, + osVersion: "27.0", osBuild: "SYNTH", physicalMemoryBytes: bytes, gpuRecommendedWorkingSetBytes: workingSet, + gpuMaximumBufferBytes: bytes / 2, allocatorLimitBytes: min(workingSet / 2 * 3, bytes / 100 * 95), + memory: .gate(observation, now: 1_100), + power: .init(onExternalPower: true, lowPowerMode: false, thermalState: "nominal")) + profile.speedIndex = .init(chip: profile.chip, osBuild: profile.osBuild, benchmark: "qmm_h4096_b4_g64_x16_v1", + prefillIndex: 1_000_000, decodeIndex: 25_000) + return profile + } + + private struct Registered { + let layout: ClusterModelLayout + let capability: ClusterRuntimeCapability + let pair: ClusterPairDescription + /// Each kind's quotes by width, 1 through 8. + let plain: [Int: ClusterPlacementTensorBatchQuote] + let assisted: [Int: ClusterPlacementTensorBatchQuote] + } + + private static func registered() throws -> Registered { + let tests = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("libs/darkbloom-cluster/Tests", isDirectory: true) + let retained = try JSONDecoder().decode(Retained.self, from: Data(contentsOf: tests + .appendingPathComponent("StageMetadataChecks/Inputs/qwen-retained-inputs.json"))).twentySeven + let family = try QwenDensePlacementFamily(configuration: retained.configuration), p = family.profile + let plan = try #require(family.tensorParallel) + let text = retained.canonicalTensors.map { + ClusterPlacementStoredTensor(name: $0.name, byteCount: $0.byteCount, dtype: $0.sourceDType, shape: $0.shape) + } + let head = try JSONDecoder().decode(Assistant.self, from: Data(contentsOf: tests + .appendingPathComponent("DarkbloomClusterRuntimeTests/Inputs/qwen27-tp-mtp-inventory.json"))).tensors.map { + ClusterPlacementStoredTensor(name: $0.name, byteCount: $0.byteCount, dtype: $0.dtype, shape: $0.shape) + } + var planning = family + planning.tensorParallelRequestAllowance = try QwenTensorParallelRequestBudget.derive(geometry: family.geometry, + plan: plan, tensors: family.requireRegisteredInventory(text), maximumTokens: family.largestContextTokens, + chunkSize: family.maximumChunkTokens, allocationBound: bound).allowance + let specification = family.definition.specification + var object = try JSONSerialization.jsonObject(with: ClusterModelLayoutBuilder.build(family: planning, + tensors: text + head, artifactSHA256: specification.artifactSHA256, + configurationSHA256: specification.configurationSHA256).encoded()) as! [String: Any] + let listed = (object["generationModes"] as? [String] ?? []) + [ClusterGenerationMode.tensorParallel.rawValue] + object["generationModes"] = ClusterGenerationMode.allCases.map(\.rawValue).filter(listed.contains) + let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) + let request = try ClusterPlacementRequestScope(runtimeModelID: family.runtimeModelID, + artifactSHA256: specification.artifactSHA256, configurationSHA256: specification.configurationSHA256, + promptTokens: p.maximumPromptTokens, outputTokens: p.maximumOutputTokens, maximumPromptTokens: p.maximumPromptTokens, + maximumOutputTokens: p.maximumOutputTokens, maximumContextTokens: p.maximumContextTokens, + requestChargeEveryRankBytes: family.requestChargeEveryRankBytes(contextTokens: p.maximumPromptTokens + p.maximumOutputTokens)) + func quotes(_ depth: Int?) throws -> [Int: ClusterPlacementTensorBatchQuote] { + try Dictionary(uniqueKeysWithValues: [1, 2, 4, 6, 8].map { lanes in + (lanes, try ClusterPlacementArtifact.tensorBatchQuote(configuration: retained.configuration, stored: text + head, + request: request, chunkTokens: p.maximumChunkTokens, lanes: lanes, assistantDepth: depth, + assistantVerification: depth == nil ? .singleton : .admittedCohort, allocationBound: bound)) + }) + } + let partitions = layout.admittedCuts.enumerated().map { index, cut in + ClusterRuntimePartition(planSHA256: String(format: "%064lx", index + 1), stages: [ + .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: cut, stagePlanSHA256: String(format: "%064lx", 100 + index), + constructionConfigurationSHA256: hash("2")), + .init(rank: 1, sourceLayerStart: cut, sourceLayerEnd: layout.layerCount, stagePlanSHA256: String(format: "%064lx", 200 + index), + constructionConfigurationSHA256: hash("4"))]) + } + let capability = try ClusterRuntimeCapability(runtimeBinarySHA256: hash("a"), adapterID: "qwen35-dense-layer-stage", + adapterVersion: 1, runtimeModelID: layout.runtimeModelID, artifactSHA256: layout.artifactSHA256, + configurationSHA256: layout.configurationSHA256, manifestSHA256: hash("d"), + profile: .init(id: "registered_qwen38_27b_greedy_generation_v1", vocabularySize: 248320, + maximumPromptTokens: p.maximumPromptTokens, maximumOutputTokens: p.maximumOutputTokens, + maximumChunkTokens: p.maximumChunkTokens, maximumContextTokens: p.maximumContextTokens), + profileFingerprint: hash("e"), partitions: partitions, arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", + arithmeticPolicySHA256: hash("5"), supportedGenerationModes: [.pipeline, .tensorParallel]) + let pair = ClusterPairDescription(schema: ClusterPairDescription.schemaName, clusterID: "fixture-cluster", + publicModelID: "EigenLabs/Qwen3.8-27B-4bit-mtp", + capabilitySHA256: ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(capability)), + chunkTokens: p.maximumChunkTokens, requestTimeoutSeconds: 315, coordinatorPort: 5577, + members: ["a", "b"].enumerated().map { index, id in + .init(id: id, host: "192.0.2.\(index + 1)", port: 22, user: "fixture", + ownerExecutable: "/fixture/darkbloom", workerExecutable: "/fixture/worker", modelDirectory: "/fixture/model", + runtimeBinarySHA256: hash("a"), jacclDevice: "en7", linkAddress: "192.0.2.\(index + 1)", trust: nil, + linkSecretFile: "/fixture/\(id).secret") + }, tokenizerFiles: [.init(path: "tokenizer.json", sha256: hash("6"), purpose: .tokenizer)], + linkControl: .init(port: 5578, linkEpoch: UUID().uuidString.lowercased(), edgeID: UUID().uuidString.lowercased())) + return .init(layout: layout, capability: capability, pair: pair, plain: try quotes(nil), assisted: try quotes(3)) + } + + @Test func twoM5UltrasSaveEightAndSmallerPairsTheWidestTheirQuoteAdmits() throws { + let model = try Self.registered() + let link = ClusterLinkCosts(measured: true, perChunkSeconds: 0.002, perDecodeStepSeconds: [:], + handoffSecondsPerByte: 1 / 2e9, provenance: "constructed for a check", + reduction: .init(fixedSeconds: 1e-6, secondsPerByte: 1 / 5e9, keyed: true, provenance: "constructed for a check")) + for (kind, quotes) in [("plain", model.plain), ("assistant", model.assisted)] { + let singleton: ClusterPlacementTensorBatchQuote = try #require(quotes[1]) + for lanes in [1, 2, 4, 6, 8] { + let quote: ClusterPlacementTensorBatchQuote = try #require(quotes[lanes]) + print("qwen27-tp-width-quote kind=\(kind) lanes=\(lanes) request_bytes=\(quote.allowance.requestBytesExcludingCollectives)" + + " reserved_bytes=\(quote.allowance.reservedBytes) per_lane_bytes=\(quote.perLaneStateBytes)" + + " rank0_equal_bytes=\(quote.rankReservedBytes(rank: 0, shares: nil) ?? -1)" + + " rank1_equal_bytes=\(quote.rankReservedBytes(rank: 1, shares: nil) ?? -1)") + } + /// The width a pair of these two idle Macs saves (1: none), or nil when tensor parallel is not placed. + func saved(_ localGiB: Double, _ peerGiB: Double) throws -> Int? { + let decided = try ClusterPlacementFlow.decide(description: model.pair, capability: model.capability, + localMemberID: "a", localProfile: try Self.idle(localGiB), peerProfile: try Self.idle(peerGiB), layout: model.layout, + tensorAssistantQuote: singleton, tensorWidthQuotes: [2, 4, 6, 8].compactMap { quotes[$0] }, + leader: "a", link: link, environment: [:], benchDebugBuild: false) + guard let chosen = decided.result.chosen, chosen.mode == .tensorParallel, let setup = decided.setup else { + print("qwen27-tp-width kind=\(kind) mac_gib=\(Int(localGiB))+\(Int(peerGiB)) placed=false") + return nil + } + let lanes = try ClusterConfigurationCodec.decode(try #require(setup.configurations["a"]), + capability: model.capability, capabilitySHA256: model.pair.capabilitySHA256).batchLanes ?? 1 + print("qwen27-tp-width kind=\(kind) mac_gib=\(Int(localGiB))+\(Int(peerGiB)) lanes=\(lanes) shares=\(chosen.tensorShares ?? [1, 1])" + + chosen.ranks.map { " rank\($0.rank)_need_bytes=\($0.needBytes) rank\($0.rank)_admissible_now_bytes=\($0.admissibleNowBytes)" }.joined()) + // Within what each Mac admits now, under the saved width's own quote. + #expect(chosen.ranks.allSatisfy { $0.needBytes <= $0.admissibleNowBytes && $0.fit == .now }) + return lanes + } + var widths: [Int] = [] + for size in [32.0, 36, 48, 64, 96, 128, 192, 256] { + guard let lanes = try saved(size, size) else { continue } + #expect(lanes >= (widths.last ?? 1), "\(kind) 2 x \(Int(size)) GiB: a larger pair never saves a narrower width") + widths.append(lanes) + } + #expect(widths.last == 8, "2 x 256 GiB, \(kind)") + #expect(widths.contains { $0 < 8 }, "\(kind): a smaller pair saves a narrower width") + for (local, peer) in [(256.0, 36.0), (256.0, 48.0), (256.0, 128.0)] { _ = try saved(local, peer) } + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift new file mode 100644 index 0000000000..a7dff7fade --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift @@ -0,0 +1,256 @@ +import DarkbloomClusterPlacement +import DarkbloomClusterProtocol +import Foundation +import Testing +@testable import ProviderCore + +/// The width a Qwen TP placement saves (`ClusterPlacementTensorWidth`), through the guided step's own decision +/// (`ClusterPlacementFlow.decide`) with constructed profiles and quotes. CPU metadata only; none is a hardware result. +@Suite(.serialized) +final class ClusterPlacementTensorWidthTests { + private var homes: [URL] = [] + deinit { for home in homes { try? FileManager.default.removeItem(at: home) } } + private let gib = 1_073_741_824 + private func hash(_ c: Character) -> String { String(repeating: String(c), count: 64) } + + /// A home with a recorded keyed link between the two members, so tensor parallel is planned on a measured link. + private func home() throws -> URL { + let result = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true) + .appendingPathComponent("tensor-width-inputs-" + UUID().uuidString) + try FileManager.default.createDirectory(at: result, withIntermediateDirectories: false, + attributes: [.posixPermissions: 0o700]) + homes.append(result) + let probe = ClusterWorkerLinkProbe(transport: "jaccl", keyed: true, pointToPointSmallBytes: 4096, + pointToPointSmallMicroseconds: 1, pointToPointLargeBytes: 1_048_576, pointToPointLargeMicroseconds: 10, + allSumSmallBytes: 4096, allSumSmallMicroseconds: 1, allSumLargeBytes: 1_048_576, allSumLargeMicroseconds: 10) + #expect(ClusterLinkProbeHistory.record(probe, members: ["a", "b"], homeDirectory: result)) + return result + } + + private func profile(free: Int) throws -> ClusterDeviceProfile { + let physical = 256 * gib + var p = try ClusterDeviceProfile(chip: "Constructed width fixture", performanceCores: 8, efficiencyCores: 4, + gpuCores: 40, osVersion: "27.0", osBuild: "CHECK", physicalMemoryBytes: physical, + gpuRecommendedWorkingSetBytes: 192 * gib, gpuMaximumBufferBytes: 128 * gib, allocatorLimitBytes: 230 * gib, + memory: .init(gatePolicy: "fixture", sampledUTC: "2026-11-01T00:00:00Z", judged: true, unjudgedReason: nil, + physicalMemoryBytes: physical, actualFreeBytes: free, countedFileCacheBytes: 0, admissibleNowBytes: free, + fileBackedBytes: 0, fileCacheReserveBytes: 0, fileCacheAboveReserveBytes: 0, anonymousBytes: physical - free - 4 * gib, + wiredBytes: 4 * gib, compressorBytes: 0, pageableBytes: 252 * gib, pressureLevel: 1, swapUsedBytes: 0, + minimumAdmissibleBytes: 6 * gib, minimumTrulyFreeBytes: 16 * 1_048_576, loadingHeadroomBytes: 4 * gib, + allocatorHeadroomBytes: 2 * gib, loadScratchBytes: 8 * 1_048_576, pageSizeBytes: 16_384), + power: .init(onExternalPower: true, lowPowerMode: false, thermalState: "nominal")) + p.speedIndex = .init(chip: p.chip, osBuild: p.osBuild, benchmark: "qmm_h4096_b4_g64_x16_v1", + prefillIndex: 1_000_000, decodeIndex: 25_000) + return p + } + + /// The registered 27B's identity on a constructed two-layer layout whose tensor parallel splits 1:1, 1:2 or 2:1. + private func fixture() throws -> (ClusterPairDescription, ClusterRuntimeCapability, ClusterModelLayout, ClusterPlacementRequestScope) { + let model = "registered_qwen38_27b" + let part = ClusterModelLayout.Part(storedBytes: 2 * gib, loadedBytes: 2 * gib, largestTensorBytes: gib / 4, tensorCount: 16) + let end = ClusterModelLayout.Part(storedBytes: gib / 2, loadedBytes: gib / 2, largestTensorBytes: gib / 2, tensorCount: 1) + let raw = ClusterModelLayout(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), + layers: (0..<2).map { .init(index: $0, kind: "fixture", weights: part, stateFixedBytes: 1024, + stateBytesPerToken: 1024, cost: 1) }, ingress: end, egress: end, excluded: .init(), admittedCuts: [1], + structuralCuts: [1], generationModes: [.pipeline, .tensorParallel], prefillSchedules: [.serial], + maximumPromptTokens: 1024, maximumOutputTokens: 128, maximumChunkTokens: 128, + boundaryBytesPerToken: 4096, requestChargeEveryRankBytes: gib) + let tensor = ClusterTensorParallelLayout(family: .init(plan: "fixture-heads", ranks: [2], reductionsPerLayer: 1, + reductionsPerStep: 0, partialBytesPerToken: 4096, stateDividesByHeads: true, shareOptions: [[1, 2], [2, 1]]), + layerDividedBytes: [2 * gib, 2 * gib], layerReplicatedBytes: [0, 0], + ingressDividedBytes: 0, ingressReplicatedBytes: gib / 2, egressDividedBytes: gib / 2, egressReplicatedBytes: 0) + var object = try JSONSerialization.jsonObject(with: raw.encoded()) as! [String: Any] + object["tensorParallel"] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(tensor)) + let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object)) + let cap = try ClusterRuntimeCapability(runtimeBinarySHA256: hash("a"), adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, + runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), manifestSHA256: hash("d"), + profile: .init(id: "registered_qwen38_27b_greedy_generation_v1", vocabularySize: 248320, + maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumChunkTokens: 512, maximumContextTokens: 65536), + profileFingerprint: hash("e"), partitions: [.init(planSHA256: hash("f"), stages: [ + .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 1, stagePlanSHA256: hash("1"), constructionConfigurationSHA256: hash("2")), + .init(rank: 1, sourceLayerStart: 1, sourceLayerEnd: 2, stagePlanSHA256: hash("3"), constructionConfigurationSHA256: hash("4"))])], + arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", arithmeticPolicySHA256: hash("5"), + supportedGenerationModes: [.pipeline, .tensorParallel]) + let capHash = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(cap)) + let pair = ClusterPairDescription(schema: ClusterPairDescription.schemaName, clusterID: "fixture-cluster", + publicModelID: "fixture-model", capabilitySHA256: capHash, chunkTokens: 128, requestTimeoutSeconds: 315, + coordinatorPort: 5577, members: ["a", "b"].enumerated().map { index, id in + .init(id: id, host: "192.0.2.\(index + 1)", port: 22, user: "fixture", + ownerExecutable: "/fixture/darkbloom", workerExecutable: "/fixture/worker", modelDirectory: "/fixture/model", + runtimeBinarySHA256: hash("a"), jacclDevice: "en7", linkAddress: "192.0.2.\(index + 1)", trust: nil, + linkSecretFile: "/fixture/\(id).secret") + }, tokenizerFiles: [.init(path: "tokenizer.json", sha256: hash("6"), purpose: .tokenizer)], + linkControl: .init(port: 5578, linkEpoch: UUID().uuidString.lowercased(), edgeID: UUID().uuidString.lowercased())) + let request = try ClusterPlacementRequestScope(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), + promptTokens: 1024, outputTokens: 128, maximumPromptTokens: 32768, maximumOutputTokens: 32768, + maximumContextTokens: 65536, requestChargeEveryRankBytes: gib) + return (pair, cap, layout, request) + } + + /// One owner's complete quote at `lanes`: 4 GiB a lane beside 1 GiB shared. + private func quote(_ request: ClusterPlacementRequestScope, lanes: Int, + assistant: ClusterPlacementTensorAssistantQuote? = nil) throws -> ClusterPlacementTensorBatchQuote { + let payload = max(512 * 4096, lanes * 248320 * 4) + return try .init(request: request, lanes: lanes, chunkTokens: 128, perLaneStateBytes: 4 * gib, + sharedBytesExcludingCollectives: gib, + allowance: .init(maximumContextTokens: 65536, maximumChunkTokens: 512, requestBytesExcludingCollectives: lanes * 4 * gib + gib, + maximumCollectivePayloadBytes: payload, maximumCollectiveFrameBytes: payload + 1024, + allocationBound: { (($0 + 16383) / 16384) * 16384 }), + assistant: assistant) + } + + private func decide(_ home: URL, free: Int, peerFree: Int? = nil, widths: [Int] = ClusterPlacementBatchScope.tensorParallelWidths, + assistant: ClusterPlacementTensorAssistantQuote? = nil) throws -> ClusterSetupPlanning.PlacementDecision { + let (pair, cap, layout, request) = try fixture() + return try ClusterPlacementFlow.decide(description: pair, capability: cap, localMemberID: "a", + localProfile: profile(free: free), peerProfile: profile(free: peerFree ?? free), layout: layout, + tensorAssistantQuote: try quote(request, lanes: 1, assistant: assistant), + tensorWidthQuotes: try widths.map { try quote(request, lanes: $0, assistant: assistant) }, leader: "a", + link: try #require(ClusterLinkProbeHistory.costs(homeDirectory: home, members: ["a", "b"])), + environment: [:], benchDebugBuild: false) + } + + /// Both Macs' saved widths: equal, or the test fails. + private func savedLanes(_ decision: ClusterSetupPlanning.PlacementDecision) throws -> Int? { + let (pair, cap, _, _) = try fixture() + let setup = try #require(decision.setup) + let lanes = try ["a", "b"].map { member in + try ClusterConfigurationCodec.decode(try #require(setup.configurations[member]), capability: cap, + capabilitySHA256: pair.capabilitySHA256).batchLanes + } + #expect(lanes[0] == lanes[1], "both Macs save one width") + return lanes[0] + } + + /// The largest rank need of the placement at one width alone (no wider width offered). + private func need(_ home: URL, lanes: Int) throws -> Int { + let decided = try decide(home, free: 200 * gib, widths: lanes == 1 ? [] : [lanes]) + return try #require(decided.result.chosen).ranks.map(\.needBytes).max()! + } + + @Test func aPlacementSavesTheWidestWidthBothMacsAdmitNow() throws { + let home = try home() + let needs = try Dictionary(uniqueKeysWithValues: [1, 2, 4, 6, 8].map { ($0, try need(home, lanes: $0)) }) + #expect(needs[1]! < needs[2]! && needs[2]! < needs[4]! && needs[4]! < needs[6]! && needs[6]! < needs[8]!) + let singleton = try decide(home, free: 200 * gib, widths: []) + #expect(try savedLanes(singleton) == nil, "no width quote: the setup saves no width, as before") + // Every Mac admits each width's need, and nothing between it and the next wider one. + for (free, expected) in [(200 * gib, 8), ((needs[6]! + needs[8]!) / 2, 6), ((needs[4]! + needs[6]!) / 2, 4), + ((needs[2]! + needs[4]!) / 2, 2), ((needs[1]! + needs[2]!) / 2, nil)] as [(Int, Int?)] { + let decided = try decide(home, free: free) + let chosen = try #require(decided.result.chosen) + #expect(try savedLanes(decided) == expected, "\(free / gib) GiB free") + #expect(chosen.mode == .tensorParallel && DistributedAutomaticBatchPlanner.accepts(chosen, requireNow: true)) + // The saved width is priced at its own complete quote, within what each Mac admits now. + #expect(chosen.ranks.map(\.needBytes).max() == needs[expected ?? 1], "\(free / gib) GiB free") + #expect(chosen.ranks.allSatisfy { $0.needBytes <= $0.admissibleNowBytes }) + // The placement is the singleton's: leader and split unchanged; only the width is added. + let alone = try #require(try decide(home, free: free, widths: []).result.chosen) + #expect(chosen.ranks.map(\.device) == alone.ranks.map(\.device) && chosen.tensorShares == alone.tensorShares) + #expect(decided.lines.contains(" \(expected ?? 0) independent histories, charged at the quoted request bound on both Macs. " + + "Stage-rate predictions remain single-request estimates; no batch speed is inferred from the lane count.") == (expected != nil)) + } + // Both Macs must admit it: the smaller Mac decides. + #expect(try savedLanes(try decide(home, free: 200 * gib, peerFree: (needs[4]! + needs[6]!) / 2)) == 4) + // A width the helper did not quote is not offered. + #expect(try savedLanes(try decide(home, free: 200 * gib, widths: [2, 4])) == 4) + } + + @Test func anAssistedOwnerIsSizedAtItsOwnQuote() throws { + let home = try home() + let assistant = try ClusterPlacementTensorAssistantQuote(policy: .init(depth: 3, inventorySHA256: hash("8"), + verification: .admittedCohort), residentBytes: gib, loadBytes: 2 * gib, largestAllocationBytes: gib) + let decided = try decide(home, free: 200 * gib, assistant: assistant) + #expect(try savedLanes(decided) == 8) + let (pair, cap, _, _) = try fixture() + let saved = try ClusterConfigurationCodec.decode(try #require(decided.setup?.configurations["a"]), capability: cap, + capabilitySHA256: pair.capabilitySHA256) + #expect(saved.tensorAssistant == assistant.policy) + // A width of another assistant (or none) is not this owner's. + let (_, _, layout, request) = try fixture() + var policy = ClusterPlacementPolicy() + try quote(request, lanes: 1, assistant: assistant).applySingleton(to: &policy, layout: layout) + #expect(throws: (any Error).self) { try self.quote(request, lanes: 8).applyWidth(to: &policy, layout: layout) } + #expect(throws: (any Error).self) { try self.quote(request, lanes: 1, assistant: assistant).applyWidth(to: &policy, layout: layout) } + } + + /// GLM tensor parallel keeps its own default; a pipeline, and a Qwen TP setup saved without a width, keep theirs. + @Test func otherFamiliesAndUnsizedSetupsKeepTheirLanes() throws { + typealias Plan = DistributedInstalledPlan + #expect(Plan.defaultBatchLanes(adapter: .glm5NextLayerStage, mode: .tensorParallel, hasPrivateImages: false) == 8) + #expect(Plan.defaultBatchLanes(adapter: .qwen35Dense, mode: .tensorParallel, hasPrivateImages: false, + runtimeModelID: "registered_qwen38_27b") == 1) + #expect(Plan.defaultBatchLanes(adapter: .qwen35Dense, mode: .pipeline, hasPrivateImages: false) == Plan.defaultBatchLanes) + // Only a placement priced by its owner's singleton quote is sized: without one, width quotes change nothing. + let home = try home() + let (pair, cap, layout, request) = try fixture() + let unquoted = try ClusterPlacementFlow.decide(description: pair, capability: cap, localMemberID: "a", + localProfile: profile(free: 200 * gib), peerProfile: profile(free: 200 * gib), layout: layout, + tensorWidthQuotes: try [8].map { try quote(request, lanes: $0) }, + leader: "a", link: try #require(ClusterLinkProbeHistory.costs(homeDirectory: home, members: ["a", "b"])), + environment: [:], benchDebugBuild: false) + #expect(unquoted.result.chosen?.mode == .tensorParallel) + #expect(try savedLanes(unquoted) == nil) + } + + /// A pair saved for coordinator pairing serves the width its placement saved, on both Macs, from its first start: + /// the approval is saved beside it unchanged, no approval or committed-start digest names it (only the setup's own + /// bytes do), and the automatic replacement never plans for a setup saved with an approval. + @Test func aCoordinatorPairKeepsTheWidthItsSetupSavedThroughApproval() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", + shape: .qwen27TensorParallel(assistant: nil, lanes: 8)) + let approval = macs.approval(), facts = try macs.facts() + #expect(macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts).changed) + let epoch = UUID() + for mac in macs.macs { + let saved = try macs.saved(mac), configuration = saved.configuration + #expect(configuration.nativeMember?.clusterApproval == approval && configuration.batchLanes == 8, "rank \(mac.rank)") + let plan = try DistributedInstalledPlan(saved: saved, paths: mac.paths) + #expect(plan.batchLanes([:]) == 8 && plan.lanesRetireAlone([:]), "rank \(mac.rank)") + #expect(plan.nativeEnvironment(matrix: URL(fileURLWithPath: "/fixture/matrix.json"), ownerEnvironment: [:])[ + DistributedInstalledPlan.batchLanesSwitch] == "8", "rank \(mac.rank)") + // The same setup without the width: every approval and committed-start digest is the same; only the + // setup's own bytes (its digest) differ. + let bytes = try ClusterConfigurationCodec.encode(configuration, capability: saved.capability, + capabilitySHA256: configuration.capabilitySHA256) + var object = try JSONSerialization.jsonObject(with: bytes) as! [String: Any] + object.removeValue(forKey: "batchLanes") + let unsizedBytes = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) + let unsized = try ClusterConfigurationCodec.decode(unsizedBytes, capability: saved.capability, + capabilitySHA256: configuration.capabilitySHA256) + let other = try DistributedInstalledPlan(saved: .init(configuration: unsized, capability: saved.capability), paths: mac.paths) + #expect(other.batchLanes([:]) == 1) + #expect(try DistributedInstalledNativeStart.common(plan: plan, epoch: epoch).canonicalBytes + == DistributedInstalledNativeStart.common(plan: other, epoch: epoch).canonicalBytes, "rank \(mac.rank)") + #expect(DistributedInstalledNativeStart.runtimeBlock(plan: plan) == DistributedInstalledNativeStart.runtimeBlock(plan: other)) + #expect(ClusterConfigurationCodec.sha256(bytes) != ClusterConfigurationCodec.sha256( + try ClusterConfigurationCodec.encode(unsized, capability: saved.capability, capabilitySHA256: configuration.capabilitySHA256))) + } + // Queued demand never re-plans an approved setup: the coordinator-approved contract stays as approved. + let reference = try ClusterConfigurationStore.installedReference(providerConfiguration: macs.leader.provider) + let planner = DistributedAutomaticBatchPlanner(providerConfiguration: macs.leader.provider, paths: macs.leader.paths) + let queued = DistributedLocalBatchDemand(generationID: UUID(), waitingRequests: 8, activeRequests: 8, currentCapacity: 8, + publicModelID: ClusterApprovalMacs.model, runtimeModelID: macs.capability.runtimeModelID, + artifactSHA256: macs.capability.artifactSHA256, configurationSHA256: macs.capability.configurationSHA256, + maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumContextTokens: 65536, requestTimeout: .seconds(300)) + #expect(try planner.snapshot(reference: reference, demand: queued, widths: [8], requireNow: true) == nil) + } + + private func demand(capacity: Int, active: Int, waiting: Int, model: String = "registered_qwen38_27b") -> DistributedLocalBatchDemand { + .init(generationID: UUID(), waitingRequests: waiting, activeRequests: active, currentCapacity: capacity, + publicModelID: "fixture-model", runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), + maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumContextTokens: 65536, requestTimeout: .seconds(315)) + } + + /// A pair placed at its widest admitted width is never drained for it; one placed narrower still widens past it. + @Test func aLocalPairWidensByReplacementOnlyPastItsSavedWidth() { + typealias Factory = DistributedAutomaticBatchFactory + #expect(Factory.replacementWidths(for: demand(capacity: 8, active: 8, waiting: 8)).isEmpty) + #expect(Factory.replacementWidths(for: demand(capacity: 6, active: 6, waiting: 2)) == [8]) + #expect(Factory.replacementWidths(for: demand(capacity: 4, active: 4, waiting: 4)) == [8, 6]) + #expect(Factory.replacementWidths(for: demand(capacity: 1, active: 1, waiting: 7)) == [8, 6, 4, 2]) + #expect(Factory.replacementWidths(for: demand(capacity: 4, active: 4, waiting: 0)).isEmpty) + // A row without a request-owned TP owner keeps the pipeline's priced widths. + #expect(Factory.replacementWidths(for: demand(capacity: 1, active: 1, waiting: 7, model: "fixture_pipeline_model")) == [8, 4, 2]) + } +} From 5d20bce05354556cb6d21562b9f8da997198a193 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:09:52 -0800 Subject: [PATCH 30/58] Say which width a sized tensor-parallel plan leaves the pipeline out for A row whose pipeline stays admissible (the 9B, the 35B A3B rows) is re-planned at its saved width on its chosen tensor-parallel placement alone. Its plan's mode reason now says so ("its tensor-parallel placement, chosen for one request, is sized for N at once") instead of a generic sentence. The 27B keeps its feature-policy reason. Wording only. Co-Authored-By: Claude Opus 5.5 --- .../Distributed/Placement/ClusterPlacementTensorWidth.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift index 08285168bd..ea5fae768a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift @@ -28,7 +28,8 @@ enum ClusterPlacementTensorWidth { var widened = policy try quote.applyWidth(to: &widened, layout: layout) widened.modes = [.tensorParallel]; widened.schedules = [chosen.prefillSchedule] - widened.modesReason = widened.modesReason ?? "its concurrent requests are sized on the chosen tensor-parallel placement" + widened.modesReason = widened.modesReason + ?? "its tensor-parallel placement, chosen for one request, is sized for \(quote.lanes) at once" widened.leader = leader; widened.requiredTensorShares = chosen.tensorShares ?? [1, 1] let result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: widened, link: link) guard let wide = result.chosen, wide.mode == .tensorParallel, wide.ranks.map(\.device) == chosen.ranks.map(\.device), From 11b5c0850878469d5a207d838aa797366c27bae9 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:18:01 -0800 Subject: [PATCH 31/58] Check a saved tensor width's pricing in the placement checks PlacementChecks now hold ClusterPlacementTensorBatchQuote.applyWidth to its contract on the 27B layout: at widths 2, 4, 6 and 8 each rank is priced at the width's complete quote, the singleton's reference request and prediction are kept and the widening steer is cleared; a singleton quote, a policy without one, another request envelope and another assistant are refused. Co-Authored-By: Claude Opus 5.5 --- .../TensorBatchScopeChecks.swift | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/TensorBatchScopeChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/TensorBatchScopeChecks.swift index a2270d57f1..461cdf673c 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/TensorBatchScopeChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/TensorBatchScopeChecks.swift @@ -191,4 +191,49 @@ func checkTensorBatchScopes(_ inputs: RetainedQwenInputs, _ checks: PlacementChe } } + // A width saved at placement (`applyWidth`): the same owner's quote at that width in place of the singleton's, + // for a reference request inside its envelope. Memory is priced at the width; the prediction stays a request's. + let single = try quote(1) + func singleton() throws -> ClusterPlacementPolicy { + var p = ClusterPlacementPolicy(); p.leader = "a"; p.promptTokens = 700; p.outputTokens = 90 + try single.applySingleton(to: &p, layout: layout) + return p + } + let alone = try ClusterPlacementPlanner.evaluate(devices: fast, cuts: [], mode: .tensorParallel, + prefillSchedule: .serial, layout: layout, policy: singleton(), link: link) + for lanes in [2, 4, 6, 8] { + let value = try quote(lanes) + var widened = try singleton() + widened.tensorParallelWideningQuote = try quote(2) + try value.applyWidth(to: &widened, layout: layout) + let candidate = try ClusterPlacementPlanner.evaluate(devices: fast, cuts: [], mode: .tensorParallel, + prefillSchedule: .serial, layout: layout, policy: widened, link: link) + checks.require("TP width \(lanes): each rank is priced at the width's complete quote", + zip(candidate.ranks, fast).allSatisfy { $0.requestNeedBytes == value.allowance.reservedBytes + $1.profile.memory.loadingHeadroomBytes }) + checks.require("TP width \(lanes): the singleton's reference request and prediction are kept", + candidate.rested == alone.rested && candidate.sustained == alone.sustained + && widened.promptTokens == 700 && widened.outputTokens == 90) + checks.require("TP width \(lanes): the singleton's widening steer is cleared", widened.tensorParallelWideningQuote == nil) + } + checks.refuses("TP width: a singleton quote is no width", because: "same owner's singleton quote") { + var p = try singleton(); try single.applyWidth(to: &p, layout: layout) + } + checks.refuses("TP width: no singleton quote to replace", because: "same owner's singleton quote") { + var p = ClusterPlacementPolicy(); p.promptTokens = 700; p.outputTokens = 90 + try quote(8).applyWidth(to: &p, layout: layout) + } + checks.refuses("TP width: another request envelope is another owner's", because: "same owner's singleton quote") { + let other = try ClusterPlacementRequestScope(runtimeModelID: request.runtimeModelID, artifactSHA256: request.artifactSHA256, + configurationSHA256: request.configurationSHA256, promptTokens: 2048, outputTokens: 128, maximumPromptTokens: 32768, + maximumOutputTokens: 32768, maximumContextTokens: 65536, requestChargeEveryRankBytes: 4 * gib) + let wide = try ClusterPlacementTensorBatchQuote(request: other, lanes: 8, chunkTokens: 128, perLaneStateBytes: 4 * gib, + sharedBytesExcludingCollectives: 80 * gib, allowance: try quote(8).allowance) + var p = try singleton(); try wide.applyWidth(to: &p, layout: layout) + } + checks.refuses("TP width: another assistant is another owner's", because: "same owner's singleton quote") { + let plain = try quote(8) + let assisted = try ClusterPlacementTensorBatchQuote(request: request, lanes: 8, chunkTokens: 128, perLaneStateBytes: 4 * gib, + sharedBytesExcludingCollectives: 80 * gib, allowance: plain.allowance, assistant: assistant) + var p = try singleton(); try assisted.applyWidth(to: &p, layout: layout) + } } From 291f5fecf53108d9fa0c3cd15a328a6bba1073bb Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:31:29 -0800 Subject: [PATCH 32/58] cluster: prefill Qwen TP prompts as merged wavefront steps A Qwen tensor-parallel prompt frame of 512 rows computed, then waited for its own sealed FP32 sums (two a layer, each read by the next residual norm), so the GPU and the link took turns. A plain text lane now runs up to eight consecutive frames as one graph, layer by layer (`QwenTensorParallelPromptWavefront`, the SDK's `Qwen35PromptWavefront`): a frame's mixer, its sum submitted at once, the next frame's mixer while the sum crosses; then the MLPs the same way. At each layer a frame reads the KV and conv/SSM state the frame before it left, so every kernel sees the frame's own shapes: logits, KV, recurrent state and prefix captures are the per-frame bytes, with the same sealed FP32 sums in the same order. - Session: `promptFrames(limit:)` plans a step (ending at the prompt's end or the capture frontier); `prefill(step:check:)` admits its frames on the schedule, runs them in one `CBv2OwnedRequestState.run` and commits each frame. Assisted, media, packed-KV and routed-expert lanes keep one frame a step. - Driver and executor: the leader plans up to 8 frames, 2 while another lane decodes; each rank runs the plan only as a prefix of its own frames (`promptStep(tokens:)`). The load agreement binds the mode. - `QwenTensorParallelRowLinear.issuedSums` collects each phase's raw sums for submission; nil changes nothing. - Memory: `QwenTensorParallelPromptWavefront.inFlightBytes` (the further frames' FP32 partials, sums and residual rows; 367,001,600 B a 27B rank) joins the batch budget's shared prompt workspace, so LOAD, placement and every request's charge include it. - Bench: `tp-check qwen-prefill --wavefronts`, and `tp-check qwen-wavefront` (two ranks over the loopback ring: step times and digests per frame limit). - SDK gitlink to `perf/qwen27-tp-prompt-wavefront` (df6fc5f1). Tests: `QwenTensorParallelPromptWavefrontTests` (planner; bitwise merged against one frame a step, both ranks: mid-frame end paged and contiguous, capture frontier, beside a decoding lane, restored prefix; the merged step's measured temporaries within its charge); the batch budget test adds the new term. Co-Authored-By: Claude Opus 5.5 --- .../QwenPrefillBench.swift | 5 +- .../QwenWavefrontCheck.swift | 63 ++++ .../TensorParallelCheck.swift | 6 + .../QwenTensorParallelBatchBudget.swift | 6 +- .../QwenTensorParallelBatchDriver.swift | 12 +- .../QwenTensorParallelBatchSession.swift | 45 ++- .../QwenTensorParallelLinear.swift | 9 +- ...wenTensorParallelNativeBatchExecutor.swift | 13 +- .../QwenTensorParallelPrefillBench.swift | 82 ++++- .../QwenTensorParallelPromptWavefront.swift | 110 ++++++ .../QwenTensorParallelResidentRuntime.swift | 1 + .../QwenTensorParallelBatchBudgetTests.swift | 5 +- ...enTensorParallelPromptWavefrontTests.swift | 341 ++++++++++++++++++ libs/mlx-swift-lm | 2 +- 14 files changed, 676 insertions(+), 24 deletions(-) create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift 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..b241f273ca --- /dev/null +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift @@ -0,0 +1,63 @@ +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] \ +// [--wavefronts 1,2,8] [--repeats 1] +// Each rank logs every run's step times and digests; both agree that every +// run left the same bytes. Loopback timings show the overlap, never a pair's. +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"), + !wavefronts.isEmpty, wavefronts.allSatisfy({ (1...8).contains($0) }) else { + throw Failure("--prompt-tokens, --chunk 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)|\(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, 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..2c58b0da31 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift @@ -25,6 +25,8 @@ 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`) // // `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 +530,10 @@ 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 + } let options = try Options(Array(CommandLine.arguments.dropFirst())) let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .prettyPrinted] diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift index fe86f41cf0..1d9bb3080e 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift @@ -87,8 +87,12 @@ struct QwenTensorParallelBatchBudget { bound(product([plan.expertsPerToken, plan.hiddenSize, 4]), count: lanes), bound(product([plan.hiddenSize, 4]), count: lanes), ]) : 0) + // A merged prompt step's further frames in flight (one prompt step at a time, shared). + let wavefront = try QwenTensorParallelPromptWavefront.inFlightBytes(plan: plan, chunkTokens: chunkSize, + allocationBound: allocationBound) let shared = try sum([scalar.fusionBytes, transient, logits, - scalar.projectionConstantBytes, batchConstants, poolSlack, prefix.residentBytes, packing, promptGather]) + scalar.projectionConstantBytes, batchConstants, poolSlack, prefix.residentBytes, packing, promptGather, + wavefront]) // A one-token batch can gather more bytes than a short prompt frame. // Control limbs and retirement votes also travel in the sealed codec. let payload = max(scalar.allowance.maximumCollectivePayloadBytes, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift index 72dbcb7ea8..4066af3dcd 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift @@ -14,12 +14,18 @@ protocol QwenTensorParallelBatchLane: AnyObject { var reusedPrefixTokens: Int { get } var storedPrefixFrontiers: [Int] { get } var canSelectNext: Bool { get } + func promptStep(frames: Int) -> QwenLayerStageFrame? + func promptStep(tokens: Int) -> QwenLayerStageFrame? } extension QwenTensorParallelBatchLane { var reusedPrefixTokens: Int { 0 } var storedPrefixFrontiers: [Int] { [] } var canSelectNext: Bool { nextFrame?.phase == .decode } + /// The prompt step of up to `frames` consecutive frames (`QwenTensorParallelPromptWavefront`). + func promptStep(frames: Int) -> QwenLayerStageFrame? { nextFrame } + /// The planned prompt step of `tokens`, if it is one this lane may run. + func promptStep(tokens: Int) -> QwenLayerStageFrame? { nextFrame.flatMap { $0.tokenCount == tokens ? $0 : nil } } } /// Both ranks run every forward. Selection returns the same token to both; @@ -133,7 +139,7 @@ final class QwenTensorParallelBatchDriver [QwenLayerStageFrame] { + guard !retired else { return [] } + let merges = QwenTensorParallelPromptWavefront.merges(model: model, request: request, + mediaInputs: inputs != nil, packedStorage: state.packedStorage) + return QwenTensorParallelPromptWavefront.frames(request: request, from: schedule.nextSequence, + frontiers: captureFrontier > 0 ? [captureFrontier] : [], limit: merges ? limit : 1) + } + + /// Runs the planned prompt step `step` (`promptFrames`), its frames as one graph. + func prefill(step: QwenLayerStageFrame, check: () throws -> Void) throws -> MLXArray? { + let frames = promptFrames(limit: QwenTensorParallelPromptWavefront.maximumFrames) + guard let count = (1...max(1, frames.count)).first(where: { + QwenTensorParallelPromptWavefront.step(Array(frames.prefix($0))) == step + }) else { throw ProbeError("Qwen TP prompt step differs from its frames") } + return try prompt(capturingHidden: false, frames: count, check: check).logits + } + func prefillForMTP(check: () throws -> Void) throws -> QwenTensorParallelMTPPromptResult { guard inputs == nil, request.qwenMedia == nil else { throw ProbeError("Qwen TP media cannot enter assistant history") } let result = try prompt(capturingHidden: true, check: check) @@ -119,13 +139,20 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { return .init(hidden: hidden, logits: result.logits) } - private func prompt(capturingHidden: Bool, check: () throws -> Void) throws -> (hidden: MLXArray?, logits: MLXArray?) { + private func prompt(capturingHidden: Bool, frames count: Int = 1, + check: () throws -> Void) throws -> (hidden: MLXArray?, logits: MLXArray?) { try MLX.withError { error in func checked() throws { try error.check(); try check() } - let proposed = try request.frame(sequence: schedule.nextSequence) - let frame = try schedule.admitPrefill(count: proposed.tokenCount, offset: proposed.tokenOffset, - final: proposed.finalPromptChunk) - guard !retired, !failed, window?.isIdle ?? true, frame.phase == .prefill, state.committedTokens == frame.tokenOffset else { + // Each frame is admitted on the schedule as the frames before it leave it. + var planned = schedule, frames: [QwenLayerStageFrame] = [] + for _ in 0.. MLXArray in + if frames.count > 1 { + return QwenTensorParallelPromptWavefront.forward(model: self.model, request: self.request, + frames: frames, caches: caches, evaluation: evaluation) + } + return Qwen35LayerSubmission.$stride.withValue(stride) { () -> MLXArray in let native = self.model.model if capturingHidden { let result = native.cbv2ForwardWithHidden(input, @@ -194,7 +225,7 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { } eval(hidden); try checked() } - try schedule.commit(frame) + schedule = planned if committedTokens == captureFrontier { try capturePrefix(check: checked) } if let timing, case .shard(let rank, _) = model.role { let clock = promptClock ?? QwenTensorParallelPromptClock() diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift index 2bf63d24ca..c1ee20d713 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift @@ -132,8 +132,15 @@ final class QwenTensorParallelRowLinear: QuantizedLinear, Qwen35BatchDecodeProje eval(partial) Stream.gpu.synchronize() } - return Self.finish(reduction.value.allSum(partial), dtype: x.dtype) + let summed = reduction.value.allSum(partial) + Self.issuedSums?.sums.append(summed) + return Self.finish(summed, dtype: x.dtype) } + + /// A prompt wavefront's phase (`QwenTensorParallelPromptWavefront`): the + /// raw all-sums its projections issue, before rounding, so the phase can + /// submit them before the next chunk is built. nil changes nothing. + @TaskLocal static var issuedSums: QwenTensorParallelIssuedSums? } /// Diagnostic only: a rank's shard with no peer. `allSum` returns this rank's diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift index 0366507f2d..5cafe9bdb6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift @@ -28,6 +28,15 @@ final class QwenTensorParallelNativeBatchLane: QwenTensorParallelBatchLane { guard !session.retired else { return nil } return try? session.request.frame(sequence: session.schedule.nextSequence) } + /// An assisted lane's prompt keeps one frame a step (its history takes each frame's hidden rows). + func promptStep(frames: Int) -> QwenLayerStageFrame? { + QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: assistant == nil ? frames : 1)) + } + func promptStep(tokens: Int) -> QwenLayerStageFrame? { + let frames = session.promptFrames(limit: assistant == nil ? QwenTensorParallelPromptWavefront.maximumFrames : 1) + return (1...max(1, frames.count)).lazy.compactMap { QwenTensorParallelPromptWavefront.step(Array(frames.prefix($0))) } + .first { $0.tokenCount == tokens } + } var committedTokens: Int { session.committedTokens } var isClosed: Bool { session.retired && session.state.isClosed && resourcesReleased } } @@ -281,10 +290,10 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> Int? { - guard lane.nextFrame == frame else { throw ProbeError("Qwen TP native prefill frame changed") } + guard lane.promptStep(tokens: frame.tokenCount) == frame else { throw ProbeError("Qwen TP native prefill frame changed") } let output: MLXArray? if let decoder = lane.assistant { output = try decoder.prefill(check: check) } - else { output = try lane.session.prefill(check: check) } + else { output = try lane.session.prefill(step: frame, check: check) } completedPrefill() guard let logits = output else { return nil } let token = try select(logits, lanes: [lane], check: check)[0] diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift index 5e2b780272..17dd113593 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift @@ -47,6 +47,8 @@ public enum QwenTensorParallelPrefillBench { public var operations = [0] /// Prefill layer-submission strides (`QwenTensorParallelBatchSession.prefillStride`; 0: one evaluation a frame). public var strides = [0] + /// Frames a prompt step merges at most (`QwenTensorParallelPromptWavefront`; 1: one frame a step). + public var wavefronts = [1] public var modes: [Mode] = [.local] /// Prefills of each configuration (the first is reported apart when more than one). public var repeats = 1 @@ -117,8 +119,8 @@ public enum QwenTensorParallelPrefillBench { + " load_s=\(format(model.loadSeconds)) active_gb=\(String(format: "%.2f", Double(Memory.activeMemory) / 1e9))") let tokens = prompt(options.promptTokens, vocabulary: model.plan.vocabularySize) - /// One whole prompt prefilled on a fresh request: per frame timings and the final logits' digest. - func prefill(chunk: Int, observeLayers: ((Int) -> Bool)? = nil) + /// One whole prompt prefilled on a fresh request: per step timings and the final logits' digest. + func prefill(chunk: Int, wavefront: Int = 1, observeLayers: ((Int) -> Bool)? = nil) throws -> (frames: [FrameTiming], digest: String, layerRows: [(frame: Int, offset: Int, times: [(Int, Double)])]) { let budget = options.promptTokens + 8 let host = try CBv2StageKVHost(model: model.model, kind: .paged, lanes: 1, @@ -154,7 +156,11 @@ public enum QwenTensorParallelPrefillBench { layerRecorder.last = now }) { try session.prefill(check: {}) } } - return try session.prefill(check: {}) + guard wavefront > 1, + let step = QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: wavefront)) else { + return try session.prefill(check: {}) + } + return try session.prefill(step: step, check: {}) } let ended = phases.now() let build = phases.span("graphConstruction.begin", "graphConstruction.end") @@ -189,13 +195,15 @@ public enum QwenTensorParallelPrefillBench { var digests: [Int: Set] = [:] for chunk in options.chunks { for operations in options.operations { - for stride in options.strides { + for (stride, wavefront) in options.strides.flatMap({ s in options.wavefronts.map { (s, $0) } }) { for mode in options.modes { reduction.mode = mode for repeatIndex in 0 ..< max(1, options.repeats) { reduction.reset() let run = { - try QwenTensorParallelBatchSession.$prefillStride.withValue(stride) { try prefill(chunk: chunk) } + try QwenTensorParallelBatchSession.$prefillStride.withValue(stride) { + try prefill(chunk: chunk, wavefront: wavefront) + } } let result = try (operations > 0 ? GPU.withCommandBufferLimits(.init(operations: operations, megabytes: 1 << 20), run) @@ -205,7 +213,7 @@ public enum QwenTensorParallelPrefillBench { digests[chunk, default: []].insert(result.digest) let middle = frames.count > 2 ? Array(frames.dropFirst().dropLast()) : frames log("\(label) path=prefill chunk=\(chunk) ops=\(operations == 0 ? "process" : String(operations))" - + " stride=\(stride) mode=\(mode.rawValue) repeat=\(repeatIndex)" + + " stride=\(stride) wavefront=\(wavefront) mode=\(mode.rawValue) repeat=\(repeatIndex)" + " total_ms=\(format(total)) tok_s=\(format(Double(options.promptTokens) / total * 1000))" + " frames=\(frames.count)" + " first_ms=\(format(frames.first?.wall ?? .nan)) last_ms=\(format(frames.last?.wall ?? .nan))" @@ -217,7 +225,7 @@ public enum QwenTensorParallelPrefillBench { + " digest=\(result.digest)") let curve = frames.enumerated().filter { $0.offset % max(1, frames.count / 8) == 0 || $0.offset == frames.count - 1 } .map { "\($0.offset * chunk):\(format($0.element.wall))" }.joined(separator: ",") - log("\(label) path=prefill-curve chunk=\(chunk) ops=\(operations == 0 ? "process" : String(operations)) stride=\(stride) mode=\(mode.rawValue) offset_ms=\(curve)") + log("\(label) path=prefill-curve chunk=\(chunk) ops=\(operations == 0 ? "process" : String(operations)) stride=\(stride) wavefront=\(wavefront) mode=\(mode.rawValue) offset_ms=\(curve)") } Memory.clearCache() } @@ -341,6 +349,66 @@ public enum QwenTensorParallelPrefillBench { var best: Double { ms.values.min() ?? .nan } } + /// A real pair's rank (`model`'s reduction is its group, for example the + /// loopback ring with sealed sums): the same prompt prefilled one frame a + /// step and in merged steps of up to each of `wavefronts` frames + /// (`QwenTensorParallelPromptWavefront`). Logs each run's step times and + /// the digests of its final logits, attention rows and recurrent states; + /// returns whether every run left this rank the same digests. + public static func pair(model: QwenTensorParallelModel, configuration: Data, promptTokens: Int, chunk: Int, + wavefronts: [Int], repeats: Int, log: (String) -> Void) throws -> Bool { + guard case .shard(let rank, _) = model.role else { throw ProbeError("The wavefront pair runs a rank shard") } + let tokens = prompt(promptTokens, vocabulary: model.plan.vocabularySize) + let budget = promptTokens + 8 + let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-wavefront-pair", + vocabularySize: model.plan.vocabularySize, hiddenSize: model.plan.hiddenSize, activationDType: "bfloat16", + maximumPromptTokens: promptTokens, maximumChunkTokens: chunk, maximumOutputTokens: budget - promptTokens, + maximumContextTokens: budget) + func digest(_ arrays: [MLXArray]) -> String { + var hash = SHA256() + for array in arrays { eval(array); hash.update(data: array.asData(access: .copy).data) } + return hash.finalize().prefix(8).map { String(format: "%02x", $0) }.joined() + } + var seen: (logits: String, rows: String, recurrent: String)? + var same = true + try prefillWarmup(model: model, configuration: configuration, chunk: min(chunk, promptTokens)) + for limit in wavefronts { + for repeatIndex in 0 ..< max(1, repeats) { + Memory.clearCache() + let host = try CBv2StageKVHost(model: model.model, kind: .paged, lanes: 1, + maximumTokensPerRequest: budget, maximumChunkTokens: chunk) + let request = try QwenLayerStageGenerationRequest(profile: profile, requestID: UUID(), + promptTokenIDs: tokens, chunkSize: chunk, outputCount: budget - promptTokens, stopTokenIDs: []) + let session = try QwenTensorParallelBatchSession(model: model, configuration: configuration, + host: host, request: request) + defer { try? session.retire() } + var steps: [(tokens: Int, ms: Double)] = [] + var logits: MLXArray? + while session.schedule.committedPromptTokens < promptTokens { + let frames = session.promptFrames(limit: limit) + guard let step = QwenTensorParallelPromptWavefront.step(frames) else { throw ProbeError("No prompt step") } + let started = DispatchTime.now().uptimeNanoseconds + logits = try session.prefill(step: step, check: {}) ?? logits + if let logits { eval(logits) } + steps.append((step.tokenCount, ms(DispatchTime.now().uptimeNanoseconds - started))) + } + let total = steps.reduce(0) { $0 + $1.ms } + let rows = session.state.rows.compactMap { $0?.snapshot() }.flatMap { [$0.keys, $0.values] } + let committed = session.state.recurrent.confirmedStateSnapshot() ?? [:] + let recurrent = committed.keys.sorted().flatMap { [committed[$0]!.conv!, committed[$0]!.ssm!] } + let value = (digest([logits ?? MLXArray(0)]), digest(rows), digest(recurrent)) + if let seen { same = same && seen == value } else { seen = value } + let perFrame = steps.map { $0.ms * Double(chunk) / Double($0.tokens) } + log("qwen-tp-wavefront-v1 rank=\(rank) limit=\(limit) repeat=\(repeatIndex) tokens=\(promptTokens)" + + " steps=\(steps.count) total_ms=\(format(total)) tok_s=\(format(Double(promptTokens) / total * 1000))" + + " per_\(chunk)_median_ms=\(format(median(perFrame))) first_step_ms=\(format(steps.first?.ms ?? .nan))" + + " logits=\(value.0) rows=\(value.1) recurrent=\(value.2)") + } + } + log("qwen-tp-wavefront-v1 rank=\(rank) digest-check \(same ? "same-bytes" : "DIFFERENT")") + return same + } + static func isFullAttention(model: QwenTensorParallelModel, layer: Int) -> Bool { (layer + 1) % model.plan.fullAttentionInterval == 0 } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift new file mode 100644 index 0000000000..56cbf5e50d --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift @@ -0,0 +1,110 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// The raw all-sums the row-parallel projections of one wavefront phase issued +/// (`QwenTensorParallelRowLinear.issuedSums`). Confined to the thread that +/// builds the forward, which binds it and drains it after each phase. +final class QwenTensorParallelIssuedSums: @unchecked Sendable { + var sums: [MLXArray] = [] +} + +/// Consecutive prompt frames of one plain text lane prefilled as one graph, +/// layer by layer (`Qwen35PromptWavefront`): a frame's mixer, its sealed sum +/// submitted at once, the next frame's mixer while that sum crosses the link; +/// then the MLPs the same way. At each layer a frame reads the attention rows +/// and the recurrent state the frame before it left, so every kernel sees the +/// frame's own rows: logits, KV rows, conv and SSM states are the per-frame +/// prefill's bytes, and each rank issues the same sums (two a layer a frame) +/// in the same order. Only when the GPU and the link run each piece changes. +enum QwenTensorParallelPromptWavefront { + /// Frames one prompt step runs at most: 8 x 512 = 4,096 tokens a graph. + static let maximumFrames = 8 + /// Frames one prompt step runs while another lane decodes, so a decoding + /// lane waits for one merged step about as long as for one frame alone. + static let framesBesideDecoding = 2 + /// Diagnostic only: `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` runs one frame a + /// step, as before. Bound into the load agreement (`agreementFields`). + static let enabled = ProcessInfo.processInfo.environment["DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT"] != "0" + /// A bench or test's own choice (nil: `enabled`). + @TaskLocal static var enabledOverride: Bool? + static var isEnabled: Bool { enabledOverride ?? enabled } + + /// Both ranks plan and validate merged prompt steps alike, or the pair refuses to load. + static var agreementFields: [String] { + ["qwen-tensor-parallel-prompt-wavefront-v1", + isEnabled ? "frames-\(maximumFrames)-beside-decoding-\(framesBesideDecoding)" : "off"] + } + + /// The frames one prompt step runs from frame `sequence`: consecutive + /// prompt frames, at most `limit`, ending at the prompt's end or at the + /// first capture frontier (`frontiers`, the capture plan's boundaries) + /// they reach. Empty when frame `sequence` is not a prompt frame. + static func frames(request: QwenLayerStageGenerationRequest, from sequence: Int, frontiers: [Int], + limit: Int) -> [QwenLayerStageFrame] { + guard let first = try? request.frame(sequence: sequence), first.phase == .prefill else { return [] } + var frames = [first] + while frames.count < limit, let last = frames.last, !last.finalPromptChunk, + !frontiers.contains(last.tokenOffset + last.tokenCount), + let next = try? request.frame(sequence: last.sequence + 1), next.phase == .prefill { + frames.append(next) + } + return frames + } + + /// What one merged step holds beyond a lone frame, charged with the + /// owner's shared prompt workspace (`QwenTensorParallelBatchBudget`): for + /// each further frame, its two FP32 partials and two FP32 sums in flight + /// and its BF16 residual rows, five times the frame's collective payload, + /// allocator-bounded. Zero for routed experts, whose frames never merge. + static func inFlightBytes(plan: QwenTensorParallelPlan, chunkTokens: Int, + allocationBound: (Int) throws -> Int) throws -> Int { + guard !plan.routedExperts else { return 0 } + let payload = try QwenLongPrefillCheckedBytes.product([chunkTokens, plan.maximumPartialBytesPerToken]) + return try QwenLongPrefillCheckedBytes.product([allocationBound(payload), 5, maximumFrames - 1]) + } + + /// The step the driver plans and both ranks validate for `frames`: the + /// first frame's sequence and offset, every frame's tokens, the last's final flag. + static func step(_ frames: [QwenLayerStageFrame]) -> QwenLayerStageFrame? { + guard let first = frames.first, let last = frames.last else { return nil } + return .init(sequence: first.sequence, phase: .prefill, tokenOffset: first.tokenOffset, + tokenCount: frames.reduce(0) { $0 + $1.tokenCount }, finalPromptChunk: last.finalPromptChunk) + } + + /// Whether a lane's frames merge: text without media inputs, native rows + /// (a packed step is checked whole before it runs), a dense model. + static func merges(model: QwenTensorParallelModel, request: QwenLayerStageGenerationRequest, + mediaInputs: Bool, packedStorage: Bool) -> Bool { + isEnabled && !mediaInputs && request.qwenMedia == nil && !packedStorage + && Qwen35PromptWavefront.supports(model.model) + } + + /// `frames`' forward inside one `CBv2OwnedRequestState.run`: the + /// wavefront, each phase's sums submitted as soon as it is built; returns + /// what the last frame's own forward returns (its evaluation handle, or + /// the final prompt row's logits from the whole frame's head, as + /// `QwenTensorParallelBatchSession.prompt` keeps them). + static func forward(model: QwenTensorParallelModel, request: QwenLayerStageGenerationRequest, + frames: [QwenLayerStageFrame], caches: [any CBv2AttendingLayerCache], + evaluation: CBv2RecurrentStateEvaluation) -> MLXArray { + let chunks = frames.map { frame in + MLXArray(request.promptTokenIDs[frame.tokenOffset ..< (frame.tokenOffset + frame.tokenCount)] + .map(Int32.init)).reshaped([1, frame.tokenCount]) + } + let final = frames.last?.finalPromptChunk ?? false + let issued = QwenTensorParallelIssuedSums() + let outputs = QwenTensorParallelRowLinear.$issuedSums.withValue(issued) { + Qwen35PromptWavefront.prefill(model.model, chunks: chunks, finalChunk: final, + caches: caches.map { $0 as! any KVCache }, recurrentState: evaluation) { _, _, _ in + guard !issued.sums.isEmpty else { return } + asyncEval(issued.sums) + issued.sums.removeAll() + } + } + // Every earlier frame's last rows join the evaluation the run waits on. + asyncEval(Array(outputs.dropLast())) + return final ? outputs[outputs.count - 1][0..., -1, 0...] : outputs[outputs.count - 1] + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift index 88a70fcc69..da027b8459 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift @@ -193,6 +193,7 @@ public final class QwenTensorParallelResidentRuntime { + QwenTensorParallelTargetWindow.agreementFields + QwenTensorParallelPlan.arithmeticAgreementFields(routedExperts: admission.specification.routedExperts != nil) + QwenTensorParallelBatchSession.decodeAgreementFields + + QwenTensorParallelPromptWavefront.agreementFields + ["qwen-tensor-parallel-prefix-v2", prefixEnabled ? "on" : "off"] + (prefixEnabled ? prefixRecords.loadAgreementFields : []) + (mediaEnabled ? [ClusterQwenMedia.contract, Qwen3VLMediaProcessor.policyID] : []) diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift index f9e10a81df..d00769d358 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift @@ -43,9 +43,12 @@ struct QwenTensorParallelBatchBudgetTests { #expect(candidate.perLaneStateBytes < scalar.stateBytes) #expect(candidate.allowance.requestBytesExcludingCollectives == lanes * candidate.perLaneStateBytes + candidate.sharedBytesExcludingCollectives) let logits = 3 * bound(lanes * plan.vocabularySize * 4) + // A merged prompt step's seven further frames: five frames' FP32 payload each. + let wavefront = plan.routedExperts ? 0 : 7 * 5 * bound(chunk * plan.maximumPartialBytesPerToken) + #expect(wavefront == 367_001_600, "the 27B rank's merged-step charge at 512-row frames") #expect(candidate.sharedBytesExcludingCollectives == scalar.fusionBytes + scalar.transientBytes + logits + 2 * scalar.projectionConstantBytes + candidate.pagedPoolSlackBytes + candidate.prefix.residentBytes - + candidate.promptGatherBytes) + + candidate.promptGatherBytes + wavefront) #expect(candidate.pagedPoolSlackBytes >= 2 * CBv2StageKVHost.segmentBytes) // The underlying host's entire admitted page capacity, its gather // and replacement pages fit inside the full state charges, at every diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift new file mode 100644 index 0000000000..c241683550 --- /dev/null +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift @@ -0,0 +1,341 @@ +import Foundation +import MLX +@testable import MLXLLM +import MLXLMCommon +import MLXNN +import Testing +@testable import DarkbloomClusterRuntime + +/// A tensor-parallel prompt step that merges consecutive frames into one +/// wavefront graph (`QwenTensorParallelPromptWavefront`) leaves the bytes the +/// frames leave run one at a time: logits, every attention row, every conv and +/// SSM state and the prefix capture, on both ranks, with the same collectives. +@Suite(.serialized) +struct QwenTensorParallelPromptWavefrontTests { + private static func request(prompt: Int, chunk: Int = 512, output: Int = 16, reused: Int = 0) throws + -> QwenLayerStageGenerationRequest { + let chunk = min(chunk, prompt) + let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-prompt-wavefront", vocabularySize: 256, + hiddenSize: 2048, activationDType: "bfloat16", maximumPromptTokens: prompt, maximumChunkTokens: chunk, + maximumOutputTokens: output, maximumContextTokens: prompt + output) + let request = try QwenLayerStageGenerationRequest(profile: profile, requestID: UUID(), + promptTokenIDs: (0.. MLXArray { + let values = array.asType(.float32).asArray(Float.self) + condition.lock() + while leaving > 0 { condition.wait() } + let generation = step + inputs[rank] = values; shapes[rank] = array.shape + if inputs.count == 2 { + precondition(shapes[0] == shapes[1], "ranks summed different shapes") + result = zip(inputs[0]!, inputs[1]!).map(+) + leaving = 2; condition.broadcast() + } else { + let deadline = Date().addingTimeInterval(120) + while leaving == 0 && step == generation { + precondition(condition.wait(until: deadline), "TP rank failed to meet its peer") + } + } + let output = result + leaving -= 1 + if leaving == 0 { inputs = [:]; shapes = [:]; result = []; step += 1; condition.broadcast() } + condition.unlock() + return MLXArray(output, array.shape).asType(array.dtype) + } + } + final class Rank: QwenTensorParallelReduction, @unchecked Sendable { + let rank: Int, size = 2 + let shared: Rendezvous + var collectives = 0 + init(_ rank: Int, _ shared: Rendezvous) { self.rank = rank; self.shared = shared } + func allSum(_ value: MLXArray) -> MLXArray { collectives += 1; return shared.sum(value, rank: rank) } + } + + /// One rank's outcome: the last logits, every row's keys and values, every + /// recurrent state, the prefix capture, the decoding lane's logits per step + /// and the collectives the prompt's steps issued. + struct Outcome: Equatable { + var logits = Data() + var rows: [Data] = [] + var recurrent: [Data] = [] + var capture: [Data] = [] + var decoded: [Data] = [] + var collectives = 0 + var steps = 0 + } + + private static func bytes(_ a: MLXArray) -> Data { eval(a); return a.asData(access: .copy).data } + + private static func state(of session: QwenTensorParallelBatchSession) -> (rows: [Data], recurrent: [Data]) { + var rows: [Data] = [] + for row in session.state.rows { + let snapshot = row!.snapshot() + rows += [Data("\(snapshot.offset)".utf8), bytes(snapshot.keys), bytes(snapshot.values)] + } + let committed = session.state.recurrent.confirmedStateSnapshot() ?? [:] + let recurrent = committed.keys.sorted().flatMap { [bytes(committed[$0]!.conv!), bytes(committed[$0]!.ssm!)] } + return (rows, recurrent) + } + + /// A prompt of `prompt` tokens on both ranks, each step merging up to + /// `limit` frames (1: today's one frame a step, through `prefill(check:)`). + /// With `decodeBeside`, a 300-token lane is prefilled first and decodes one + /// fixed token before each prompt step and after the last. With + /// `restoreAt`, the prompt resumes from the state a donor run one frame a + /// step kept there (a prefix-cache hit). + private static func run(_ models: [QwenTensorParallelModel], _ ranks: [Rank], configuration: Data, + kind: ClusterStageKVBackendKind, prompt: Int, limit: Int, captureFrontier: Int = 0, + decodeBeside: Bool = false, restoreAt: Int = 0) throws -> [Outcome] { + let threads = TensorParallelRankThreads() + let id = UUID(), besideID = UUID() + let results = (0..<2).map { _ in RankResult() } + for rank in ranks { rank.collectives = 0 } + threads.run { rank in + Device.withDefaultDevice(.gpu) { + do { + let model = models[rank] + let host = try CBv2StageKVHost(model: model.model, kind: kind, lanes: decodeBeside ? 2 : 1, + maximumTokensPerRequest: prompt + 16, maximumChunkTokens: 512) + var target = try Self.request(prompt: prompt) + target = try QwenLayerStageGenerationRequest(profile: target.profile, requestID: id, + promptTokenIDs: target.promptTokenIDs, chunkSize: 512, outputCount: 16, stopTokenIDs: []) + let bound: (Int) throws -> Int = { (($0 + 16_383) / 16_384) * 16_384 } + var restored: QwenTensorParallelBatchPrefixState? + if restoreAt > 0 { + let donorHost = try CBv2StageKVHost(model: model.model, kind: kind, lanes: 1, + maximumTokensPerRequest: prompt + 16, maximumChunkTokens: 512) + let donor = try QwenTensorParallelBatchSession(model: model, configuration: configuration, + host: donorHost, request: target, captureFrontier: restoreAt, captureLimitBytes: 256 << 20, + allocationBound: bound) + while donor.schedule.committedPromptTokens < prompt { _ = try donor.prefill(check: {}) } + try donor.retire() + restored = try #require(try donor.takeCapturedPrefix()) + target = try target.planned(reusedPrefix: restoreAt, splitFinalToken: false) + } + let session = try QwenTensorParallelBatchSession(model: model, configuration: configuration, + host: host, request: target, restored: restored, captureFrontier: captureFrontier, + captureLimitBytes: captureFrontier > 0 ? 256 << 20 : 0, allocationBound: bound) + var beside: QwenTensorParallelBatchSession? + if decodeBeside { + let short = try Self.request(prompt: 300) + let other = try QwenLayerStageGenerationRequest(profile: short.profile, requestID: besideID, + promptTokenIDs: short.promptTokenIDs, chunkSize: short.chunkSize, outputCount: 16, + stopTokenIDs: []) + beside = try QwenTensorParallelBatchSession(model: model, configuration: configuration, + host: host, request: other) + _ = try beside!.prefill(check: {}) + } + var outcome = Outcome() + func decodeBesideStep() throws { + guard let beside else { return } + let token = 11 + outcome.decoded.count + outcome.decoded.append(bytes(try QwenTensorParallelBatchSession.decode([beside], + tokens: [token], check: {}))) + } + var last: MLXArray? + while session.schedule.committedPromptTokens < prompt { + try decodeBesideStep() + let issued = ranks[rank].collectives + defer { outcome.collectives += ranks[rank].collectives - issued; outcome.steps += 1 } + if limit == 1 { + last = try session.prefill(check: {}) ?? last + } else { + let step = try #require(QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: limit))) + last = try session.prefill(step: step, check: {}) ?? last + } + } + try decodeBesideStep() + outcome.logits = bytes(try #require(last)) + (outcome.rows, outcome.recurrent) = state(of: session) + try session.retire() + if let captured = try session.takeCapturedPrefix() { + outcome.capture = [Data("\(captured.committedTokens)".utf8)] + + captured.attention.keys.sorted().flatMap { [bytes(captured.attention[$0]!.keys), + bytes(captured.attention[$0]!.values)] } + + captured.recurrent.keys.sorted().flatMap { [bytes(captured.recurrent[$0]!.conv), + bytes(captured.recurrent[$0]!.ssm)] } + } + try beside?.retire() + results[rank].outcome = outcome + } catch { results[rank].failure = error } + } + } + for result in results { if let failure = result.failure { throw failure } } + return try results.map { try #require($0.outcome) } + } + + /// One rank thread's own result. + final class RankResult: @unchecked Sendable { + var outcome: Outcome? + var failure: Error? + } + + /// Both ranks' temporaries per prompt step of `limit` frames (the largest + /// step's peak above the settled allocation before and after it). + private static func promptTransient(_ models: [QwenTensorParallelModel], configuration: Data, prompt: Int, + limit: Int) throws -> Int { + let threads = TensorParallelRankThreads() + let id = UUID() + let sessions = try (0..<2).map { rank -> QwenTensorParallelBatchSession in + let host = try CBv2StageKVHost(model: models[rank].model, kind: .paged, lanes: 1, + maximumTokensPerRequest: prompt + 16, maximumChunkTokens: 512) + let shape = try Self.request(prompt: prompt) + let request = try QwenLayerStageGenerationRequest(profile: shape.profile, requestID: id, + promptTokenIDs: shape.promptTokenIDs, chunkSize: 512, outputCount: 16, stopTokenIDs: []) + return try QwenTensorParallelBatchSession(model: models[rank], configuration: configuration, host: host, + request: request) + } + defer { for session in sessions { try? session.retire() } } + var largest = 0 + while sessions[0].schedule.committedPromptTokens < prompt { + Stream.gpu.synchronize(); Memory.clearCache() + let before = Memory.activeMemory + Memory.peakMemory = 0 + let results = (0..<2).map { _ in RankResult() } + threads.run { rank in + Device.withDefaultDevice(.gpu) { + do { + let session = sessions[rank] + let step = try #require(QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: limit))) + if let logits = try session.prefill(step: step, check: {}) { eval(logits) } + } catch { results[rank].failure = error } + } + } + for result in results { if let failure = result.failure { throw failure } } + Stream.gpu.synchronize() + largest = max(largest, Memory.peakMemory - max(before, Memory.activeMemory)) + Memory.clearCache() + } + return largest + } + + /// A merged step of eight frames allocates no more temporaries than the + /// largest lone frame plus the further frames' charge + /// (`QwenTensorParallelPromptWavefront.inFlightBytes`, which LOAD and each + /// request's charge add to the shared prompt workspace), measured on both + /// in-process ranks of a paged one-lane host at a 4,096-token prompt. + @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1")) + func mergedStepTemporariesStayWithinTheirCharge() throws { + try Device.withDefaultDevice(.gpu) { + let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 2048, layers: 8, heads: 8, kvHeads: 2, + vocabulary: 256) + var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any] + var text = root["text_config"] as! [String: Any] + text["max_position_embeddings"] = 8192; root["text_config"] = text + let configuration = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) + let wire = Rendezvous() + let models = try (0..<2).map { rank in + try QwenTensorParallelModel.assemble(configurationData: configuration, + role: .shard(rank: rank, size: 2), reduction: Rank(rank, wire)) { _, keep in + for (name, value) in fixture.tensors { try keep(name, value) } + } + } + let single = try Self.promptTransient(models, configuration: configuration, prompt: 4096, limit: 1) + let merged = try Self.promptTransient(models, configuration: configuration, prompt: 4096, + limit: QwenTensorParallelPromptWavefront.maximumFrames) + let charge = try QwenTensorParallelPromptWavefront.inFlightBytes(plan: models[0].plan, chunkTokens: 512, + allocationBound: { (($0 + 16_383) / 16_384) * 16_384 }) + print("darkbloom-tp-wavefront-memory-v1 frames=\(QwenTensorParallelPromptWavefront.maximumFrames)" + + " single_pair=\(single) merged_pair=\(merged) in_flight_per_rank=\(charge)") + #expect(single > 0 && merged <= single + 2 * charge, "a merged step exceeded a frame and its charge") + } + } + + /// Hybrid shards (six recurrent, two attention layers) over the in-process + /// pair. Each case runs today's one frame a step, then merged steps: + /// - a prompt ending mid-frame (1,100 tokens: one step of three frames), + /// paged (the one-lane host's prefill mirror) and contiguous; + /// - a capture frontier inside the prompt (2,600 tokens, kept at 1,024: + /// steps of two and four frames, the capture taken between them); + /// - beside a decoding lane on a two-lane paged host (each prompt history + /// gathered from its pages): two frames a step, the decoding lane's + /// logits unchanged at every step; + /// - after a prefix restored at 1,024 tokens: the suffix's four frames in one step. + @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1")) + func mergedFramesKeepEveryBit() throws { + try Device.withDefaultDevice(.gpu) { + let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 2048, layers: 8, heads: 8, kvHeads: 2, + vocabulary: 256) + var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any] + var text = root["text_config"] as! [String: Any] + text["max_position_embeddings"] = 8192; root["text_config"] = text + let configuration = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) + let wire = Rendezvous() + let ranks = (0..<2).map { Rank($0, wire) } + let models = try (0..<2).map { rank in + try QwenTensorParallelModel.assemble(configurationData: configuration, + role: .shard(rank: rank, size: 2), reduction: ranks[rank]) { _, keep in + for (name, value) in fixture.tensors { try keep(name, value) } + } + } + #expect(Qwen35PromptWavefront.supports(models[0].model)) + let cases: [(name: String, kind: ClusterStageKVBackendKind, prompt: Int, limit: Int, capture: Int, beside: Bool, + restore: Int)] = [ + ("mid-frame end, paged", .paged, 1_100, 8, 0, false, 0), + ("mid-frame end, contiguous", .contiguous, 1_100, 8, 0, false, 0), + ("capture frontier", .paged, 2_600, 8, 1_024, false, 0), + ("beside a decoding lane", .paged, 1_100, QwenTensorParallelPromptWavefront.framesBesideDecoding, 0, true, 0), + ("restored prefix", .paged, 2_600, 8, 0, false, 1_024), + ] + for item in cases { + let before = try Self.run(models, ranks, configuration: configuration, kind: item.kind, + prompt: item.prompt, limit: 1, captureFrontier: item.capture, decodeBeside: item.beside, + restoreAt: item.restore) + let after = try Self.run(models, ranks, configuration: configuration, kind: item.kind, + prompt: item.prompt, limit: item.limit, captureFrontier: item.capture, decodeBeside: item.beside, + restoreAt: item.restore) + for rank in 0..<2 { + let x = before[rank], y = after[rank] + #expect(x.logits == y.logits, "\(item.name): final logits, rank \(rank)") + #expect(x.rows == y.rows && x.rows.count == 6, "\(item.name): attention rows, rank \(rank)") + #expect(x.recurrent == y.recurrent && x.recurrent.count == 12, "\(item.name): conv/SSM, rank \(rank)") + #expect(x.capture == y.capture && x.capture.isEmpty == (item.capture == 0), + "\(item.name): prefix capture, rank \(rank)") + #expect(x.collectives == y.collectives && x.collectives > 0, + "\(item.name): the prompt's collectives, rank \(rank)") + #expect(y.steps < x.steps, "\(item.name): \(y.steps) merged steps against \(x.steps) frames") + // Two merged steps (three decodes) against three frames (four): each decode is the lane's own. + #expect(y.decoded.count == (item.beside ? 3 : 0) && x.decoded.prefix(y.decoded.count).elementsEqual(y.decoded), + "\(item.name): the decoding lane's logits, rank \(rank)") + } + #expect(before[0].logits != before[1].logits, "\(item.name): ranks hold distinct vocabulary halves") + } + } + } +} diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index ad2ed74b7d..df6fc5f122 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit ad2ed74b7dbd60fa7f679dd81c8996dba89bf415 +Subproject commit df6fc5f122a9a9df556c1ae3a5291634ef4b3514 From 3556a33747d46fd57ea5c0373b9f51d1ce220e2f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:31:46 -0800 Subject: [PATCH 33/58] docs: Qwen TP prompt wavefront New inference.md section "Qwen tensor-parallel prompt wavefront": the merged prompt step, its planning, graph and commit, its invariants (per-frame bytes, the same sealed FP32 sums, which lanes merge, the memory charge, the load agreement), failure modes, diagnostics and the loopback measurement. The request-owned lanes section links it from the driver paragraph; hardware-support.md adds the merged step's charge to the TP batch admission boundary. Changelog fragment qwen27-tp-prefill. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-prefill.md | 16 ++++ docs/architecture/hardware-support.md | 9 ++- docs/architecture/inference.md | 106 +++++++++++++++++++++++++- 3 files changed, 126 insertions(+), 5 deletions(-) create mode 100644 changelog.d/qwen27-tp-prefill.md diff --git a/changelog.d/qwen27-tp-prefill.md b/changelog.d/qwen27-tp-prefill.md new file mode 100644 index 0000000000..e8a307afd3 --- /dev/null +++ b/changelog.d/qwen27-tp-prefill.md @@ -0,0 +1,16 @@ +### Qwen tensor-parallel prompt wavefront + +- A Qwen tensor-parallel pair now prefills a text prompt 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 (about 367 MB a Qwen3.8-27B rank at one lane). +- `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/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index c91f96c2e6..60579caab7 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-10-31 +> 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 @@ -1151,7 +1151,12 @@ 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 +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; `QwenTensorParallelPromptWavefrontTests.mergedStepTemporariesStayWithinTheirCharge` +measures a merged step against it). 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. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a6bf854a24..b8a265c7a1 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-02 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -5094,8 +5094,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 @@ -5187,6 +5188,105 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Ten `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift` (`serveBatch`, `prepareBatch`). +### 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`). +- **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: 367,001,600 + bytes a 27B rank at 512-row frames. + `mergedStepTemporariesStayWithinTheirCharge` measures a merged step against + it. +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 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 +934-1,003 ms in steps of two or eight frames, against 1,514-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 From 681591d40a44e0d303bcacb3a8ae8a9ea3735a06 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:47:06 -0800 Subject: [PATCH 34/58] cluster: say what the wavefront's last submission does; step offsets in the prefill curve - `QwenTensorParallelPromptWavefront.forward`: the earlier frames' last rows are submitted as each frame's own output was; nothing reads them. The comment claimed they joined the run's evaluation. - `QwenTensorParallelPrefillBench`: `path=prefill-curve` names each step's first token, not the step index times the chunk (merged steps hold several frames). Co-Authored-By: Claude Opus 5.5 --- .../TensorParallel/QwenTensorParallelPrefillBench.swift | 6 ++++-- .../TensorParallel/QwenTensorParallelPromptWavefront.swift | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift index 17dd113593..966347b968 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift @@ -103,6 +103,8 @@ public enum QwenTensorParallelPrefillBench { var build: Double var evaluation: Double var other: Double + /// The step's first token. + var offset = 0 } public static func run(_ options: Options, log: @escaping (String) -> Void) throws { @@ -167,7 +169,7 @@ public enum QwenTensorParallelPrefillBench { let evaluation = phases.span("evaluation.begin", "evaluation.end") let wall = ms(ended - started) frames.append(.init(wall: wall, build: build, evaluation: evaluation, - other: wall - (build.isNaN ? 0 : build) - (evaluation.isNaN ? 0 : evaluation))) + other: wall - (build.isNaN ? 0 : build) - (evaluation.isNaN ? 0 : evaluation), offset: offset)) if observing { layerRows.append((index, offset, layerRecorder.layerTimes)) } if let logits { eval(logits) @@ -224,7 +226,7 @@ public enum QwenTensorParallelPrefillBench { + " collectives=\(reduction.collectives) collective_mb=\(format(Double(reduction.collectiveBytes) / 1e6))" + " digest=\(result.digest)") let curve = frames.enumerated().filter { $0.offset % max(1, frames.count / 8) == 0 || $0.offset == frames.count - 1 } - .map { "\($0.offset * chunk):\(format($0.element.wall))" }.joined(separator: ",") + .map { "\($0.element.offset):\(format($0.element.wall))" }.joined(separator: ",") log("\(label) path=prefill-curve chunk=\(chunk) ops=\(operations == 0 ? "process" : String(operations)) stride=\(stride) wavefront=\(wavefront) mode=\(mode.rawValue) offset_ms=\(curve)") } Memory.clearCache() diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift index 56cbf5e50d..97da76b0fc 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift @@ -103,7 +103,7 @@ enum QwenTensorParallelPromptWavefront { issued.sums.removeAll() } } - // Every earlier frame's last rows join the evaluation the run waits on. + // Earlier frames' last rows run too, as each frame's own output did; nothing reads them. asyncEval(Array(outputs.dropLast())) return final ? outputs[outputs.count - 1][0..., -1, 0...] : outputs[outputs.count - 1] } From 6e152ae06f56252c66745d931b9d3b337391fd0a Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:51:18 -0800 Subject: [PATCH 35/58] cluster: test the executor's planned merged prompt step `executorRunsThePlannedMergedStep`: on two in-process ranks, the native executor runs a 1,100-token prompt as one planned step of three frames and selects the token one frame a step selects; a lane takes a planned token count only where one of its own steps ends (`promptStep(tokens:)`: 1,100 and 1,024 accepted, 700 and 2,048 refused). The suite's GPU tests share one fixture helper. Co-Authored-By: Claude Opus 5.5 --- ...enTensorParallelPromptWavefrontTests.swift | 117 ++++++++++++++---- 1 file changed, 90 insertions(+), 27 deletions(-) diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift index c241683550..699ad6fbb5 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift @@ -206,6 +206,26 @@ struct QwenTensorParallelPromptWavefrontTests { var failure: Error? } + /// Hybrid shards of one synthetic checkpoint (six recurrent, two attention + /// layers) on two in-process ranks that sum by meeting each other. + private static func pair() throws -> (configuration: Data, ranks: [Rank], models: [QwenTensorParallelModel]) { + let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 2048, layers: 8, heads: 8, kvHeads: 2, + vocabulary: 256) + var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any] + var text = root["text_config"] as! [String: Any] + text["max_position_embeddings"] = 8192; root["text_config"] = text + let configuration = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) + let wire = Rendezvous() + let ranks = (0..<2).map { Rank($0, wire) } + let models = try (0..<2).map { rank in + try QwenTensorParallelModel.assemble(configurationData: configuration, + role: .shard(rank: rank, size: 2), reduction: ranks[rank]) { _, keep in + for (name, value) in fixture.tensors { try keep(name, value) } + } + } + return (configuration, ranks, models) + } + /// Both ranks' temporaries per prompt step of `limit` frames (the largest /// step's peak above the settled allocation before and after it). private static func promptTransient(_ models: [QwenTensorParallelModel], configuration: Data, prompt: Int, @@ -253,19 +273,7 @@ struct QwenTensorParallelPromptWavefrontTests { @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1")) func mergedStepTemporariesStayWithinTheirCharge() throws { try Device.withDefaultDevice(.gpu) { - let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 2048, layers: 8, heads: 8, kvHeads: 2, - vocabulary: 256) - var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any] - var text = root["text_config"] as! [String: Any] - text["max_position_embeddings"] = 8192; root["text_config"] = text - let configuration = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) - let wire = Rendezvous() - let models = try (0..<2).map { rank in - try QwenTensorParallelModel.assemble(configurationData: configuration, - role: .shard(rank: rank, size: 2), reduction: Rank(rank, wire)) { _, keep in - for (name, value) in fixture.tensors { try keep(name, value) } - } - } + let (configuration, _, models) = try Self.pair() let single = try Self.promptTransient(models, configuration: configuration, prompt: 4096, limit: 1) let merged = try Self.promptTransient(models, configuration: configuration, prompt: 4096, limit: QwenTensorParallelPromptWavefront.maximumFrames) @@ -290,20 +298,7 @@ struct QwenTensorParallelPromptWavefrontTests { @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1")) func mergedFramesKeepEveryBit() throws { try Device.withDefaultDevice(.gpu) { - let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 2048, layers: 8, heads: 8, kvHeads: 2, - vocabulary: 256) - var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any] - var text = root["text_config"] as! [String: Any] - text["max_position_embeddings"] = 8192; root["text_config"] = text - let configuration = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) - let wire = Rendezvous() - let ranks = (0..<2).map { Rank($0, wire) } - let models = try (0..<2).map { rank in - try QwenTensorParallelModel.assemble(configurationData: configuration, - role: .shard(rank: rank, size: 2), reduction: ranks[rank]) { _, keep in - for (name, value) in fixture.tensors { try keep(name, value) } - } - } + let (configuration, ranks, models) = try Self.pair() #expect(Qwen35PromptWavefront.supports(models[0].model)) let cases: [(name: String, kind: ClusterStageKVBackendKind, prompt: Int, limit: Int, capture: Int, beside: Bool, restore: Int)] = [ @@ -338,4 +333,72 @@ struct QwenTensorParallelPromptWavefrontTests { } } } + + struct Reservation: QwenTensorParallelBatchReservation { + let request: QwenLayerStageGenerationRequest + let deadline: UInt64 = .max + var laneStateBytes: Int { 1 } + var joinable: Bool { true } + } + + /// The native executor runs the leader's planned step: a 1,100-token + /// prompt in one merged step selects the token one frame a step selects, + /// on both ranks, and a lane takes a planned token count only where it + /// ends one of its own steps (`promptStep(tokens:)`). + @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1")) + func executorRunsThePlannedMergedStep() throws { + try Device.withDefaultDevice(.gpu) { + let (configuration, ranks, models) = try Self.pair() + let shape = try Self.request(prompt: 1_100) + let request = try QwenLayerStageGenerationRequest(profile: shape.profile, requestID: UUID(), + promptTokenIDs: shape.promptTokenIDs, chunkSize: 512, outputCount: 16, stopTokenIDs: []) + func selected(limit: Int) throws -> [(token: Int, steps: Int)] { + let results = (0..<2).map { _ in ExecutorResult() } + let lanes = try (0..<2).map { rank -> QwenTensorParallelNativeBatchLane in + let host = try CBv2StageKVHost(model: models[rank].model, kind: .paged, lanes: 1, + maximumTokensPerRequest: 1_116, maximumChunkTokens: 512) + let executor = try QwenTensorParallelNativeBatchExecutor(model: models[rank], + configuration: configuration, host: host, group: ranks[rank], prepare: { _, _ in nil }, + completedDecode: { _ in }, completedPrefill: {}, releaseResources: { _ in }) + let lane = try executor.open(.init(request: request), check: {}) + if rank == 0 { + #expect(lane.promptStep(tokens: 1_100) == QwenTensorParallelPromptWavefront.step( + lane.session.promptFrames(limit: 3))) + #expect(lane.promptStep(tokens: 1_024)?.finalPromptChunk == false) + #expect(lane.promptStep(tokens: 700) == nil && lane.promptStep(tokens: 2_048) == nil) + } + results[rank].executor = executor + return lane + } + defer { for lane in lanes { try? lane.session.retire() } } + let threads = TensorParallelRankThreads() + threads.run { rank in + Device.withDefaultDevice(.gpu) { + do { + let lane = lanes[rank], executor = try #require(results[rank].executor) + var steps = 0, token: Int? + while lane.nextFrame?.phase == .prefill { + let step = try #require(lane.promptStep(frames: limit)) + token = try executor.prefill(lane, frame: step, check: {}); steps += 1 + } + results[rank].selection = (try #require(token), steps) + } catch { results[rank].failure = error } + } + } + for result in results { if let failure = result.failure { throw failure } } + return try results.map { try #require($0.selection) } + } + let one = try selected(limit: 1) + let merged = try selected(limit: QwenTensorParallelPromptWavefront.maximumFrames) + #expect(one.map(\.steps) == [3, 3] && merged.map(\.steps) == [1, 1]) + #expect(one.map(\.token) == merged.map(\.token) && one[0].token == one[1].token) + } + } + + /// One rank thread's executor and selection. + final class ExecutorResult: @unchecked Sendable { + var executor: QwenTensorParallelNativeBatchExecutor? + var selection: (token: Int, steps: Int)? + var failure: Error? + } } From 1751746aa89b29785a40bdf7e2ddb61c98052c95 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:52:43 -0800 Subject: [PATCH 36/58] Keep a sized tensor plan's mode reasons, and its plans off decide's frame Refactor pass on the saved Qwen TP width. A row whose pipeline stays a candidate (the 9B, the 35B A3B rows) was re-planned on its tensor-parallel placement alone, so its plan said "Tensor parallel: pipeline is left out (its tensor-parallel placement, chosen for one request, is sized for 8 at once)" instead of its comparison with the pipeline, on the plan screen and in the explanation. The sized plan now keeps the singleton plan's mode decision (modes and kept-mode reasons, the tensor-parallel assessment, the shard table); only its chosen placement is priced at the width. The 27B's reason line is as before; its shard table and tensor-parallel section now come from the singleton plan (the same placement and predictions). A new test plans the 9B identity: red on the previous commit (the "left out" line), green now. Stack: binding the sized plan in ClusterPlacementFlow.decide was moved into an inout callee, but `var result` still cost decide's debug frame 20,288 B (94,224 B on the base, 114,512 B with it: every later read of the var copies the whole result). decide now initializes a constant result from one call, ClusterPlacementTensorWidth.plan, which runs the planner directly without width quotes and otherwise hands off to `widest`, where the sizing's plans live. Debug frames: decide 92,912 B, plan 8,144 B, widest 24,448 B. Against the previous commit the sizing path is 28,992 B shallower and the unsized path (the drained replacement included) 13,456 B; against the base, the unsized path is 6,832 B deeper. Sizing is still gated by the singleton quote (`tensorParallelBatchQuote` of one lane), so a batch scope or no quote plans as before. Docs: one home for the sizing rule (the reference rows link to it). Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 6 ++- docs/reference/configuration.md | 7 +-- .../Placement/ClusterPlacementFlow.swift | 10 ++--- .../ClusterPlacementTensorWidth.swift | 44 ++++++++++++------- .../ClusterPlacementTensorWidthTests.swift | 40 +++++++++++++---- 5 files changed, 71 insertions(+), 36 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 8c6d490eed..325e765b83 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5211,8 +5211,10 @@ coordinator pairing never widened. 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. When no width fits, the setup - saves none and serves one request at a time, as before. + 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. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index f079a77953..e561032c4e 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -788,7 +788,7 @@ 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. The guided setup saves it on both Macs for a Qwen TP placement: the widest of 8, 6, 4 and 2 both Macs admit now under that width's complete LOAD quote, omitted when none does. A setup saved for coordinator pairing keeps it unchanged beside its approval. | `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`validate`), `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift` (`widest`) | +| `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 @@ -1620,8 +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. The guided setup asks for the quote at each of these widths and saves -the widest both Macs admit now. 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/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift index 086fd21480..1bad1a07b2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift @@ -276,13 +276,11 @@ public enum ClusterPlacementFlow { policy.modesReason = policy.modesReason ?? "a capacity change keeps the running tensor-parallel shares" policy.requiredTensorShares = incumbentTensorShares } - var result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link) - // A singleton tensor placement saves the widest width its owner's quotes admit on both Macs now. + // A singleton tensor placement saves the widest width its owner's quotes admit on both Macs now. One call + // initializes a constant `result`, so the sizing's plans stay off this frame, which a deep planner stack shares. var batchLanes = batchScope?.lanes - if batchScope == nil, tensorAssistantQuote != nil, !tensorWidthQuotes.isEmpty { - try ClusterPlacementTensorWidth.size(&result, lanes: &batchLanes, quotes: tensorWidthQuotes, - devices: devices, layout: layout, policy: policy, link: link) - } + let result = try ClusterPlacementTensorWidth.plan(devices: devices, layout: layout, policy: policy, link: link, + quotes: tensorWidthQuotes, lanes: &batchLanes) var lines = (forced.map(ClusterForcedModeSetting.lines) ?? []) + (benchCap.map(ClusterPlannerBenchCap.lines(capBytes:)) ?? []) + (benchChip.map(ClusterBenchChip.lines(chipName:)) ?? []) + servedLines diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift index ea5fae768a..c948f41354 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift @@ -8,35 +8,45 @@ import DarkbloomClusterProtocol /// a replacement is held to (`ClusterPlacementCandidate.admitted`). When none fits, the setup saves no width and keeps /// the family default. enum ClusterPlacementTensorWidth { - /// `result` becomes the widest admitted width's plan and `lanes` that width; both stay as they are when none - /// fits. Never inlined, so the plans it makes stay off the caller's frame, which a deep planner stack shares. + /// The plan `ClusterPlacementFlow.decide` keeps: `ClusterPlacementPlanner.plan`'s or, given width quotes, + /// `widest`'s. Never inlined, and only `widest`'s frame holds the sizing's plans: the caller's frame, which a deep + /// planner stack shares, holds just the one plan it keeps. @inline(never) - static func size(_ result: inout ClusterPlacementResult, lanes: inout Int?, quotes: [ClusterPlacementTensorBatchQuote], - devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy, - link: ClusterLinkCosts) throws { - guard let sized = try widest(result, quotes: quotes, devices: devices, layout: layout, policy: policy, link: link) else { return } - result = sized.result; lanes = sized.lanes + static func plan(devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy, + link: ClusterLinkCosts, quotes: [ClusterPlacementTensorBatchQuote], lanes: inout Int?) throws + -> ClusterPlacementResult { + guard !quotes.isEmpty else { + return try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link) + } + return try widest(devices: devices, layout: layout, policy: policy, link: link, quotes: quotes, lanes: &lanes) } - static func widest(_ singleton: ClusterPlacementResult, quotes: [ClusterPlacementTensorBatchQuote], - devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy, - link: ClusterLinkCosts) throws -> (lanes: Int, result: ClusterPlacementResult)? { + /// The singleton plan or, when the widest admitted width exists, that width's plan, with `lanes` set to it. Only a + /// placement priced by its owner's singleton quote is sized: a batch scope's quote, or none, leaves the plan as it + /// is. The mode was chosen for one request, so a sized plan keeps that choice's reasons and comparisons + /// (`deploymentReason`); only its chosen placement is priced at the width. + @inline(never) + static func widest(devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy, + link: ClusterLinkCosts, quotes: [ClusterPlacementTensorBatchQuote], lanes: inout Int?) throws + -> ClusterPlacementResult { + let singleton = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link) // A split the setup can save: equal, or integer weights. guard let chosen = singleton.chosen, chosen.mode == .tensorParallel, chosen.shares == nil || chosen.tensorShares != nil, - policy.tensorParallelBatchQuote?.lanes == 1, let leader = chosen.ranks.first?.device else { return nil } + policy.tensorParallelBatchQuote?.lanes == 1, let leader = chosen.ranks.first?.device else { return singleton } for quote in quotes.sorted(by: { $0.lanes > $1.lanes }) { var widened = policy try quote.applyWidth(to: &widened, layout: layout) widened.modes = [.tensorParallel]; widened.schedules = [chosen.prefillSchedule] - widened.modesReason = widened.modesReason - ?? "its tensor-parallel placement, chosen for one request, is sized for \(quote.lanes) at once" widened.leader = leader; widened.requiredTensorShares = chosen.tensorShares ?? [1, 1] - let result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: widened, link: link) - guard let wide = result.chosen, wide.mode == .tensorParallel, wide.ranks.map(\.device) == chosen.ranks.map(\.device), + var sized = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: widened, link: link) + guard let wide = sized.chosen, wide.mode == .tensorParallel, wide.ranks.map(\.device) == chosen.ranks.map(\.device), wide.tensorShares == chosen.tensorShares, wide.admitted(requireNow: true) else { continue } - return (quote.lanes, result) + sized.modesReason = singleton.modesReason; sized.keptModeReason = singleton.keptModeReason + sized.tensorParallel = singleton.tensorParallel; sized.shards = singleton.shards + lanes = quote.lanes + return sized } - return nil + return singleton } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift index a7dff7fade..ac5ee2dfdc 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift @@ -44,9 +44,17 @@ final class ClusterPlacementTensorWidthTests { return p } - /// The registered 27B's identity on a constructed two-layer layout whose tensor parallel splits 1:1, 1:2 or 2:1. - private func fixture() throws -> (ClusterPairDescription, ClusterRuntimeCapability, ClusterModelLayout, ClusterPlacementRequestScope) { - let model = "registered_qwen38_27b" + /// A registered Qwen TP row's identity: the 27B, whose features keep its plans to tensor parallel + /// (`ClusterModelFeaturePolicy`), or the 9B, whose plans keep the pipeline a candidate, as the 35B A3B rows' do. + private typealias Row = (model: String, profile: String) + private static let twentySevenB: Row = ("registered_qwen38_27b", "registered_qwen38_27b_greedy_generation_v1") + private static let nineB: Row = ("registered_qwen35_9b", "registered_qwen35_9b_greedy_generation_v1") + + /// A registered row's identity (the 27B's by default) on a constructed two-layer layout whose tensor parallel + /// splits 1:1, 1:2 or 2:1. + private func fixture(_ row: Row = twentySevenB) + throws -> (ClusterPairDescription, ClusterRuntimeCapability, ClusterModelLayout, ClusterPlacementRequestScope) { + let model = row.model let part = ClusterModelLayout.Part(storedBytes: 2 * gib, loadedBytes: 2 * gib, largestTensorBytes: gib / 4, tensorCount: 16) let end = ClusterModelLayout.Part(storedBytes: gib / 2, loadedBytes: gib / 2, largestTensorBytes: gib / 2, tensorCount: 1) let raw = ClusterModelLayout(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), @@ -64,7 +72,7 @@ final class ClusterPlacementTensorWidthTests { let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object)) let cap = try ClusterRuntimeCapability(runtimeBinarySHA256: hash("a"), adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), manifestSHA256: hash("d"), - profile: .init(id: "registered_qwen38_27b_greedy_generation_v1", vocabularySize: 248320, + profile: .init(id: row.profile, vocabularySize: 248320, maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumChunkTokens: 512, maximumContextTokens: 65536), profileFingerprint: hash("e"), partitions: [.init(planSHA256: hash("f"), stages: [ .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 1, stagePlanSHA256: hash("1"), constructionConfigurationSHA256: hash("2")), @@ -100,8 +108,9 @@ final class ClusterPlacementTensorWidthTests { } private func decide(_ home: URL, free: Int, peerFree: Int? = nil, widths: [Int] = ClusterPlacementBatchScope.tensorParallelWidths, - assistant: ClusterPlacementTensorAssistantQuote? = nil) throws -> ClusterSetupPlanning.PlacementDecision { - let (pair, cap, layout, request) = try fixture() + assistant: ClusterPlacementTensorAssistantQuote? = nil, + row: Row = twentySevenB) throws -> ClusterSetupPlanning.PlacementDecision { + let (pair, cap, layout, request) = try fixture(row) return try ClusterPlacementFlow.decide(description: pair, capability: cap, localMemberID: "a", localProfile: profile(free: free), peerProfile: profile(free: peerFree ?? free), layout: layout, tensorAssistantQuote: try quote(request, lanes: 1, assistant: assistant), @@ -111,8 +120,8 @@ final class ClusterPlacementTensorWidthTests { } /// Both Macs' saved widths: equal, or the test fails. - private func savedLanes(_ decision: ClusterSetupPlanning.PlacementDecision) throws -> Int? { - let (pair, cap, _, _) = try fixture() + private func savedLanes(_ decision: ClusterSetupPlanning.PlacementDecision, row: Row = twentySevenB) throws -> Int? { + let (pair, cap, _, _) = try fixture(row) let setup = try #require(decision.setup) let lanes = try ["a", "b"].map { member in try ClusterConfigurationCodec.decode(try #require(setup.configurations[member]), capability: cap, @@ -174,6 +183,21 @@ final class ClusterPlacementTensorWidthTests { #expect(throws: (any Error).self) { try self.quote(request, lanes: 1, assistant: assistant).applyWidth(to: &policy, layout: layout) } } + /// A row whose pipeline stays a candidate is sized the same way, and its plan keeps the reason its mode was chosen + /// for one request (its comparison with the pipeline); only the chosen placement's memory is the width's. + @Test func aRowWhosePipelineStaysACandidateKeepsItsModeReason() throws { + let home = try home(), row = Self.nineB + let alone = try decide(home, free: 200 * gib, widths: [], row: row) + let sized = try decide(home, free: 200 * gib, row: row) + #expect(alone.result.chosen?.mode == .tensorParallel && alone.result.modesReason == nil) + #expect(try savedLanes(sized, row: row) == 8) + let reason = try #require(ClusterPlacementExplanation.deploymentReason(sized.result)) + #expect(reason == ClusterPlacementExplanation.deploymentReason(alone.result) && !reason.contains("left out"), "\(reason)") + #expect(sized.lines.contains(" " + reason)) + let need = { (decision: ClusterSetupPlanning.PlacementDecision) in decision.result.chosen?.ranks.map(\.needBytes).max() ?? 0 } + #expect(need(sized) > need(alone)) + } + /// GLM tensor parallel keeps its own default; a pipeline, and a Qwen TP setup saved without a width, keep theirs. @Test func otherFamiliesAndUnsizedSetupsKeepTheirLanes() throws { typealias Plan = DistributedInstalledPlan From 83b73188c337e50d85bd979ec7d03707b292792d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:52:43 -0800 Subject: [PATCH 37/58] Say in the changelog how many requests a Qwen TP pair serves at once Users see that `darkbloom cluster` sets a Qwen tensor-parallel pair to serve up to 8 requests at once, sized to both Macs' memory, from its first load. Same facts as before (widths per Mac size, memory safety, the local fallback, existing setups, approvals), in user terms. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-default-lanes.md | 37 +++++++++++++------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/changelog.d/qwen27-tp-default-lanes.md b/changelog.d/qwen27-tp-default-lanes.md index 5195f462ab..14f85a899c 100644 --- a/changelog.d/qwen27-tp-default-lanes.md +++ b/changelog.d/qwen27-tp-default-lanes.md @@ -1,19 +1,20 @@ -### Qwen tensor-parallel pairs serve concurrent requests from their first load +### Qwen tensor-parallel pairs serve up to 8 requests at once, sized to memory -- The guided cluster setup now saves a width for a Qwen tensor-parallel pair: - the widest of 8, 6, 4 and 2 concurrent requests that both Macs admit now under - that width's complete load quote. The pair serves that many requests at once - from its first load. Before, it served one: a local pair widened only after a - burst, through a drained reload that the burst waited for, and a pair served - through Darkbloom never widened. -- On two idle Macs, Qwen3.8-27B without the speculative assistant saves 8 from - 48 GB a Mac (4 at 32 or 36 GB). With the assistant, which serves local - clusters only, it saves 8 from 96 GB a Mac and less on smaller Macs. When no - width fits, the setup serves one request at a time as before. -- Memory safety is unchanged: both Macs still reserve the saved width's whole - quote at load and admit each request alone. A local pair planned narrower - still widens under queued demand; a pair saved at 8 is never reloaded for it. -- A pair served through Darkbloom keeps its saved width beside its approval. No - approval, registration or committed-start digest changes. Existing setups keep - their saved bytes and their one-request width until they are planned again, - as after an update. +- `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 48 GB a Mac without the + speculative assistant (4 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. From 3e5c352bd2a1f95b439f63d862f72c32c25fe2b9 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:31:11 -0800 Subject: [PATCH 38/58] cluster: keep at most four wavefront sums unfinished; peak memory in the wavefront check Over the loopback ring a merged prompt step's peak rose 0.5-1.5 GB a rank above one frame's (4-layer shards at the 27B's per-rank widths), against the 367 MB `QwenTensorParallelPromptWavefront.inFlightBytes` charges: MLX encodes, and allocates, the independent frames' phases up to `MLX_MAX_ACTIVE_TASKS` tasks ahead of the link. The in-process test cannot see it, because its sums complete as they are built. - `forward` waits for the oldest submitted sum while more than `sumsInFlight` (4) are unfinished. Evaluation order only: the same sums in the same order on both ranks. Measured with the bound: at most 314 MB above one frame's peak (sealed ring: below it, also at a 65,536-token context), the same digests, and steps as fast as without it on the unsealed ring. - `tp-check qwen-wavefront` logs each run's `peak_mb` and takes `--output-tokens` (the request's context past the prompt). - The SDK's phase callback takes no arguments (mlx-swift-lm ad856be1 on `perf/qwen27-tp-prompt-wavefront`). - Comments: the driver runs one prompt step a driver step, not one frame. Co-Authored-By: Claude Opus 5.5 --- .../QwenWavefrontCheck.swift | 14 ++++++++------ .../QwenTensorParallelBatchBudget.swift | 4 ++-- .../QwenTensorParallelBatchDriver.swift | 2 +- .../QwenTensorParallelPrefillBench.swift | 18 ++++++++++++------ .../QwenTensorParallelPromptWavefront.swift | 18 +++++++++++++----- libs/mlx-swift-lm | 2 +- 6 files changed, 37 insertions(+), 21 deletions(-) diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift index b241f273ca..e5c5eecab0 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift @@ -6,9 +6,10 @@ import MLX // 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] \ -// [--wavefronts 1,2,8] [--repeats 1] -// Each rank logs every run's step times and digests; both agree that every -// run left the same bytes. Loopback timings show the overlap, never a pair's. +// [--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] = [:] @@ -31,13 +32,14 @@ enum QwenWavefrontCheck { 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 and --repeats take positive integers, --wavefronts 1 to 8") + 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)|\(wavefronts)|\(repeats)" + 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") } @@ -52,7 +54,7 @@ enum QwenWavefrontCheck { 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, wavefronts: wavefronts, repeats: repeats) { line in + promptTokens: prompt, chunk: chunk, outputTokens: output, wavefronts: wavefronts, repeats: repeats) { line in FileHandle.standardOutput.write(Data((line + "\n").utf8)) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift index 1d9bb3080e..423cf8aee7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift @@ -15,7 +15,7 @@ struct QwenTensorParallelBatchBudget { let sharedBytesExcludingCollectives: Int let batchProjectionConstantBytes: Int let pagedPoolSlackBytes: Int - /// Paged: one full-history gather bank, shared (one prompt frame per step). + /// Paged: one full-history gather bank, shared (one prompt step at a time). let promptGatherBytes: Int let prefix: QwenTensorParallelBatchPrefixBudget let allowance: ClusterTensorParallelRequestAllowance @@ -43,7 +43,7 @@ struct QwenTensorParallelBatchBudget { // The full-history gather bank is a prompt frame's transient: decode // and verify windows attend the pages in place (the fused paged // decode kernel, one query column at a time), and the batch driver - // runs at most one prompt frame per step, so one bank serves every + // runs one lane's prompt step at a time, so one bank serves every // lane (`QwenTensorParallelBatchSessionTests.fullHistoryGatherIsOne // PromptFramesTransient` measures both). The scalar floor's F32 KV // term (two BF16 banks) is replaced by the lane's own BF16 page diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift index 4066af3dcd..4c238577f7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift @@ -48,7 +48,7 @@ extension QwenTensorParallelBatchExecutor { func confirmedRetirement(_ lane: Lane, clean: Bool) throws {} } -/// One prefill frame on its original grid and one real decode rectangle per +/// One prompt step (consecutive frames on the original grid) and one real decode rectangle per /// step. Every active request owns its native history. A slow client holds /// only its own token credit. Successful retirement is published only after /// both ranks have drained, including cancellation and deadline departures. diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift index 966347b968..cc1bd8bafb 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift @@ -354,14 +354,16 @@ public enum QwenTensorParallelPrefillBench { /// A real pair's rank (`model`'s reduction is its group, for example the /// loopback ring with sealed sums): the same prompt prefilled one frame a /// step and in merged steps of up to each of `wavefronts` frames - /// (`QwenTensorParallelPromptWavefront`). Logs each run's step times and - /// the digests of its final logits, attention rows and recurrent states; - /// returns whether every run left this rank the same digests. + /// (`QwenTensorParallelPromptWavefront`). Logs each run's step times, its + /// peak allocation above the memory in use before the prompt (`peak_mb`) + /// and the digests of its final logits, attention rows and recurrent + /// states; returns whether every run left this rank the same digests. public static func pair(model: QwenTensorParallelModel, configuration: Data, promptTokens: Int, chunk: Int, - wavefronts: [Int], repeats: Int, log: (String) -> Void) throws -> Bool { + outputTokens: Int = 8, wavefronts: [Int], repeats: Int, + log: (String) -> Void) throws -> Bool { guard case .shard(let rank, _) = model.role else { throw ProbeError("The wavefront pair runs a rank shard") } let tokens = prompt(promptTokens, vocabulary: model.plan.vocabularySize) - let budget = promptTokens + 8 + let budget = promptTokens + outputTokens let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-wavefront-pair", vocabularySize: model.plan.vocabularySize, hiddenSize: model.plan.hiddenSize, activationDType: "bfloat16", maximumPromptTokens: promptTokens, maximumChunkTokens: chunk, maximumOutputTokens: budget - promptTokens, @@ -386,6 +388,9 @@ public enum QwenTensorParallelPrefillBench { defer { try? session.retire() } var steps: [(tokens: Int, ms: Double)] = [] var logits: MLXArray? + Stream.gpu.synchronize() + let before = Memory.activeMemory + Memory.peakMemory = 0 while session.schedule.committedPromptTokens < promptTokens { let frames = session.promptFrames(limit: limit) guard let step = QwenTensorParallelPromptWavefront.step(frames) else { throw ProbeError("No prompt step") } @@ -394,6 +399,7 @@ public enum QwenTensorParallelPrefillBench { if let logits { eval(logits) } steps.append((step.tokenCount, ms(DispatchTime.now().uptimeNanoseconds - started))) } + let peak = max(0, Memory.peakMemory - before) let total = steps.reduce(0) { $0 + $1.ms } let rows = session.state.rows.compactMap { $0?.snapshot() }.flatMap { [$0.keys, $0.values] } let committed = session.state.recurrent.confirmedStateSnapshot() ?? [:] @@ -404,7 +410,7 @@ public enum QwenTensorParallelPrefillBench { log("qwen-tp-wavefront-v1 rank=\(rank) limit=\(limit) repeat=\(repeatIndex) tokens=\(promptTokens)" + " steps=\(steps.count) total_ms=\(format(total)) tok_s=\(format(Double(promptTokens) / total * 1000))" + " per_\(chunk)_median_ms=\(format(median(perFrame))) first_step_ms=\(format(steps.first?.ms ?? .nan))" - + " logits=\(value.0) rows=\(value.1) recurrent=\(value.2)") + + " peak_mb=\(format(Double(peak) / 1e6)) logits=\(value.0) rows=\(value.1) recurrent=\(value.2)") } } log("qwen-tp-wavefront-v1 rank=\(rank) digest-check \(same ? "same-bytes" : "DIFFERENT")") diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift index 97da76b0fc..0563a5a2da 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift @@ -24,6 +24,11 @@ enum QwenTensorParallelPromptWavefront { /// Frames one prompt step runs while another lane decodes, so a decoding /// lane waits for one merged step about as long as for one frame alone. static let framesBesideDecoding = 2 + /// Unfinished sums a step keeps submitted: building waits for the oldest + /// beyond them. Unbounded, MLX encodes (and allocates) up to + /// `MLX_MAX_ACTIVE_TASKS` tasks of independent frames ahead, beyond + /// `inFlightBytes`. Evaluation order only: the sums and their order are unchanged. + static let sumsInFlight = 4 /// Diagnostic only: `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` runs one frame a /// step, as before. Bound into the load agreement (`agreementFields`). static let enabled = ProcessInfo.processInfo.environment["DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT"] != "0" @@ -82,10 +87,10 @@ enum QwenTensorParallelPromptWavefront { } /// `frames`' forward inside one `CBv2OwnedRequestState.run`: the - /// wavefront, each phase's sums submitted as soon as it is built; returns - /// what the last frame's own forward returns (its evaluation handle, or - /// the final prompt row's logits from the whole frame's head, as - /// `QwenTensorParallelBatchSession.prompt` keeps them). + /// wavefront, each phase's sums submitted as soon as it is built (at most + /// `sumsInFlight` unfinished); returns what the last frame's own forward + /// returns (its evaluation handle, or the final prompt row's logits from + /// the whole frame's head, as `QwenTensorParallelBatchSession.prompt` keeps them). static func forward(model: QwenTensorParallelModel, request: QwenLayerStageGenerationRequest, frames: [QwenLayerStageFrame], caches: [any CBv2AttendingLayerCache], evaluation: CBv2RecurrentStateEvaluation) -> MLXArray { @@ -95,12 +100,15 @@ enum QwenTensorParallelPromptWavefront { } let final = frames.last?.finalPromptChunk ?? false let issued = QwenTensorParallelIssuedSums() + var submitted: [MLXArray] = [] let outputs = QwenTensorParallelRowLinear.$issuedSums.withValue(issued) { Qwen35PromptWavefront.prefill(model.model, chunks: chunks, finalChunk: final, - caches: caches.map { $0 as! any KVCache }, recurrentState: evaluation) { _, _, _ in + caches: caches.map { $0 as! any KVCache }, recurrentState: evaluation) { guard !issued.sums.isEmpty else { return } asyncEval(issued.sums) + submitted += issued.sums issued.sums.removeAll() + while submitted.count > sumsInFlight { eval(submitted.removeFirst()) } } } // Earlier frames' last rows run too, as each frame's own output did; nothing reads them. diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index df6fc5f122..ad856be115 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit df6fc5f122a9a9df556c1ae3a5291634ef4b3514 +Subproject commit ad856be1151d20c28a354eda81ce71ba68044d79 From 775ed581ffc1817b5f2f351b8673433d2e54ea8d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:31:12 -0800 Subject: [PATCH 39/58] docs: Qwen TP prompt wavefront's bounded sums and measured peaks - hardware-support.md: the driver runs one lane's prompt step at a time (it said one prompt frame per step); a merged step keeps at most `sumsInFlight` sums unfinished, with the loopback ring's measured peaks, and the in-process test's limit. This is the term's one home: inference.md links it instead of restating 367,001,600 bytes. - inference.md: the bound in the graph description, `peak_mb`, and the loopback timings remeasured with the bound. - Changelog: the charge is the same at any width (it said one lane), and the entry says the prefill is faster. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-prefill.md | 9 +++++---- docs/architecture/hardware-support.md | 13 +++++++++---- docs/architecture/inference.md | 25 ++++++++++++++----------- 3 files changed, 28 insertions(+), 19 deletions(-) diff --git a/changelog.d/qwen27-tp-prefill.md b/changelog.d/qwen27-tp-prefill.md index e8a307afd3..2f113dafb5 100644 --- a/changelog.d/qwen27-tp-prefill.md +++ b/changelog.d/qwen27-tp-prefill.md @@ -1,14 +1,15 @@ ### Qwen tensor-parallel prompt wavefront -- A Qwen tensor-parallel pair now prefills a text prompt 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 +- 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 (about 367 MB a Qwen3.8-27B rank at one lane). + 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. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 60579caab7..0dd6b1860d 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1149,14 +1149,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` +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; `QwenTensorParallelPromptWavefrontTests.mergedStepTemporariesStayWithinTheirCharge` -measures a merged step against it). Segment slack and allocator overhead stay charged. Collective scratch prices complete +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. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index b8a265c7a1..48db55a8cf 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5229,7 +5229,10 @@ flowchart LR 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`). + 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. @@ -5253,10 +5256,9 @@ Invariants: 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: 367,001,600 - bytes a 27B rank at 512-row frames. - `mergedStepTemporariesStayWithinTheirCharge` measures a merged step against - it. + 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. @@ -5268,12 +5270,13 @@ 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 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 -934-1,003 ms in steps of two or eight frames, against 1,514-1,522 ms one frame -a step, every run with the same bytes on both ranks. +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`), From e475680b3aba4baacf9ca1d428a776e58ea2227b Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:01:36 -0800 Subject: [PATCH 40/58] cluster: carry the next Qwen TP step's control in plain decode selection sums A plain decode step (every row selects without an assistant, no prompt step after it) now carries the next step's plan and report in its own sealed selection sum: after the greedy cohort's six words a row, or after the sampled cohort's choices. Such a step pays one sealed sum and one host read instead of an exchange plus a selection. Prompt, idle and assisted steps keep the exchange. The plan is made once the forward committed and before the step's tokens are read, so host events apply one step later: - a row decodes on its newest token (QwenTensorParallelBatchWire.carriedToken) once the owner answered the token before it; both ranks drop that decode when the token in the sum ended the request (EOS or length); - rank 0 publishes a token only after the owner's answer to the one before it (a token selected first is held with its logprobs); - a stop answer that arrives after one more token was selected keeps the tokens the owner saw: that token is never published, both ranks drop it, and the native finish counts one discarded forward. The wire version (qwen-tp-independent-history-batch-v2-folded-control) is bound into the load agreement, and the collective payload quote covers the longer frame. Tokens, logits and native state are unchanged: the control limbs are exact in FP32 and each element of the sum is added alone. Tests: control words in every steady step's selection sum; EOS and length derived identically on both ranks (alone and beside other rows); a host stop applied one step late with its extra token never published; joins, a prompt and a cancellation interleaved with folded steps; the native executor's tokens and logprobs unchanged with control words at widths 1-8, greedy and sampled. 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. Co-Authored-By: Claude Opus 5.5 --- .../TensorParallelCheck/QwenDecodeCheck.swift | 69 ++++++ .../TensorParallelCheck.swift | 6 + .../QwenTensorParallelBatchBudget.swift | 5 +- .../QwenTensorParallelBatchDriver.swift | 216 ++++++++++++++---- .../QwenTensorParallelBatchWire.swift | 10 +- .../QwenTensorParallelDecodeBench.swift | 110 +++++++++ ...wenTensorParallelNativeBatchExecutor.swift | 58 +++-- ...pendentHistoryBatchDriverTestSupport.swift | 11 +- .../QwenTensorParallelBatchBudgetTests.swift | 3 +- .../QwenTensorParallelBatchDriverTests.swift | 152 +++++++++++- .../QwenTensorParallelBatchSessionTests.swift | 44 +++- 11 files changed, 611 insertions(+), 73 deletions(-) create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift 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/TensorParallelCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift index 2c58b0da31..967355f838 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift @@ -27,6 +27,8 @@ import MLX // 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 @@ -534,6 +536,10 @@ enum CompareCommand { 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/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift index 423cf8aee7..27aa7805f6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift @@ -94,11 +94,12 @@ struct QwenTensorParallelBatchBudget { scalar.projectionConstantBytes, batchConstants, poolSlack, prefix.residentBytes, packing, promptGather, wavefront]) // A one-token batch can gather more bytes than a short prompt frame. - // Control limbs and retirement votes also travel in the sealed codec. + // Control limbs and retirement votes also travel in the sealed codec, + // the next step's limbs after a greedy selection's six words a row. let payload = max(scalar.allowance.maximumCollectivePayloadBytes, try product([lanes, plan.maximumPartialBytesPerToken]), try product([lanes, plan.vocabularySize, 4]), - try product([QwenTensorParallelBatchWire.words, 4])) + try product([QwenTensorParallelBatchWire.words + 6 * lanes, 4])) let frame = try sum([payload, QwenTensorParallelSealCodec.frameOverhead]) let allowance = try ClusterTensorParallelRequestAllowance(maximumContextTokens: maximumTokens, maximumChunkTokens: chunkSize, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift index 4c238577f7..442bd20ee5 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift @@ -14,6 +14,9 @@ protocol QwenTensorParallelBatchLane: AnyObject { var reusedPrefixTokens: Int { get } var storedPrefixFrontiers: [Int] { get } var canSelectNext: Bool { get } + /// The lane's decode selects through the plain selection sum (no + /// assistant round or accepted queue), which can carry control words. + var plainSelection: Bool { get } func promptStep(frames: Int) -> QwenLayerStageFrame? func promptStep(tokens: Int) -> QwenLayerStageFrame? } @@ -22,6 +25,7 @@ extension QwenTensorParallelBatchLane { var reusedPrefixTokens: Int { 0 } var storedPrefixFrontiers: [Int] { [] } var canSelectNext: Bool { nextFrame?.phase == .decode } + var plainSelection: Bool { true } /// The prompt step of up to `frames` consecutive frames (`QwenTensorParallelPromptWavefront`). func promptStep(frames: Int) -> QwenLayerStageFrame? { nextFrame } /// The planned prompt step of `tokens`, if it is one this lane may run. @@ -38,7 +42,11 @@ protocol QwenTensorParallelBatchExecutor: AnyObject { func discard(_ reservation: Reservation) throws func open(_ reservation: Reservation, check: () throws -> Void) throws -> Lane func prefill(_ lane: Lane, frame: QwenLayerStageFrame, check: () throws -> Void) throws -> Int? - func decode(_ lanes: [Lane], tokens: [Int], check: () throws -> Void) throws -> [Int] + /// One decode rectangle. `control` runs once the forward committed and + /// before selection; words it returns (plain lanes only) ride the + /// selection's sealed sum, and both ranks' summed words come back. + func decode(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?, + check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) func retire(_ lane: Lane, reason: QwenLayerStageGenerationFinishReason?, selected: Int, last: Int?) throws func takeLogprobs(_ lane: Lane) throws -> ClusterWorkerTokenLogprobs? func confirmedRetirement(_ lane: Lane, clean: Bool) throws @@ -46,12 +54,23 @@ protocol QwenTensorParallelBatchExecutor: AnyObject { extension QwenTensorParallelBatchExecutor { func confirmedRetirement(_ lane: Lane, clean: Bool) throws {} + func decode(_ lanes: [Lane], tokens: [Int], check: () throws -> Void) throws -> [Int] { + try decode(lanes, tokens: tokens, control: { nil }, check: check).tokens + } } /// One prompt step (consecutive frames on the original grid) and one real decode rectangle per /// step. Every active request owns its native history. A slow client holds /// only its own token credit. Successful retirement is published only after /// both ranks have drained, including cancellation and deadline departures. +/// +/// A step whose decode rectangle is plain and runs no prompt folds the next +/// step's plan and report into its selection sum: one sealed sum and one host +/// read a step. That plan is made before the step's tokens are known, so +/// host events (answers, credits, cancellations, joins) apply one step later, +/// and both ranks drop a carried decode whose token ended its request (EOS or +/// length). Rank 0 publishes a token only once the owner answered the one +/// before it; a token selected before a stop answer is never published. final class QwenTensorParallelBatchDriver { typealias Reservation = Executor.Reservation private final class Record { @@ -59,17 +78,25 @@ final class QwenTensorParallelBatchDriver QwenLayerStageGenerationFinishReason? { - guard let last = tokens.last else { return nil } - if reservation.request.stopTokenIDs.contains(last) { return .eos } - if tokens.count == reservation.request.outputCount { return .length } + /// How the request ends at its first `count` tokens, given the owner's answer to the last. + func finish(_ proceed: Bool, count: Int) -> QwenLayerStageGenerationFinishReason? { + guard count >= 1, count <= tokens.count else { return nil } + if reservation.request.stopTokenIDs.contains(tokens[count - 1]) { return .eos } + if count == reservation.request.outputCount { return .length } return proceed ? nil : .clientStop } + /// Its last token ends the request: no further forward. + var ended: Bool { finish(true, count: tokens.count) != nil } } private let executor: Executor private let book: ClusterBatchLaneBook @@ -78,14 +105,17 @@ final class QwenTensorParallelBatchDriver, capacity: Int, vocabulary: Int, - joinWaitNanoseconds: UInt64 = 30_000_000_000, + joinWaitNanoseconds: UInt64 = 30_000_000_000, foldsControl: Bool = true, now: @escaping () -> UInt64 = { DispatchTime.now().uptimeNanoseconds }) throws { guard (0...1).contains(executor.rank), (1...8).contains(capacity), vocabulary > 0, joinWaitNanoseconds > 0 else { throw ProbeError("Qwen TP batch driver has invalid geometry") } self.executor = executor; self.book = book; self.capacity = capacity; self.vocabulary = vocabulary - self.joinWaitNanoseconds = joinWaitNanoseconds; self.now = now + self.joinWaitNanoseconds = joinWaitNanoseconds; self.foldsControl = foldsControl; self.now = now } private func cancelled(_ record: Record) -> Bool { @@ -101,27 +131,37 @@ final class QwenTensorParallelBatchDriver() + /// This step's plan and report, when they rode the last step's selection sum. + var carried: (plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply)? do { while true { let stop = try autoreleasepool { () throws -> Bool in - let answers = executor.rank == 0 ? try decisions.serviceAndPoll(host) : [:] - if executor.rank == 1 { try host.serviceControl() } - try check() - let localPlan = executor.rank == 0 - ? makePlan(step: step, answers: answers, decisions: decisions, peerCancelled: peerCancelled, - coalescing: &coalescing) : nil - let localReport = executor.rank == 1 ? report(step: step) : nil - let sum = try executor.exchange(QwenTensorParallelBatchWire.contribution( - rank: executor.rank, plan: localPlan, report: localReport), check: check) - let (plan, peer) = try QwenTensorParallelBatchWire.read(sum, step: step, lanes: capacity) - if let localPlan, plan != localPlan { throw ProbeError("Qwen TP leader plan changed in transit") } - if let localReport, peer != localReport { throw ProbeError("Qwen TP follower report changed in transit") } + let plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply + let wasCarried = carried != nil + if let folded = carried { + (plan, peer) = folded; carried = nil + if executor.rank == 1 { try host.serviceControl() } + try check() + } else { + let answers = executor.rank == 0 ? try decisions.serviceAndPoll(host) : [:] + if executor.rank == 1 { try host.serviceControl() } + try check() + let localPlan = executor.rank == 0 + ? try makePlan(step: step, answers: answers, decisions: &decisions, host: host, + peerCancelled: peerCancelled, coalescing: &coalescing) : nil + let localReport = executor.rank == 1 ? report(step: step) : nil + let sum = try executor.exchange(QwenTensorParallelBatchWire.contribution( + rank: executor.rank, plan: localPlan, report: localReport), check: check) + (plan, peer) = try Self.read(sum, step: step, lanes: capacity, plan: localPlan, report: localReport) + } try validate(plan, peer: peer) peerCancelled = Set((0.. Record in guard let record = records[slot], let native = record.native, @@ -130,13 +170,36 @@ final class QwenTensorParallelBatchDriver [Float]? in + guard folds else { return nil } + if executor.rank == 0 { + let answers = try decisions.serviceAndPoll(host) + try check() + nextPlan = try makePlan(step: step + 1, answers: answers, decisions: &decisions, host: host, + peerCancelled: peerCancelled, coalescing: &coalescing, carrying: carrying) + } else { + try host.serviceControl(); try check() + nextReport = report(step: step + 1, carrying: carrying) + } + return try QwenTensorParallelBatchWire.contribution(rank: executor.rank, plan: nextPlan, report: nextReport) + }, check: { try check(); try host.serviceControl() }) + guard result.tokens.count == lanes.count, (result.control != nil) == folds else { + throw ProbeError("Qwen TP decode omitted a lane or its control words") + } + for (lane, token) in zip(lanes, result.tokens) { + try selected(token, lane: lane, decisions: &decisions, host: host, peerCancelled: peerCancelled) + } + if let words = result.control { + let (next, nextPeer) = try Self.read(words, step: step + 1, lanes: capacity, plan: nextPlan, report: nextReport) + carried = (try resolve(next, carrying: carrying), nextPeer) + } } - let prompts = plan.slots.indices.filter { plan.slots[$0].role == .prefill } - guard prompts.count <= 1 else { throw ProbeError("Qwen TP plan has multiple prefill frames") } if let slot = prompts.first { let value = plan.slots[slot] guard let lane = records[slot], let native = lane.native, let frame = native.promptStep(tokens: value.frameCount), @@ -146,9 +209,12 @@ final class QwenTensorParallelBatchDriver, coalescing: inout QwenBatchDecodeCoalescing) -> QwenBatchWire.Header { + /// Rank 0's plan for `step`. `carrying`: rows decoding in the step whose + /// selection sum carries this plan. Each counts the token it is selecting + /// and decodes on it (`carriedToken`) only if the owner already answered + /// the token before it; a stop keeps the tokens the owner saw. + private func makePlan(step: Int, answers: [UUID: Bool], decisions: inout QwenBatchDecisionProgress, + host: QwenBatchServingHost, peerCancelled: Set, + coalescing: inout QwenBatchDecodeCoalescing, carrying: Set = []) throws -> QwenBatchWire.Header { var slots = [QwenBatchWire.Slot](repeating: .init(), count: capacity) for (slot, record) in records { + let carried = carrying.contains(slot) var value = QwenBatchWire.Slot(state: .active, requestID: record.id) value.committedTokens = record.native?.committedTokens ?? 0 - value.selectedTokens = record.tokens.count; value.fingerprintWords = record.fingerprint - let reason = answers[record.id].flatMap { record.finish($0) } + value.selectedTokens = record.tokens.count + (carried ? 1 : 0); value.fingerprintWords = record.fingerprint + // An answer is to the last published token. + let reason = answers[record.id].flatMap { record.finish($0, count: record.published) } if cancelled(record) || peerCancelled.contains(slot) || reason != nil { value.state = .leaving; value.leaveCancelled = cancelled(record) || peerCancelled.contains(slot) value.leaveReason = value.leaveCancelled ? nil : reason - } else if record.native?.canSelectNext == true, decisions.canForward(record.id) { - value.role = .decode; value.inputToken = record.tokens.last ?? -1 + if !value.leaveCancelled { value.selectedTokens = record.published } + record.leaving = true + } else { + if answers[record.id] == true { + try publishHeld(record, decisions: &decisions, host: host, peerCancelled: peerCancelled) + } + if record.native?.canSelectNext == true, record.published == record.tokens.count, + decisions.canForward(record.id) { + value.role = .decode + value.inputToken = carried ? QwenTensorParallelBatchWire.carriedToken : record.tokens.last ?? -1 + } } slots[slot] = value } @@ -208,9 +290,37 @@ final class QwenTensorParallelBatchDriver QwenBatchWire.Reply { + private func report(step: Int, carrying: Set = []) -> QwenBatchWire.Reply { let mask = records.values.reduce(0) { $0 | (cancelled($1) ? 1 << $1.slot : 0) } - return .init(step: step, tokens: (0.. (QwenBatchWire.Header, QwenBatchWire.Reply) { + let (received, peer) = try QwenTensorParallelBatchWire.read(sum, step: step, lanes: lanes) + if let plan, received != plan { throw ProbeError("Qwen TP leader plan changed in transit") } + if let report, peer != report { throw ProbeError("Qwen TP follower report changed in transit") } + return (received, peer) + } + + /// A carried plan was made before the tokens of the step that carried it. + /// A row that decodes on its new token takes it, unless that token ended + /// its request (a stop token or its output count): both ranks read it in + /// the same sum and drop that decode alike. + private func resolve(_ plan: QwenBatchWire.Header, carrying: Set) throws -> QwenBatchWire.Header { + var plan = plan + for slot in plan.slots.indices where plan.slots[slot].inputToken == QwenTensorParallelBatchWire.carriedToken { + guard plan.slots[slot].role == .decode, carrying.contains(slot), let record = records[slot], + let token = record.tokens.last else { + throw ProbeError("Qwen TP carried decode has no carrying row") + } + if record.ended { plan.slots[slot].role = .none; plan.slots[slot].inputToken = -1 } + else { plan.slots[slot].inputToken = token } + } + return plan } private func validate(_ plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply) throws { @@ -229,8 +339,12 @@ final class QwenTensorParallelBatchDriver) throws { guard (0..) throws { + guard lane.published == lane.tokens.count - 1, !lane.leaving, decisions.canForward(lane.id), + !peerCancelled.contains(lane.slot), !cancelled(lane) else { return } + try decisions.published(lane.id) + try host.publishToken(requestID: lane.id, ordinal: lane.published, tokenID: lane.tokens[lane.published], + committedTokens: lane.reservation.request.promptCount + lane.published, logprobs: lane.heldLogprobs) + lane.published += 1; lane.heldLogprobs = nil } private func leave(_ plan: QwenBatchWire.Header, host: QwenBatchServingHost, @@ -293,8 +417,10 @@ final class QwenTensorParallelBatchDriver [Float] { guard (rank == 0 && plan != nil && report == nil) || (rank == 1 && plan == nil && report != nil) else { @@ -42,6 +49,7 @@ enum QwenTensorParallelBatchWire { let report = try QwenBatchWire.Reply(words: Array(values.suffix(QwenBatchWire.replyWords)), expectedStep: step, lanes: lanes) guard report.tokens.allSatisfy({ $0 >= -1 }), report.restored.allSatisfy({ $0 == 0 }), plan.slots.allSatisfy({ !$0.confirming && $0.offers.isEmpty && $0.reusedPrefix == 0 }), + plan.slots.allSatisfy({ $0.inputToken >= carriedToken }), !plan.stop || plan.slots.allSatisfy({ $0.state == .empty }) else { throw ProbeError("Qwen TP batch control message requests an unsupported transition") } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift new file mode 100644 index 0000000000..e19224b0a6 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift @@ -0,0 +1,110 @@ +import DarkbloomClusterProtocol +import CryptoKit +import Foundation +import MLX + +/// Developer bench (`darkbloom-cluster-tp-check qwen-decode`): the batch +/// driver's plain decode on this rank, through the real driver, native +/// executor and the rank's group (two ranks of one Mac over the loopback +/// ring, sealed or not). Each run decodes `width` requests together, with the +/// next step's control exchanged a step or folded into the selection sum; +/// the owner answers each token after `answerDelayMicroseconds`. Logs each +/// run's decode step time and a digest of every request's retired tokens; +/// returns whether every run retired the same tokens. Loopback timings show +/// a step's host work and synchronization, never a pair's. +public enum QwenTensorParallelDecodeBench { + struct Reserved: QwenTensorParallelBatchReservation { + let request: QwenLayerStageGenerationRequest + var deadline: UInt64 { .max } + var laneStateBytes: Int { 1 } + var joinable: Bool { true } + } + + /// Rank 0 publishes; the owner answers "go on" once the delay passed. + final class Owner: QwenBatchServingHost { + let delay: UInt64 + private(set) var times: [UUID: [UInt64]] = [:] + init(delay: UInt64) { self.delay = delay } + func serviceControl() throws {} + func publishToken(requestID: UUID, ordinal: Int, tokenID: Int, committedTokens: Int) throws { + times[requestID, default: []].append(DispatchTime.now().uptimeNanoseconds) + } + func publishToken(requestID: UUID, ordinal: Int, tokenID: Int, committedTokens: Int, + logprobs: ClusterWorkerTokenLogprobs?) throws { + try publishToken(requestID: requestID, ordinal: ordinal, tokenID: tokenID, committedTokens: committedTokens) + } + func awaitDecisions(_ requestIDs: [UUID]) throws -> [UUID: Bool] { throw ProbeError("The decode bench polls answers") } + func publishFinished(requestID: UUID, reason: ClusterWorkerFinishReason) throws {} + func publishPromptCache(requestID: UUID, reusedTokens: Int, storedFrontiers: [Int]) throws {} + func pollDecision(_ requestID: UUID) throws -> Bool? { + guard let last = times[requestID]?.last else { return nil } + return DispatchTime.now().uptimeNanoseconds - last >= delay ? true : nil + } + func publishLeft(requestID: UUID) throws {} + } + + public static func pair(model: QwenTensorParallelModel, configuration: Data, group: any QwenTensorParallelReduction, + width: Int, promptTokens: Int, outputTokens: Int, sampled: Bool, folds: [Bool], + repeats: Int, answerDelayMicroseconds: Int, log: (String) -> Void) throws -> Bool { + guard case .shard(let rank, _) = model.role, (1...8).contains(width), promptTokens > 0, outputTokens > 1 else { + throw ProbeError("The decode bench runs a rank shard with 1 to 8 requests of at least two tokens") + } + let vocabulary = model.plan.vocabularySize, chunk = min(512, promptTokens), budget = promptTokens + outputTokens + let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-decode-bench", vocabularySize: vocabulary, + hiddenSize: model.plan.hiddenSize, activationDType: "bfloat16", maximumPromptTokens: promptTokens, + maximumChunkTokens: chunk, maximumOutputTokens: outputTokens, maximumContextTokens: budget) + var seen: String?, same = true + for (index, fold) in ([folds.first ?? true] + folds.flatMap { Array(repeating: $0, count: max(1, repeats)) }).enumerated() { + Memory.clearCache() + let host = try CBv2StageKVHost(model: model.model, kind: .paged, lanes: width, + maximumTokensPerRequest: budget, maximumChunkTokens: chunk) + let executor = try QwenTensorParallelNativeBatchExecutor(model: model, configuration: configuration, + host: host, group: group, prepare: { _, _ in nil }, completedDecode: { _ in }, completedPrefill: {}, + releaseResources: { _ in }) + let book = ClusterBatchLaneBook() + for row in 0 ..< width { + // Both ranks name the same requests: IDs and prompts follow the run and row. + let id = UUID(uuid: (UInt8(index), UInt8(row), 0, 0, 0, 0, 0x40, 0, 0x80, 0, 0, 0, 0, 0, 0, 1)) + let sampling: ClusterWorkerSampling? = sampled ? .init(temperature: 0.7, topP: 0.9, topK: 32, minP: 0.01, + repetitionPenalty: 1.1, repetitionContextSize: 12, frequencyPenalty: 0.15, presencePenalty: 0.2, + seed: UInt64(77 + row), stream: UInt64(5 * row + 1), logitBias: []) : nil + let request = try QwenLayerStageGenerationRequest(profile: profile, requestID: id, + promptTokenIDs: (0 ..< promptTokens).map { (row * 7_919 + $0 * 104_729 + 11) % vocabulary }, + chunkSize: chunk, outputCount: outputTokens, stopTokenIDs: [], sampling: sampling) + try book.reserve(id, Reserved(request: request), lanes: width) + try book.start(id) + } + let owner = Owner(delay: UInt64(max(0, answerDelayMicroseconds)) * 1_000) + let driver = try QwenTensorParallelBatchDriver(executor: executor, book: book, capacity: width, + vocabulary: vocabulary, foldsControl: fold) + var retired: [UUID: [Int]] = [:] + let started = DispatchTime.now().uptimeNanoseconds + try MLX.withError { error in + try driver.serve(host: owner, retiredSelection: { id, tokens, _ in retired[id] = tokens }, + check: { try error.check() }) + } + let total = Double(DispatchTime.now().uptimeNanoseconds - started) / 1e6 + var hash = SHA256() + for id in retired.keys.sorted(by: { $0.uuidString < $1.uuidString }) { + hash.update(data: Data(retired[id]!.flatMap { withUnsafeBytes(of: Int32($0).littleEndian, Array.init) })) + } + let digest = hash.finalize().prefix(8).map { String(format: "%02x", $0) }.joined() + guard retired.count == width, retired.values.allSatisfy({ $0.count == outputTokens }) else { + throw ProbeError("The decode bench retired another set of tokens") + } + // The first run warms the kernels; it is checked, never timed. + if index == 0 { seen = digest; continue } + same = same && seen == digest + // Rank 0: each request's decode, from its first token to its last, per token. + let steps = owner.times.values.map { Double($0.last! - $0.first!) / 1e6 / Double($0.count - 1) }.sorted() + log("qwen-tp-decode-v1 rank=\(rank) control=\(fold ? "folded" : "exchanged") width=\(width)" + + " sampled=\(sampled ? 1 : 0) answer_delay_us=\(answerDelayMicroseconds) prompt=\(promptTokens)" + + " output=\(outputTokens) total_ms=\(String(format: "%.1f", total))" + + (steps.isEmpty ? "" : " step_ms_median=\(String(format: "%.3f", steps[steps.count / 2]))" + + " step_ms_min=\(String(format: "%.3f", steps.first!)) step_ms_max=\(String(format: "%.3f", steps.last!))") + + " tokens=\(digest)") + } + log("qwen-tp-decode-v1 rank=\(rank) token-check \(same ? "same-tokens" : "DIFFERENT")") + return same + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift index 5cafe9bdb6..d159622756 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift @@ -9,6 +9,7 @@ final class QwenTensorParallelNativeBatchLane: QwenTensorParallelBatchLane { var accepted = QwenTensorParallelAcceptedSelections() var selectedCount = 0 var canSelectNext: Bool { !accepted.isEmpty || nextFrame?.phase == .decode } + var plainSelection: Bool { assistant == nil } var prefixKey: String? /// This request's scope on the SSD tier, kept for its persist after a /// confirmed clean retirement. @@ -296,15 +297,16 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> [Int] { + func decode(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?, + check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) { try GPU.withCommandBufferLimits(QwenTensorParallelBatchSession.decodeCommandBuffers) { - try decodeRound(lanes, tokens: tokens, check: check) + try decodeRound(lanes, tokens: tokens, control: control, check: check) } } @@ -333,11 +335,13 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> [Int] { + private func decodeRound(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?, + check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) { guard !lanes.isEmpty, lanes.count == tokens.count, lanes.count <= host.lanes, Set(lanes.map { ObjectIdentifier($0) }).count == lanes.count else { throw ProbeError("Qwen TP accepted selections require distinct scheduled lanes") } + var carried: [Float]? if let context = assistant, let quote = context.cohortBudget { let frontiers = cohortFrontiers(lanes, tokens: tokens, depth: context.depth) let eligible = frontiers.keys.sorted() @@ -396,7 +400,14 @@ final class QwenTensorParallelNativeBatchExecutor
`) cannot complete a stop sequence on its own. - A stop sequence that names a marker no longer fires on it: `
`, or From ce95ac8d406f2e1941773f35bb35818b823bc115 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 02:24:21 -0800 Subject: [PATCH 51/58] ci: re-run checks after runner checkout timeouts No file changes. In CI run 41412596359, Provider Unit Tests shards 4 and 5 hung in actions/checkout on self-hosted runners and reached the job time limit before any test ran; Docs Impact in the Contribution Policy run hung the same way. Co-Authored-By: Claude Opus 5.5 From 253801c32c7aac7783b137928d2c74b2ff62c548 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 06:17:37 -0800 Subject: [PATCH 52/58] ci: one more run after a runner checkout timeout No file changes. CI run 41428558024 on the identical tree had Provider Unit Tests shard 1 hang in actions/checkout on a self-hosted runner until the job time limit; shards 2-5 passed there and shards 1-3 passed in run 41412596359. Co-Authored-By: Claude Opus 5.5 From 02bb2899ebfc0280f61b222d47c1927f56ee7478 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 23:23:18 -0800 Subject: [PATCH 53/58] docs: reconcile pipeline notes with current dev Preserve the authored pipeline decode notes and the current dev documentation before a non-force dev refresh. Only documentation conflict preparation; no production qualification claim. AI-assisted integration by Darkbloom Provider (Hermes). --- docs/architecture/hardware-support.md | 57 +++++- docs/architecture/inference.md | 252 ++++++++++++++++++++++++-- 2 files changed, 283 insertions(+), 26 deletions(-) diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index d74f5b25b9..4da0ba050d 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1220,17 +1220,54 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacem ### Qwen27 TP batch prefix ownership -`QwenTensorParallelBatchPrefixBudget` separately bounds every compact attention, -conv and SSM array using the native allocator metadata. Full unsliced geometry -conservatively covers either rank and unequal shares. The complete native -batch allowance adds one snapshot bank per live lane plus two banks for the -resident cache; the existing live-state, gather, replacement and collective -charges remain. The metadata planner and verified LOAD call the same helper. -A reused prefix does not lower admission or refund the destination's future -state. The configured budget is a ceiling; cache arrays materialize only on -capture. See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). +`QwenTensorParallelBatchPrefixBudget` prices one plain lane's prompt-prefix +capture, separately bounding every array with the native allocator metadata: +its own heads' keys and values to its deepest kept boundary, and one +convolution and SSM state for every boundary a prompt with that deepest +boundary keeps (`pricedStates`: the deepest, the margin boundary, and the +stripe boundaries up to nine, so at most eleven, and never fewer for a longer +prompt). Each request's reservation charges its own prompt's capture +(`QwenTensorParallelRequestCharge`); LOAD and the placement quote charge one +capture of the profile's longest prompt per lane (`promptTokens`), and nothing +for a resident tier. The geometry is the rank's own heads at LOAD and in each +rank's placement quote; without a rank, the full unsliced geometry covers either +rank and unequal shares. The existing live-state, gather, replacement and +collective charges remain, and a reused prefix does not lower admission or +refund the destination's future state. + +The memory tier that keeps captures after their requests is charged nowhere. +Its budget is half the room LOAD measures beside its whole quote +(`ClusterStagePrefixBudget.roomBytes`, `QwenStagePrefixCache.budget(roomBytes:)`): +at most a thirty-second of the Mac's memory, in 256 MiB steps, and 0 when the +room is under 512 MiB. The reservation and running-batch gates do not credit +its entries as the owner's own allocations, nor, while the SSD writer is busy, +up to its queue's byte bound for the retired captures it still holds; the +writer drains and then the entries give way before either gate refuses +(`QwenTensorParallelSnapshotCache.yieldingMemory`). A capture always keeps what +its request's charge covers. With no tier budget it keeps nothing resident and +still writes its SSD record. A request whose prompt exceeds the memory plan's +is charged at its own prompt, outside LOAD's per-lane quote +([native context](inference.md#qwen27-tensor-parallel-native-context)). The assistant's lanes +keep their single 4,096-token frontier and its two charged resident banks +(`QwenTensorParallelMTPPrefixBudget`). See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). + +The registered Qwen3.8 27B, one rank's own heads at the memory plan (32,768 +prompt tokens, 65,536 context, 16 KiB allocator pages; +`QwenTensorParallelBatchPrefixTests`, `QwenTensorParallelPrefixPlacementTests`): + +| Term | Before (`qwen-tp-batch-grid-prefix-4096-v1`) | Now (`qwen-tp-batch-prefix-depth-v2`) | +|---|---|---| +| A lane's capture | 212,860,928 B (4,096 tokens) | 1,764,753,408 B (rows to 32,256 and nine recurrent states) | +| Resident tier in the quote | 425,721,856 B (two banks) | 0 (half the measured room) | +| LOAD request bytes, one lane | 9,184,591,872 B | 10,310,762,496 B | +| LOAD request bytes, eight lanes | 28,471,181,312 B | 40,460,599,296 B | +| Idle pairs the planner places tensor parallel on, one lane | 2 x 36 GiB and larger | the same; a rank needs 1,126,170,624 B more | +| The same, eight lanes | 2 x 96 GiB and larger | the same; a rank needs 11,989,417,984 B more | + +The planner rows leave out the vision tower's resident bytes, as the served +layout does; both columns leave them out alike. Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift` -(`derive`). +(`captureBytes`, `derive`). A drained automatic batch replacement uses the device index and this pair's recorded keyed-link measurement. Missing or invalid measurements continue to diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index d032d74517..8273852658 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1581,6 +1581,15 @@ never crosses a cache scope; `DARKBLOOM_TTFT_PROMPT_CACHE=0` restores the unchanged path ([configuration](../reference/configuration.md#prompt-preparation-and-admission)). +Decoded text keeps the spacing the tokens spell, unless the tokenizer config sets +`clean_up_tokenization_spaces` to true. swift-transformers reads an absent key as +true, which drops the space in sequences such as ` .`, ` ,`, ` ?`, ` !` and ` 's`, +and can make a streamed decode repeat bytes it already sent. Gemma 4's published +config omits the key. `LocalTokenizerLoader` +(`provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift`) +resolves an absent key to false in memory, as Python Transformers does, and keeps +an explicit Boolean. Input IDs, sampling and cache keys do not depend on it. + Bridge-side order (`EngineV2Bridge.submitTokenized`): request-id normalisation (`maxRequestIdLength = 256`; duplicates rejected) → first deadline check → translation (`maxTokens = request.max_tokens ?? @@ -1594,11 +1603,21 @@ The SSD stage runs before `engine.submit`, off the engine queue, while the engine may be evaluating another request's prefill chunk under MLX-Swift's process-wide `evalLock`. A provider-staged complete-checkpoint import therefore creates its destinations already available from host bytes and never evaluates -or fences them, so staging does not wait for that chunk +or fences them, so staging does not wait for that chunk; its CPU decode tests each +restored row once for values the native dtype cannot hold, and a refused row never +reaches a destination ([destination contract](../reference/ssd-kv-cache.md#complete-checkpoint-payload), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift` (`CBv2CompleteCheckpointImport`)). +A donor's stream retires only after its complete checkpoint is published +(`EngineLoopV2.finishAfterCompletePrefixPublication`), so export time is added +to the donating response's end. At a quantized checkpoint precision, export +encodes each older attention row on the CPU with one prepared row encoder per +segment read, which writes the scalar codec's exact bytes +([conversion](../reference/ssd-kv-cache.md#complete-checkpoint-payload), +`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/NativeQuantizedCheckpointTensorSource.swift`). + Segmented paged admission no longer waits for queued GPU work. A released row's free 64 MiB segments are parked per pool, up to `min(2 GiB, slot grant / 8)`, outside the grant, floor and ledger charge, and the next admission of the same @@ -2891,7 +2910,15 @@ a share of every layer, and one fewer than the members otherwise, as the coordinator requires. A setup with unequal tensor-parallel shares is refused at registration, because the provider does not encode the plan's `tensor_parallel_shares` yet: a plan without them is an equal split to the -coordinator. Under a model approval, which names no build, the plan also carries +coordinator. So a cluster served through Darkbloom is planned with equal shares +only (`ClusterPlacementPolicy.equalTensorShares`, which +`ClusterPlacementFlow.decide` sets for the coordinator scope: the guided setup, +the plans it forwards and the service's re-plans after an update or a memory +refusal), and a local cluster keeps the faster unequal split. Each Mac's check +of a cluster approval refuses one beside unequal shares +(`ClusterApprovalAttachment.attachment`; +[coordinator-paired member](../reference/configuration.md#coordinator-paired-member)). +Under a model approval, which names no build, the plan also carries the member's own runtime block (`ClusterPlan.runtime`: worker, capability, resource policy and profile from its saved setup, `DistributedInstalledNativeStart.runtimeBlock`), so both members must run the @@ -2961,9 +2988,16 @@ live line (`ClusterOnboardingDriver.move`, `ClusterOnboardingProgress.live`), laid out by `TransferProgressLine` through `ClusterTransferReports`; a transcript without a live line keeps only the reports `TransferProgressLine.takeLogLine` marks and the lines for the record. +Its restart line reads FileVault with `fdesetup isactive` +(`OnboardingLive.fileVaultOn`): five seconds, then SIGTERM and two more, and no +answer reads as unknown. The exit comes from `ProcessExitObserver`, which does not run the calling thread's run loop. After a Darkbloom update changes a Mac's worker digest, the control leader's cluster service re-plans and re-adopts the same model by itself -(`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`). A model change of +(`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`), once both Macs +answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`): the +[pair's coordinated update](../provider/cluster-always-on.md#the-pairs-coordinated-update) +restarts the two Macs seconds apart, and a plan made while one still runs the +other build would fail and wait 600 s. A model change of a serving cluster (`m`, or `darkbloom cluster local `) plans the same way: its list was priced while the running parts held their memory, where tensor parallel may not fit now, so once both parts stopped and both Macs gave the @@ -3538,6 +3572,41 @@ part the same key with a different file (`ClusterServiceAgent.partHealthPath`, service's heartbeat and still waits for its registration as a supervised member. An empty or absent key is passed on unchanged. +## Cluster service listeners follow the cable and the pairing + +Each Mac's cluster service answers the other Mac on two listeners: the setup +exchange's (`ClusterSetupLinkExchange.port`) and the control lease's +(`ClusterSetupLinkExchange.controlPort`). A listener binds the cable's port and +address as they are when it starts, and is keyed with the pairing that holds +then (`ClusterSetupLinkExchange.Responder.pairing`). It refuses every handshake +the other Mac keys with a later pairing (`handshakeRejected` there), so a +listener left on an earlier pairing refuses every lease and setup request. + +At most once per `ClusterService.listenerCheckSeconds` +(`static let listenerCheckSeconds: Double = 5`) seconds for each listener, +`ClusterService.listenerChange` compares the listener with what holds now: + +- a cable on another port or address restarts it there; +- another pairing restarts it with that pairing. `ClusterSetupLinkExchange.Pairing.Identity` + compares both pins, the cluster label, the link epoch and the edge, never the + edge secret; every ceremony derives a new link epoch, so pairing the same two + Macs again is another pairing; +- no pairing at all stops it; +- a pairing store that cannot be read changes nothing, as an unreadable setup + record leaves a running part alone. + +Each restart or stop of the exchange's listener names its reason in the service +log; the control lease's listener restarts and stops without a line. The +control node of an earlier pairing is dropped once the pairing names another +local or peer member (`ClusterService.ensureControl`). + +Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift` +(`ClusterService.listenerChange`, `ensureResponder`), +`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift` +(`ensureControlResponder`, `ensureControl`) and +`provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift` +(`ClusterSetupLinkExchange.Responder`). + ## GLM tool-stream completion GLM tool output uses the SDK GLM parser to validate the complete tool suffix at @@ -3790,7 +3859,24 @@ forwards fuse, on the families measured byte-equal to the unfused operations the Gated DeltaNet convolution step (concatenation, depthwise convolution and SiLU) and its q/k normalization, the attention output gate, the SwiGLU product, and a single vector's gate, up and SwiGLU in one launch (a window keeps the two -projections: the fused kernel measured slower there). A residual stream +projections: the fused kernel measured slower there). That one-launch SwiGLU +(`AffineQuantizedVectors.projectSwiGLU`) computes its sigmoid as MLX's +`Sigmoid` does, with `metal::precise::exp`; Metal's default fast `exp` rounds +the bf16 gate -6.84375 to another SwiGLU value. Only a tensor-parallel batch +session's one-row decode step takes that kernel (it needs +`Qwen35BatchDecodeScope.exactVectors`; single-Mac serving and +`darkbloom-cluster-tp-check run` never do), so with the fast `exp` a registered +27B row alone left the bits of its cohort and window steps. Tensor-parallel +serving output recorded with an earlier build differs only where such a step +met that gate, and is regenerated once. +`AffineQuantizedVectorsTests.swigluEqualsTheCompiledSwiGLUAtEveryGateValue` +compares the kernel with the two projections and the compiled SwiGLU at every +normal bf16 and f16 gate value. The convolution step's SiLU +(`GatedDeltaConvolution`) still uses the default `exp`, so it can round +differently from the unfused SiLU that prompt chunks of more than eight tokens +take (`Qwen35DecodeFusionParityTests` finds f16 and f32 differences); every +decode row count and window of up to eight columns takes that kernel, so rows +still agree. A residual stream narrower than its norms (the Prism/Bonsai packs: FP16 packed embedding rows under FP32 norms and projections) keeps the unfused sum that promotes it to FP32 on every family (`Qwen35DecoderLayer.residualNorm`); the fused step @@ -4037,7 +4123,7 @@ See [focused cluster tests](../developer/test.md#focused-qwen35-moe-tensor-paral GLM's placement family (`GLM5NextPlacementFamily`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Metadata/GLM5NextServingMetadata.swift`) offers the two-rank plan `glm5_next_heads_and_expert_channels_v1` whenever the registered row lists `tensor_parallel_v1` and the geometry halves. Each text-layer tensor is divided or replicated exactly as the SDK's `GLM5NextTensorShard.splitAxis` loads it; the embedding, final norm and head are replicated, and the NextN layer and vision tower belong to no text range. Every rank decodes in speculative rounds with the NextN layer, which it holds whole beside its share, so the plan states it (`ClusterTensorParallelFamilyPlan.speculativeHead`, `GLM5NextPlacementFamily.tensorParallelSpeculativeHead`): the planner charges each tensor-parallel rank the layout's `speculativeHead` part (4,183,320,576 stored bytes, each tensor in whole pages, as `mtp_bytes` on the worker's load line) and the request memory the rounds add at the memory plan's context (the larger of the contiguous and the paged NextN charge of `GLM5NextTensorParallelRequestCharge`), and divides a token's predicted decode step by the speed-up the pair measured at the runtime's depth over one token per step (76.0 against 62.6 tok/s at depth 2, `GLM5NextPlacementFamily.measuredTensorParallelDecode`). Served tensor-parallel requests are taken back to one-token steps by the same speed-up before they correct the shares (`ClusterServedCalibration`), so the next plan predicts what was served. Without it the plan priced no NextN bytes and one token per step: it could admit a pair the load gate then refused, and it predicted decode too slow. Three terms of the load gate are not in the plan yet: the vision tower rank 0 holds for media (1.13 GB), the freed-buffer cache (`GLM5NextTensorParallelResidentRuntime.freedBufferCacheBytes`) and the bulk prefill's further workspaces and sealed sums' buffers (`bulkPrefillChunkTokens`). On two M5 Ultra 256 GB, adding them to the planner's estimate as it stands would put each rank's need above the at-rest ceiling (`ClusterDeviceProfile.atRestAdmissibleBytes`), so the pair would no longer plan tensor parallel; they wait for the gate's own charge to replace the estimate rather than be added to it. The plan sums two partials of the 4096-wide residual per layer and one per step (91 per decode step); the partials are the row-parallel projections' bfloat16 outputs, sent as they are and added in float32 with one rounding (`GLM5NextTensorParallelResidentRuntime.partialsTransport`, bound into the load agreement). That is bit-identical to widening them to float32 before the link, as `ClusterTensorParallelTerms.current` (`partialsDType` float32) describes, with half the bytes: GLM's projections never kept float32 partials (flagged for platform review) and holds request state whole on each rank, since the DSA latent cache is replicated. The pipeline's private image profile stays pipeline-only, in both the layout and the capability; tensor parallel serves media under the text profile (below). The hardware prior (`ClusterHardwarePrior.decodeBytesPerToken`) counts a mixture of experts' routed experts at the fraction a token is routed to (`ClusterRoutedExperts`; 8 of GLM's 288), not every expert byte. Of the bytes a step reads, a tensor-parallel share divides only the plan's divided bytes (`dividedDecodeFraction`), because every rank reads its replicated bytes whole. On two identical M5 Ultra 256 GB with GLM measured alone the product's rule (tensor parallel first wherever it fits) places tensor parallel on equal shares with the NextN layer priced, both on a new pair before any load measured the link and after the first load's keyed probe; the planner's own speed comparison (the plan tool without `--tensor-parallel-first`) chooses tensor parallel once the keyed link is measured and a pipeline before (`GLMTensorParallelChecks`; through `ClusterPlacementFlow.decide` in `PlacementSetupCheck.glmTensorParallelPair`). The pair serves it with eight lanes (`DistributedInstalledPlan.tensorParallelBatchLanes`). -A chosen GLM tensor-parallel placement is served by `GLM5NextTensorParallelResidentRuntime` (`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/`). Each rank verifies the whole artifact, loads every layer's share through `GLM5NextTensorShard`, and sums each layer's attention and feed-forward partials (bfloat16, added in float32) over the sealed all-sum (AES-256-GCM on the keyed JACCL data plane; a peer piece that does not open fails the request). On the JACCL mesh the sum is streamed in one CPU-stream task: each 256 KiB sealed piece carries its own tag, crosses as soon as it is sealed and is opened and added as soon as it lands, so only the first and last pieces wait for crypto (`SealedAllSum`, `sealed_stream.h`); other groups seal and gather the whole frame. Prefill runs 4,096-token chunks on both ranks (`prefillChunkTokens`: the M5 neural accelerators reach ~94 TFLOPS on 4,096-row NVFP4 matmuls against ~62 at 2,048; charged as a second request workspace), each chunk as two micro-batches whose sums are issued as soon as their partials exist, so one computes while the other's sum crosses the link (`GLM5NextTextStage.tensorParallelMicroBatches`; 2,532 against 1,767 tok/s whole); sampled decode runs one token per step, and the ranks' tokens must agree at every step. A tensor-parallel worker lifts MLX's per-command-buffer input-size bound before anything native starts (`WorkerCommandBufferBudget`, `MLX_MAX_MB_PER_BUFFER`; a launcher value is kept): every MoE launch takes a whole expert bank as input, so decode committed ~88 buffers a step instead of ~22 (measured 19.0 -> 16.8 ms a step; the 50-operation bound stays). Decode steps, MTP rounds and lane rounds encode with at most 100 operations a buffer on the thread that encodes them (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`), above the owner's 16-operation rank guard, which prefill keeps: each further buffer is a GPU gap of about 10 µs (13.24 -> 12.56 ms a step, tokens identical). An MTP round submits its NextN priming and proposals as soon as they are built, so the GPU runs them while the host builds the verification forward (`GLM5NextTensorParallelSpeculation.EarlySubmission.proposals`; before, the whole round's graph, about 1.8 ms of host work, was built with the GPU idle): a depth-2 round 23.06 -> 21.64 ms (95.9 -> 102.7 tok/s), two lanes 115.2 -> 121.6 tok/s, tokens and top logits identical. A greedy round reads out half the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum: each rank's slot carries its half's maximum and argmax, and the larger maximum wins, rank 0's lower index on a tie, which is the whole head's argmax (`GLM5NextTensorParallelSpeculation.splitsVocabulary`, `GLM5NextTextStageReadout.allTokensVocabularyPart`): 21.32 -> 21.05 ms a depth-2 round, tokens identical; sampled rounds keep the whole head. A GLM tensor-parallel worker lets the hyper-connection site that reads a sum wait for it itself (`WorkerFenceFusion`: `MLX_METAL_FENCED_INPUTS`; a launcher value is kept), one dependent dispatch fewer on each of a step's 90 sums. The core's fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: above 32 KB a partial's update is split over several threadgroups and that path never signals the CPU, so two batched lanes (six verification rows) stalled every round about 0.7 s. The load gate charges the shard, the NextN layer, both pipeline ranks' request budgets plus speculative decode's request state, and a 4 GiB freed-buffer cache (the load runs with MLX's cache at zero; serving with it at zero halves prefill and decode). READY names the installed partition's plan hash, as a pipeline rank does. Prompt prefixes are reused as under Qwen tensor parallel: each rank keeps its own stage cache (its heads' KDA state and the replicated DSA latents) at a prompt's last whole chunk boundary in memory (`GLM5NextTensorParallelPrefixCache`, at most 8 GiB), and a request restores the longest boundary both ranks hold after one sealed vote, or neither does; entries give way first under memory pressure and every failure drops them. Each request's entries are its own partition's (`GLM5NextTensorParallelResidentRuntime.prefixScope`, see [tenant partitions](prefix-cache.md#cluster-prefix-tenant-partitions)): a tenant's boundaries are voted, restored and kept for that tenant alone, and a request whose cache is off votes and keeps none, on a cache-on request's frames. Each rank also keeps a cleanly retired request's boundary in the encrypted SSD tier, read from the memory entry's pages behind serving; the vote counts those records, and a boundary taken from one is restored into the request's own pages only after a second sealed exchange confirms both ranks have it, in the same partition (`prefixDiskScope`), so a restarted pair restores what the last one kept ([GLM TP prefix SSD tier](prefix-cache.md#glm-tp-prefix-ssd-tier)). The link probe that prices the reduction (`QwenTensorParallelLinkProbe`, recorded by both pipeline and tensor-parallel loads) times the sealed all-sum after one unmeasured pass with the same bounded cache, so the planner prices what a ready rank pays (a cold probe read 16.9 ms per 32 MiB against 5.8 ms ready). +A chosen GLM tensor-parallel placement is served by `GLM5NextTensorParallelResidentRuntime` (`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/`). Each rank verifies the whole artifact, loads every layer's share through `GLM5NextTensorShard`, and sums each layer's attention and feed-forward partials (bfloat16, added in float32) over the sealed all-sum (AES-256-GCM on the keyed JACCL data plane; a peer piece that does not open fails the request). On the JACCL mesh the sum is streamed in one CPU-stream task: each 256 KiB sealed piece carries its own tag, crosses as soon as it is sealed and is opened and added as soon as it lands, so only the first and last pieces wait for crypto (`SealedAllSum`, `sealed_stream.h`); other groups seal and gather the whole frame. Prefill runs 4,096-token chunks on both ranks (`prefillChunkTokens`: the M5 neural accelerators reach ~94 TFLOPS on 4,096-row NVFP4 matmuls against ~62 at 2,048; charged as a second request workspace), each chunk as two micro-batches whose sums are issued as soon as their partials exist, so one computes while the other's sum crosses the link (`GLM5NextTextStage.tensorParallelMicroBatches`; 2,532 against 1,767 tok/s whole); greedy and sampled requests then decode in MTP rounds (below). A tensor-parallel worker lifts MLX's per-command-buffer input-size bound before anything native starts (`WorkerCommandBufferBudget`, `MLX_MAX_MB_PER_BUFFER`; a launcher value is kept): every MoE launch takes a whole expert bank as input, so decode committed ~88 buffers a step instead of ~22 (measured 19.0 -> 16.8 ms a step; the 50-operation bound stays). Decode steps, MTP rounds and lane rounds encode with at most 100 operations a buffer on the thread that encodes them (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`), above the owner's 16-operation rank guard, which prefill keeps: each further buffer is a GPU gap of about 10 µs (13.24 -> 12.56 ms a step, tokens identical). An MTP round submits its NextN priming and proposals as soon as they are built, so the GPU runs them while the host builds the verification forward (`GLM5NextTensorParallelSpeculation.EarlySubmission.proposals`; before, the whole round's graph, about 1.8 ms of host work, was built with the GPU idle): a depth-2 round 23.06 -> 21.64 ms (95.9 -> 102.7 tok/s), two lanes 115.2 -> 121.6 tok/s, tokens and top logits identical. A greedy round reads out half the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum: each rank's slot carries its half's maximum and argmax, and the larger maximum wins, rank 0's lower index on a tie, which is the whole head's argmax (`GLM5NextTensorParallelSpeculation.splitsVocabulary`, `GLM5NextTextStageReadout.allTokensVocabularyPart`): 21.32 -> 21.05 ms a depth-2 round, tokens identical; sampled rounds keep the whole head. A GLM tensor-parallel worker lets the hyper-connection site that reads a sum wait for it itself (`WorkerFenceFusion`: `MLX_METAL_FENCED_INPUTS`; a launcher value is kept), one dependent dispatch fewer on each of a step's 90 sums. The core's fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: above 32 KB a partial's update is split over several threadgroups and that path never signals the CPU, so two batched lanes (six verification rows) stalled every round about 0.7 s. The load gate charges the shard, the NextN layer, both pipeline ranks' request budgets plus speculative decode's request state, and a 4 GiB freed-buffer cache (the load runs with MLX's cache at zero; serving with it at zero halves prefill and decode). READY names the installed partition's plan hash, as a pipeline rank does. Prompt prefixes are reused as under Qwen tensor parallel: each rank keeps its own stage cache (its heads' KDA state and the replicated DSA latents) at a prompt's last whole chunk boundary in memory (`GLM5NextTensorParallelPrefixCache`, at most 8 GiB), and a request restores the longest boundary both ranks hold after one sealed vote, or neither does; entries give way first under memory pressure and every failure drops them. Each request's entries are its own partition's (`GLM5NextTensorParallelResidentRuntime.prefixScope`, see [tenant partitions](prefix-cache.md#cluster-prefix-tenant-partitions)): a tenant's boundaries are voted, restored and kept for that tenant alone, and a request whose cache is off votes and keeps none, on a cache-on request's frames. Each rank also keeps a cleanly retired request's boundary in the encrypted SSD tier, read from the memory entry's pages behind serving; the vote counts those records, and a boundary taken from one is restored into the request's own pages only after a second sealed exchange confirms both ranks have it, in the same partition (`prefixDiskScope`), so a restarted pair restores what the last one kept ([GLM TP prefix SSD tier](prefix-cache.md#glm-tp-prefix-ssd-tier)). The link probe that prices the reduction (`QwenTensorParallelLinkProbe`, recorded by both pipeline and tensor-parallel loads) times the sealed all-sum after one unmeasured pass with the same bounded cache, so the planner prices what a ready rank pays (a cold probe read 16.9 ms per 32 MiB against 5.8 ms ready). Greedy requests under GLM tensor parallel decode speculatively with the model's own NextN (MTP) layer (`GLM5NextTensorParallelResidentRuntime.mtpDepth`, depth 2; `GLM5NextTensorParallelSpeculation`). Every rank loads the layer whole beside its shard (about 4.2 GB; it shares the replicated embedding and head and needs no sums), so both ranks propose the same tokens from the same inputs. A round proposes up to `mtpDepth` tokens (step 0, then index-shared continuations for depth 2 and 3), verifies the last committed token and the proposals in one stage forward (`GLM5NextTextStage.prepareVerification`: a `[1, 1 + depth]` window through the same 91 sums), and keeps the longest prefix of proposals equal to the target's greedy tokens, plus the target's next token. Each KDA layer adopts the state it captured after the last kept token and each DSA history drops the rest (`GLM5NextTextStageCandidate.commit(afterEvaluating:keeping:)`), so a rejected proposal costs no replay forward. The round's one sealed reduction carries each rank's target tokens, proposals and stop flag: tokens or proposals that differ end the request, and a stop flag on either rank ends both after the same round. Rounds are not pipelined; each reads its agreement before the next is built, but a round's tokens are committed while the next round runs (`GLM5NextTensorParallelSpeculation.round`, `whileRunning`), unless they end the request. The NextN history is primed from the prompt's hidden rows (history only: no attention, MoE or readout) and afterwards only from verified pairs, and prompt-prefix entries keep it at their boundary. Tokens leave one at a time through the same stop and length rules. The output is the target's greedy tokens, computed in windows of up to `1 + depth` rows instead of one-row steps. MLX runs a one-row quantized projection (and the head) as `qmv` and a multi-row one as `qmv_wide`, which reduces K in a different order, so every window rounds differently from a one-token step and the KDA and DSA histories carry that forward: a long speculative decode drifts from one-token greedy decode and can choose a different token after tens to hundreds of tokens, not only at near-ties (measured on the 3,931-token prompt: first difference at output 104 for depths 1 and 2, and at 89 for depth 3; `qmv_wide` rounds a row the same in two- and three-row windows). The ranks never differ, and a one-token window is bitwise an ordinary step (`darkbloom-cluster-tp-check glm --mtp-check one-token`; `keep-first` decodes one token per round through full windows to separate this arithmetic from acceptance and rollback). On the pair (sealed, 256 tokens) decode measured 62.6 tok/s one token per step, 68.7 at depth 1, 76.0 at depth 2 (2.24 tokens a round) and 71.8 at depth 3. Sampled requests decode in rounds too: each proposal is drawn with the request's own sampler and the keyed noise of the output index it is for (coupled drafting, `GLM5NextTensorParallelResidentRuntime.coupledDraftSharpness`), and every committed token is the target's draw from its window logits; the sampler moves only acceptance. The load agreement binds the depth (`glm5-next-tp-mtp-v1`). The planner prices the rounds and the NextN layer as described above (`ClusterTensorParallelSpeculativeHead`). @@ -4045,7 +4131,7 @@ The proposals a round verifies can follow the pair's load (`GLM5NextTensorParall GLM image and video input under tensor parallel (`ClusterGLMMedia`, contract `glm53_tp_media_v1`) is the single-Mac product's media path split across the leader and rank 0. The leader runs the product's code up to the vision tower (`DistributedGLMMediaIngress`): `EngineV2VisionPrefill.glm5NextUserInput` (the bounded `MediaIngest` decode and every product cap) and `GLM5NextProcessor.prepareDetailed` with the artifact's processor budgets and the thinking-off tokenizer, on the CPU device, so the expanded prompt, its spans and its patches are the product's; it checks them as `buildGLM5NextSubmission` does and describes each part: its encoded bytes' digest, grid, per-pair token offsets, the product's tower limits for one frame (`VisionTowerBudget.glm5FrameLimits`) and a SHA-256 of its prepared patches. Rank 0's reservation carries the encoded bytes as well (at most 32 MiB, the one worker command above the 8 MiB command bound: `ClusterWorkerLimits.mediaCommandBytes`); rank 1's carries the digests only, and both bind the envelope's fingerprint into the request digest. Rank 0 holds the vision tower (1.13 GB of bfloat16 weights, charged at load). From the reservation on, off the executor and without MLX, rank 0 rebuilds the ingest's media values, prepares them with the SDK's `GLM5NextProcessor.prepareMediaValues` (the media half of `prepareDetailed`, as host values) and requires every grid and patch digest to equal the leader's; the reservation itself returns at once. When the request opens, after the digest agreement, both ranks exchange small sealed sums carrying that preparation's status and each rank's stop until it ended (a stop ends the request on both ranks before anything is made; a failed or different preparation is an agreement failure on both). Rank 0 then runs the tower once per temporal pair with the leader's limits on the default GPU stream, as the product does, and one sealed all-sum per frame carries the features to rank 1, which adds negative zero (the additive identity for every value, signed zeros included, rounded once); rank 0 checks each result bit for bit and a last small sum carries its verdict, so both ranks end together on a difference. Every one of these sums is evaluated alone. With batch lanes a media lane runs the same open, frames and rounds: rank 0 joins it only once its preparation ended (`GLM5NextTensorParallelLaneReservation.joinable`), so the running lanes never wait for a decode, and its media charge is held with its lane state. A prefill frame that holds media positions replaces their embedding rows with the features by concatenation (the product's `spliceEmbeddings`) and runs from those embeddings through the same chunks and micro-batches (`GLM5NextTextStage.prepareForward(embeddings:cache:segments:readout:snapshotAfter:)`), so a frame merging several chunks stays bitwise for media rows as for text; every other row and frame is the text path's, on tensor parallel's own chunk grid. Unlike the single-Mac product, which decodes media requests target-only, a media request here decodes speculatively as text does: the NextN history is primed with the same input rows, so a media position's next input is its feature row (`GLM5NextMTP.primeHistory(shiftedEmbeddings:)`, as a multimodal target's drafter is fed). It neither restores nor stores prompt prefixes. Workers advertise the contract at READY (`ClusterWorkerReady.media`) with a request capacity that covers one media request (`GLM5NextTensorParallelMedia.capacityBytes`); a text request is still charged only its own context. The leader binds media only when both ranks advertise it, and the pipeline's private image profile is unchanged. -Rank 0 hands each committed token to its owner and reads the owner's answer late (`ClusterCommittedTokenChannel`, `WorkerRuntime.start(_:tokens:)`): it publishes the token at once, and reads the answer after the next step or round was submitted, before it publishes the next token. The protocol's token credit is unchanged (`ClusterWorkerSession` still refuses a token before the answer to the one before, and anything after a stop), but the answer's round trip through the owner (pipes, the provider's token callback and detokenizer; about 0.7 ms a token measured at the endpoint; greedy decode went from 73.5 to 76.8 tok/s through the API, matching the bench) now overlaps the next step's encoding and GPU time instead of sitting between steps. A stop answer takes effect one step or round later; that work is computed and never published, and its flag reaches the peer in the next submitted sum as before. Other runtimes publish and wait as before (the protocol's default implementation). +Rank 0 hands each committed token to its owner and reads the owner's answer late (`ClusterCommittedTokenChannel`, `WorkerRuntime.start(_:tokens:)`): it publishes the token at once, and reads the answer after the next step or round was submitted, before it publishes the next token. The protocol's token credit is unchanged (`ClusterWorkerSession` still refuses a token before the answer to the one before, and anything after a stop), but the answer's round trip through the owner (pipes, the provider's token callback and detokenizer; about 0.7 ms a token measured at the endpoint; greedy decode went from 73.5 to 76.8 tok/s through the API, matching the bench) now overlaps the next step's encoding and GPU time instead of sitting between steps. A stop answer takes effect one step or round later; that work is computed and never published, and its flag reaches the peer in the next submitted sum as before. A rank that stopped commits nothing more, but still ends at a stop token its peer commits, so both ranks leave after the same round or step: in MTP rounds, and in the one-token steps a build without the NextN layer runs (`GLM5NextTensorParallelStepLoop`, `ClusterGLMTensorParallel.speculativeDepth` 0). Rank 0's count and finish then cross in one small agreement, and rank 1 adopts them unless it stopped on its own (`QwenTensorParallelStopRule.reconcile`). Other runtimes publish and wait as before (the protocol's default implementation). GLM's decode and prefill kernels changed only in ways that keep every output bit for bit (they serve one Mac and the cluster alike). Decode: each hyper-connection site is one launch whose last threadgroup finishes the Sinkhorn and collapse (`GLM5NextHyperConnectionNormFusion`, `SplitForm.oneLaunch`); the MoE decode router spreads each expert row over 8 SIMD groups and replays top-K with `simd_max`/`simd_min` in the same order (`GLM5NextMoEDecodeKernel`); DSA decode uses smaller, more numerous threadgroups, a 1,024-thread top-k and a two-launch cache append that writes fresh buffers (`GLM5NextSparseDecodeKernel`, `GLM5NextTextCache`); per-call constants are cached and dead KDA nodes are no longer built. Prefill: the MoE gathers decode a packed NVFP4 word at a time (`GLM5NextMoEPrefillKernel`) and DSA's absorbed queries run beside the first index-score block. A prefill hyper-connection site that folds the previous expand (89 of a forward's 90) computes each expanded value inside the mix fragment that multiplies it and stores it there, so the expand's memory traffic overlaps the matrix products and no barrier precedes the mix, and its rows' collapses share one barrier (`GLM5NextHyperConnectionKernel.fusedExpandPrefillSource`; `GLM53_HC_FUSED_EXPAND=0` keeps the two-pass site): every per-element expression and sum order is the two-pass kernel's, 0.61 -> 0.56 ms a site at 4,096 rows on one M5 Ultra rank, about 5 ms per 4,096 prompt tokens per rank. Host: MLX shares generated kernel sources, resolves pipelines once and binds repeat launches without rebuilding names or keys. Core's fused fence update and fenced custom-kernel inputs (`MLX_METAL_FUSED_FENCE_UPDATE`, `MLX_METAL_FENCED_INPUTS`) are off by default; a GLM tensor-parallel rank turns the fenced inputs on (`WorkerFenceFusion`) and leaves the fused fence update to its launcher. Measured on two M5 Ultra (sealed TP2, MTP depth 2): plain decode 14.45 -> 12.43 ms a step, an MTP round 27.8 -> 23.9 ms, 15.7K-token prefill 3,819 -> 3,917 tok/s, tokens and top logits identical. Changes that only reorder sums were measured with a teacher-forced full-model perplexity bench and rejected (KDA paired order, DSA absorbed product on the tensor units, the tensor-unit prefill router, INT8 activations: +0.4 to +5.6 % perplexity, about 79 % top-1 agreement against a 99.4 % noise floor of the product's own chunking). @@ -4509,18 +4595,32 @@ synchronizes before dropping request caches on completion or failure. Copies share immutable old pages; a later write replaces the affected page handle. Sliding histories release old pages when they repack or enter the fixed ring. +Sliding pages also keep the ring's wrapped flag: a one-token write that rotates +sets it, and a chunk or trim clears it. Their `metaState` is the seven values the +pinned SDK writes for `RotatingKVCache(maxSize: window)` in the same state: keep, +window, step, offset, write index, capacity origin and wrapped flag +(`GPTOSSSlidingRing`). Restoring accepts only that layout for the cache's window, +and only with the rows that ring holds: its first `index` rows, or the whole +window once wrapped. It refuses the five-value legacy layout, a rewind reserve, a +kept prefix, and any other step, window or capacity origin. It also refuses an +unwrapped ring that has evicted rows but holds fewer than `window - 1`, which the +SDK's `trim` after eviction can leave: pages cap masks and trims by the offset, +the SDK by the rows it holds. GPT-OSS serving never reads or restores this +metadata. + `GPTOSSRequestStateBudget` keeps the existing full-request admission scope and never lowers its previous contiguous allowance. It also charges each page's allocator bound separately, the gathered attention view, and partial-page copies; sliding repacking includes old and new page versions. Physical allocation is demand-grown even though the request is admitted conservatively for its whole declared scope. LOAD and live-memory gates remain authoritative. -CPU parity against the actual SDK caches covers ring/page/chunk boundaries and -sinks. Real two-Mac numerical acceptance, resource release and performance -remain separate qualification gates. +CPU parity against the actual SDK caches covers ring/page/chunk boundaries, +metadata, restores and sinks. Real two-Mac numerical acceptance, resource release +and performance remain separate qualification gates. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift` -(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, +(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift` +(`GPTOSSSlidingRing`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift`, and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Resident/GPTOSSResidentAdmission.swift` (`loadAgreementFingerprint`). See [focused cache checks](../developer/test.md#gpt-oss-cluster-paged-kv-checks). @@ -4853,6 +4953,32 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Reside and `MiMoV26IndependentHistoryCache.swift`. See [MiMo independent-history checks](../developer/test.md#mimo-independent-history-batch-checks). +### MiMo contiguous ring metadata + +Only image-candidate loads keep MiMo's ordinary caches: `KVCacheSimple` for +full attention and `RotatingKVCache(maxSize: window)` for each sliding window. +The four text modes use pages with cluster prefix reuse off +([independent histories](#mimo-plain-pipeline-independent-histories)), so only +image candidates take cluster prompt-prefix snapshots. `MiMoPhaseSplitState` +also handles ordinary caches, but no load reaches that branch: image candidates +refuse phase split (`MiMoResidentRuntime.load`). The pinned SDK writes a ring's +`metaState` as seven values: keep, window, step, offset, write index, capacity +origin and wrapped flag. A rewind reserve adds an eighth. + +| Path | What it writes or accepts | +|---|---| +| Model ring check (`MiMoSlidingRing.isModelRing`) | Only the model's own ring: every value except offset, write index and wrapped flag equals a fresh ring's | +| Prefix capture and restore (`MiMoStagePrefixSnapshot`) | Restores a tail at the frontier's offset and write index, not wrapped | +| Phase split (`MiMoPhaseSplitState`) | Replays the frame grid for the write index and wrapped flag; exports or adopts a ring only when its whole metadata matches | +| Verify-window rollback (`MiMoWindowRollback`) | Cuts a multi-token window's rows and rewrites only offset and write index; that window left the wrapped flag false | +| Page histories (`MiMoPhaseSplitState.pagedMetadata`) | Keep their own five values | + +The snapshot and the phase split refuse a kept prefix, another step or origin, +a rewind reserve or another layout. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoSlidingRing.swift`, +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoPhaseSplit.swift`, +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Prefix/MiMoStagePrefixSnapshot.swift` +and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoWindowRollback.swift`. + ### Gemma paged prefix restoration Installed plain Gemma pipelines retain the paged KV default at every supported @@ -4891,6 +5017,17 @@ replace full-artifact qualification. Preserve earlier solo/pair reports and failed records; remeasure the candidate with the original comparator and qualification schedules. See [the test guide](../developer/test.md). +## GPT-OSS decode command buffers + +GPT-OSS's plain decode steps (every row one token) commit a Metal command buffer +every 100 operations with no input-size bound (`GPTOSSDecodeCommandBuffers`, +through `CBv2DecodeCommandBufferLimitsProviding`). MLX's defaults commit every 40 +to 50 operations or 40 to 50 M distinct input elements, and a step's inputs include +the expert banks and each 64 MiB KV segment its history reads, so decode committed +after almost every MoE layer and waited on MLX's limit of ten command buffers in +flight. Results do not depend on the partitioning. Prefill chunks keep MLX's +defaults. + ## Nemotron prefix chunk arithmetic The registered Nemotron 3.5 Lightning stage preserves the original global @@ -5169,6 +5306,20 @@ acknowledgement. Failed release retains the reservation for cleanup or the worker's process fence. Every row's singleton and batch owners publish raw selection logprobs through the committed-token channel. +Selection checks finiteness inside its own sealed sum, as the assistant's greedy +choice does (`QwenTensorParallelNativeBatchExecutor.select`): each rank adds its +rows' non-finite logit counts beside their maximum and first global index (a +sampled cohort counts the gathered rows), and both ranks read them from the +same evaluation that yields the tokens. A non-finite logit on either rank fails +both ranks before any token is chosen, a sampler advances or anything is +published, so neither rank waits in a collective its peer never enters. The +load agreement binds this selection sum +(`qwen-tensor-parallel-selection-nonfinite-in-sum-v1`): a rank whose selection +sums other words refuses to load beside it rather than meet it in a sum of +another length. The decode step pays no separate finiteness read +(`QwenTensorParallelBatchSession.validateLogits` checks shape and dtype), and +every selected token is unchanged. + 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 @@ -5179,8 +5330,54 @@ the 27B, whose features keep it in tensor parallel, and an assistant quote bind placement to tensor parallel as before. Synthetic CPU and both-chip native fixtures are not full-artifact, RDMA, tower, throughput or endpoint evidence. +Each rank logs its decode routes once per loaded model when its native +executor first starts serving (`darkbloom-qwen-tp-decode-census-v1`, +`QwenTensorParallelBatchSession.censusLine`): every projection's route (the +batch-invariant kernel `aqv`, a row-parallel FP32 partial on it `partial`, or +MLX's own kernels with the reason, `mlx-...`) and each projection shape's +layout per vector count (plain rows of one to eight and their four-column +windows), the residual-norm form, the paged attention geometry and partition +size, the selection, and any arithmetic switch the launcher set. A registered +27B rank reports `mlx=0`. Only host values are read; nothing is evaluated. +Layouts are listed per checkpoint projection: the SDK multiplies a Gated +DeltaNet layer's four input projections as one call of their summed rows, and +fuses gate, up and SwiGLU at `swiglu_fused_vectors` only while its decode +fusions are on. A routed-expert row's switch projections are not listed. + +`QwenTensorParallelRowsCheck` checks the row contract at the registered 27B +per-rank widths (three Gated DeltaNet layers and one attention layer; the +whole 248,320-row vocabulary) with random weights that follow the registered +artifact's value statistics: MLX's affine 4-bit quantization of near-normal +weights (group 64, signed BF16 scales of 0.001 to 0.005, biases -8 times the +scale, codes about 8), its norm, convolution, `A_log` and `dt_bias` ranges, +and gate rows whose SwiGLU inputs reach its range (about ±30). A row's logits +and history equal its run alone, on a one- or an eight-lane host, beside rows +of 100 to 4,600 tokens that join and leave, across two KV segments, while an +assistant observes the cohort, and at every position of a four-column verify +window alone and in a cohort. Both ranks run it in one process +(`QwenTensorParallelRealGeometryRowsTests`, `QWEN_TP_REAL_GEOMETRY_GPU=1`) or +as two processes over the loopback ring (`darkbloom-cluster-tp-check +qwen-rows`, native or sealed sums, with the worker's arithmetic environment). +It refuses to report when a logit is not finite, when its reference logits are +not all distinct, when the long rows fit one KV segment, or when its comparison +misses a planted difference. `qwen-rows run` also loads a registered +checkpoint directory on a Mac with the memory for it, reading the files +directly as `tp-check run` does, not through the product's verified load +(`QwenTensorParallelVerifiedLoad`: no artifact hashes, inventory or load memory +gate). `qwen-rows layers` names the first decoder layer where a row's step +beside another leaves its solo bits +(`QwenTensorParallelRowsCheck.firstDifferingLayers`, through +`Qwen35LayerSubmission.observer`). On an M5 Ultra every comparison is bitwise +equal, with the fixture and with the registered checkpoint. It covers neither +JACCL's streamed sealed sums, the driver under live traffic nor the HTTP +stream. + Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift` -(`QwenTensorParallelBatchSession`), +(`QwenTensorParallelBatchSession`, `censusLine`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift` +(`QwenTensorParallelRowsCheck`), +`libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift` +(`QwenRowsCheck`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift` (`serve`, `makePlan`, `join`, `leave`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Batch/QwenBatchDecodeCoalescing.swift` @@ -5213,17 +5410,21 @@ and verify transients. The shared charge is never below LOAD's. Each rank's live gate (`reserveLane`, with the same OS and allocator checks) admits the whole charge or refuses that request alone. The endpoint then answers 503 with the context the pair serves now, and the pair keeps serving. A request within the -memory plan is charged as before and must still fit LOAD's per-lane quote. +memory plan, at most its context and its prompt, must still fit LOAD's per-lane +quote. A longer prompt within that context is charged at its own prompt, as a +longer context is, because each request's prefix capture grows with its prompt +(`QwenTensorParallelRequestCharge.withinMemoryPlan`). READY's request capacity is the larger of LOAD's quote and one request at 262,144 tokens. READY, and every keep-warm answer while no lane is held, carry the longest context the reservation gate admits now (`servingContextTokens`, computed with the gate's own arithmetic). The pair refuses a longer request before either rank is asked. With the registered inventory on an M5 Ultra -(256 GB), eight lanes with the depth-3 assistant reserve 48.4 GB a rank at LOAD -(4.6 GB a lane). A 262,144-token request beside seven standard ones is charged -69.4 GB a rank (a 13.9 GB lane and 22.8 GB of shared workspaces), beside at most -16.3 GB of weights (`QwenTensorParallelNativeContextTests`). +(256 GB), eight lanes with the depth-3 assistant reserve 60.4 GB a rank at LOAD +(6.2 GB a lane). A 262,144-token request beside seven standard ones is charged +89.0 GB a rank (a 23.1 GB lane, including its own prompt's prefix capture, and +22.4 GB of shared workspaces), beside at most 16.3 GB of weights +(`QwenTensorParallelNativeContextTests`). The pipeline and hand-off modes stay at the memory plan. Their LOAD gates size it, and they refuse a longer reservation (`requireWithinMemoryProfile`). Provider @@ -5263,6 +5464,25 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Ten `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2OwnedRequestState.swift` (`growReservation`). +### Qwen27 tensor-parallel prompt-prefix depth + +A plain Qwen tensor-parallel lane keeps prompt-prefix boundaries to its request's +context on its own 512-token chunk grid, not to a fixed 4,096 tokens: the +deepest whole chunk before the final token, a boundary 64 tokens before the +prompt end for the next turn, and one Mac's 4,096-token stripe boundaries for +a shared system prompt (`QwenTensorParallelBatchPrefixBudget`, policy +`qwen-tp-batch-prefix-depth-v2`, which the load agreement binds). A repeated +33K-token prompt restores 32,768 tokens on both ranks, as one Mac reuses. A +request restored from memory or a native SSD record computes exactly what a +cold one computes on the same grid; the SSD tier's default `balanced` records +keep their older rows approximate. +The mechanism, the parity cases and the SSD records are in +[the Qwen27 TP prefixes](prefix-cache.md#qwen27-tp-prefix-ssd-tier) and the +section before it; the memory each request and LOAD charge is in +[Qwen27 TP batch prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership). +The assistant's lanes keep one boundary of at most 4,096 tokens +([assistant prefix ownership](prefix-cache.md#qwen27-tp-assistant-prefix-ownership)). + ### Qwen27 cluster media ingress ownership The scheduler routes image/video requests through `DistributedQwenMediaIngress` From ebcab3dda90247ff5aba1da7891dc0d2e292d2ea Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 23:26:32 -0800 Subject: [PATCH 54/58] docs: align merge preimage headers with dev Resolve only the date-header merge conflict; preserve both documentation bodies. The latest authored date is restored immediately after the signed dev merge. No runtime source change. AI-assisted integration by Darkbloom Provider (Hermes). --- docs/architecture/hardware-support.md | 2 +- docs/architecture/inference.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 4da0ba050d..8b28d8d119 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-02 +> Last updated: 2026-11-01 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 diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 8273852658..9fee7d6546 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-02 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` From df5d76b05b4f554ee377044cd225b2182b2847f3 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 23:27:16 -0800 Subject: [PATCH 55/58] docs: retain authored pipeline verification dates Restore the authored 2026-11-02 dates after the non-force dev refresh. The final tree equals the locally checked two-parent merge with only the date conflicts resolved; both documentation bodies are preserved. No additional runtime edits. AI-assisted integration by Darkbloom Provider (Hermes). --- docs/architecture/hardware-support.md | 2 +- docs/architecture/inference.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 8b28d8d119..4da0ba050d 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 diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 9fee7d6546..8273852658 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-02 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` From c1ed803dcb10c4758e89462c21aa4373dc5ccd6d Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:44:34 -0600 Subject: [PATCH 56/58] Pin libs/mlx-swift-lm to SDK main 2311af6e SDK main 2311af6e contains SDK #383 (ad856be1, the pin this branch had) and the other 0.10.7 SDK merges (#370, #371, #377, #382, #384, #375, #376). Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index ad856be115..2311af6e67 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit ad856be1151d20c28a354eda81ce71ba68044d79 +Subproject commit 2311af6e67c2d79b6b7b59504978af67fe6857e0 From f5417945ed8c3746ec60f4079386b193ab5bdea9 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:46:54 -0600 Subject: [PATCH 57/58] docs: the saved Qwen TP widths after the per-lane prefix capture The width table, the eight-lane byte figures and the changelog were computed before #1720 charged each lane's prompt-prefix capture in the LOAD quote. The merged head's ClusterPlacementTensorWidthRegisteredTests prints the new figures: a rank of an equal split reserves 40,544,616,448 bytes at eight lanes without the assistant (was 28,555,198,464) and 60,367,765,504 with it (was 48,378,347,520). Idle pairs now save 2/2/4/8/8 without the assistant and 1/1/2/4/8 with it at 32/36/48/64/96+ GiB a Mac. The sizing code is unchanged; it reads the live quotes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-default-lanes.md | 6 +++--- docs/architecture/inference.md | 18 ++++++++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/changelog.d/qwen27-tp-default-lanes.md b/changelog.d/qwen27-tp-default-lanes.md index 14f85a899c..beaec56878 100644 --- a/changelog.d/qwen27-tp-default-lanes.md +++ b/changelog.d/qwen27-tp-default-lanes.md @@ -6,9 +6,9 @@ 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 48 GB a Mac without the - speculative assistant (4 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 +- 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 diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 38339256ec..684ada8cf1 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` @@ -5361,15 +5361,17 @@ the served layout; `ClusterPlacementTensorWidthRegisteredTests`): | Each Mac | Without the assistant (served through Darkbloom) | With the depth-3 assistant (local) | |---|---|---| -| 32 GiB | 4 | 1 | -| 36 GiB | 4 | 2 | -| 48 GiB | 8 | 4 | -| 64 GiB | 8 | 6 | +| 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 28,555,198,464 bytes at -LOAD without the assistant and 48,378,347,520 bytes with it; with its weights -and loading headroom it needs 42,084,887,040 and 65,642,146,304 bytes. Every +At eight lanes, each rank of an equal split reserves 40,544,616,448 bytes at +LOAD without the assistant and 60,367,765,504 bytes with it, each lane's +prompt-prefix capture included ([prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership)); +with its weights and loading headroom it needs 54,074,305,024 and +77,631,564,288 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. From 39d8f0ccf9321e232e6b9fe6547580931bfe2468 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:17:41 -0600 Subject: [PATCH 58/58] docs: Qwen TP saved-width byte figures include the prompt wavefront term #1724 measured the 8-lane LOAD figures before #1725 added the shared 367,001,600-byte merged-step term to every Qwen TP batch quote. With both merged, ClusterPlacementTensorWidthRegisteredTests prints 40,911,618,048 / 60,734,767,104 bytes reserved per rank and 54,441,306,624 / 77,998,565,888 bytes needed (composition CI run 41631482989). The width table is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 77f7584b4d..bf47946298 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5625,11 +5625,13 @@ the served layout; `ClusterPlacementTensorWidthRegisteredTests`): | 64 GiB | 8 | 4 | | 96 GiB and larger | 8 | 8 | -At eight lanes, each rank of an equal split reserves 40,544,616,448 bytes at -LOAD without the assistant and 60,367,765,504 bytes with it, each lane's -prompt-prefix capture included ([prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership)); -with its weights and loading headroom it needs 54,074,305,024 and -77,631,564,288 bytes. Every +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.