From 1024fa6c2b6a2b2c3055c775914ad00dc1947bcd Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Thu, 12 Nov 2026 20:51:18 -0800
Subject: [PATCH 01/14] test(provider): exit-thinking for Qwen 3.5/3.6's
`` (red)
Since 0.10.12 the loop guard ends a repeating thought as `length` with no
answer for every guarded family. #2040 lets Gemma 4 answer instead; this
extends it to Qwen 3.5 and 3.6 (`qwen3_5`, `qwen3_5_moe`). Production, the
last 12 h on 0.10.12, GPQA-shaped requests: 15.6-29.5 per 1,000 end
guard-stopped with no answer (Qwen 3.6 35B 25.6, Qwen 3.5 35B 15.6, Qwen 3.5
9B 29.5), as often as Gemma's 20.2. Qwen 3.8 (`qwen4_exp`) is 1.4 per 1,000,
so it stays out.
Red tests and the API they need, with no behaviour yet:
- Qwen's exit is the close as its template writes it, `\n\n\n`, with
`` as its own token: [10, 248069, 10, 10] with the repo's Qwen
byte tokenizer. The served prompt opens the thought (`\n`), so the
row starts inside it. Qwen 3.8 has none; the env list still turns
Qwen's off and keeps Gemma's.
- A repeating Qwen thought asks to end the thought; a loop after
`` does not.
- The splice: with a multi-token exit, only the close marker's own token
in flight means the row closed its thought itself (newlines do not).
- Served end to end (scheduler, bridge, a scripted engine): the
continuation is the prompt, the row's tokens and the four exit tokens;
the answer follows `\n\n`; and the continuation's stop strings
apply from its first token (its scope starts outside the thought, where
the row's started inside).
- GenerationLoopExitThinking.closeToken and Markers.before/after.
Co-Authored-By: Claude Opus 5.5
---
.../GenerationLoopExitThinking.swift | 25 +++-
.../LoopExitThinkingContinuationTests.swift | 37 ++++++
...nerationLoopExitThinkingServingTests.swift | 115 ++++++++++++++----
.../GenerationLoopExitThinkingTests.swift | 61 +++++++++-
4 files changed, 209 insertions(+), 29 deletions(-)
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
index c49856b7c5..8cdc89e3ca 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
@@ -16,10 +16,14 @@ public struct GenerationLoopExitThinking: Sendable {
let openMarker: String
/// Text that closes it.
let closeMarker: String
- /// The tokens appended to end the thought: the close marker's token.
+ /// The tokens appended to end the thought: the family's closing text, with
+ /// the close marker as its own special token.
let exitTokens: [Int]
/// Their text, as the client's stream shows them.
let exitText: String
+ /// The close marker's own token. A row that produced it after the stop
+ /// closed its thought itself.
+ let closeToken: Int
/// The prompt itself left the reasoning channel open.
let startsInside: Bool
/// Shared with the continuation: the row's tokens and the guard's request.
@@ -28,6 +32,21 @@ public struct GenerationLoopExitThinking: Sendable {
/// budget: a model that wrote a loop may write a near-verbatim one next,
/// which the guard does not see.
var answerTokenLimit = GenerationLoopExitThinkingPolicy.answerTokenLimit
+
+ init(
+ openMarker: String, closeMarker: String, exitTokens: [Int], exitText: String, closeToken: Int? = nil,
+ startsInside: Bool, record: GenerationLoopExitRecord,
+ answerTokenLimit: Int = GenerationLoopExitThinkingPolicy.answerTokenLimit
+ ) {
+ self.openMarker = openMarker
+ self.closeMarker = closeMarker
+ self.exitTokens = exitTokens
+ self.exitText = exitText
+ self.closeToken = closeToken ?? exitTokens.first ?? -1
+ self.startsInside = startsInside
+ self.record = record
+ self.answerTokenLimit = answerTokenLimit
+ }
}
/// One request's generated tokens and whether its loop guard asked to end
@@ -70,6 +89,10 @@ enum GenerationLoopExitThinkingPolicy {
struct Markers: Sendable, Equatable {
let open: String
let close: String
+ /// What the family's template writes around the close marker when the
+ /// model ends its own thought (Qwen: `\n\n\n`).
+ var before = ""
+ var after = ""
}
/// The families whose thought this can end, by `model_type`.
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
index 8d239293e9..fd71696607 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
@@ -160,6 +160,43 @@ struct LoopExitThinkingContinuationTests {
#expect(calls.submits.isEmpty)
}
+ @Test("a multi-token exit (Qwen's `\\n\\n\\n`): only the close marker in flight means the row closed its thought")
+ func multiTokenExit() async throws {
+ let exitTokens = [10, 248_069, 10, 10]
+ func qwenExit(_ tokens: [Int]) -> GenerationLoopExitThinking {
+ let record = GenerationLoopExitRecord()
+ record.append(tokens)
+ record.requestExit(.init(period: 19, span: 2_048, generatedTokens: 4_096))
+ return GenerationLoopExitThinking(
+ openMarker: "", closeMarker: "", exitTokens: exitTokens, exitText: "\n\n\n",
+ closeToken: 248_069, startsInside: true, record: record)
+ }
+ // Newlines in flight after the stop are still the thought.
+ let calls = Calls()
+ let tokens = Array(repeating: 900, count: 4_096) + [10, 10, 900]
+ let out = await drain(splice(
+ first: stream([.info(promptTokens: 5, completionTokens: 4_099, tokensPerSecond: 10, finishReason: "length")]),
+ exit: qwenExit(tokens), calls: calls
+ ) {
+ self.stream([.chunk("B"), .info(promptTokens: 4_108, completionTokens: 1, tokensPerSecond: 20,
+ finishReason: "stop")])
+ }.events)
+ #expect(out == ["chunk:\n\n\n", "chunk:B", "info:5/4104/stop"])
+ let submit = try #require(calls.submits.first)
+ #expect(submit.prompt == Self.prompt + tokens + exitTokens)
+ #expect(submit.maxTokens == 8_192 - 4_099 - 4)
+
+ // `` in flight: the row closed its thought itself.
+ let closed = Calls()
+ let closing = Array(repeating: 900, count: 4_096) + [10, 248_069, 10, 10, 65]
+ let kept = await drain(splice(
+ first: stream([.info(promptTokens: 5, completionTokens: 4_101, tokensPerSecond: 10, finishReason: "length")]),
+ exit: qwenExit(closing), calls: closed
+ ) { self.stream([.chunk("never")]) }.events)
+ #expect(kept == ["info:5/4101/length"])
+ #expect(closed.submits.isEmpty)
+ }
+
@Test("no output budget left: nothing is submitted")
func noBudget() async {
let calls = Calls()
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
index f3bc093458..2cb082afc0 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
@@ -7,11 +7,26 @@ import Testing
@testable import ProviderCore
-/// A Gemma 4 row that repeats one clause verbatim, inside its thought or in
-/// its answer, one token per delta; the guard's cancel ends it `.cancelled`
-/// (a row nobody cancels ends `.length` after a short wait). Any later
-/// submission is the continuation: it answers "Answer: B" and stops.
+/// A row that repeats one clause verbatim, inside its thought or in its
+/// answer, one token per delta; the guard's cancel ends it `.cancelled` (a row
+/// nobody cancels ends `.length` after a short wait). Any later submission is
+/// the continuation: it answers "Answer: B" and stops.
private final class ThoughtLoopCBv2Engine: CBv2Engine, @unchecked Sendable {
+ /// How one family's row spells its text, opens its thought (when the
+ /// prompt has not) and closes it.
+ struct Family: Sendable {
+ let tokens: @Sendable (String) -> [Int]
+ let opening: [String]
+ let closing: [String]
+
+ static let gemma = Family(
+ tokens: { GemmaThoughtTestTokenizer.tokens($0) }, opening: ["<|channel>", "thought\n"],
+ closing: ["ok", ""])
+ /// The served Qwen 3.5/3.6 template opens the thought in the prompt.
+ static let qwen = Family(
+ tokens: { QwenByteTestTokenizer.tokens($0) }, opening: [], closing: ["ok\n", "", "\n\n"])
+ }
+
private let lock = NSLock()
private var continuations: [AsyncStream.Continuation] = []
private var submitted: [CBv2Request] = []
@@ -19,10 +34,12 @@ private final class ThoughtLoopCBv2Engine: CBv2Engine, @unchecked Sendable {
private var cancels = 0
let loopInsideThought: Bool
let loopTokens: Int
+ let family: Family
- init(loopInsideThought: Bool, loopTokens: Int = 4_200) {
+ init(loopInsideThought: Bool, loopTokens: Int = 4_200, family: Family = .gemma) {
self.loopInsideThought = loopInsideThought
self.loopTokens = loopTokens
+ self.family = family
}
var requests: [CBv2Request] { lock.withLock { submitted } }
@@ -38,17 +55,13 @@ private final class ThoughtLoopCBv2Engine: CBv2Engine, @unchecked Sendable {
return submitted.count - 1
}
func emit(_ text: String) {
- let tokens = GemmaThoughtTestTokenizer.tokens(text)
+ let tokens = family.tokens(text)
lock.withLock { produced[index] += tokens }
continuation.yield(.delta(text: text, tokens: tokens, logprobs: nil))
}
if index == 0 {
- emit("<|channel>")
- emit("thought\n")
- if !loopInsideThought {
- emit("ok")
- emit("")
- }
+ family.opening.forEach(emit)
+ if !loopInsideThought { family.closing.forEach(emit) }
let clause = Array("Wait, the carbon count is 19. ")
for position in 0.. = [GemmaThoughtTestTokenizer.turnClose, GemmaThoughtTestTokenizer.eos]
+ var parser = ReasoningParserFormat.gemma4
+ }
+
+ /// Qwen 3.5 with thinking on: the prompt ends `\n`.
+ private static let qwen = Served(
+ modelID: "EigenLabs/Qwen3.5-9B-MLX-4bit-mtp", modelType: "qwen3_5",
+ tokenizer: TokenizerHandle(QwenByteTestTokenizer()), eosTokenIds: [248_046, 248_044], parser: .qwen3)
+
private struct Outcome {
var content = ""
var reasoning = ""
@@ -222,30 +249,30 @@ struct GenerationLoopExitThinkingServingTests {
}
private func serve(
- _ engine: ThoughtLoopCBv2Engine, modelType: String = "gemma4", maxTokens: Int = 8_192
+ _ engine: ThoughtLoopCBv2Engine, served: Served = Served(), maxTokens: Int = 8_192
) async throws -> Outcome {
let telemetry = TelemetrySink()
- let bridge = EngineV2Bridge(engine: engine, modelId: modelID, tokenizer: Self.tokenizer,
- eosTokenIds: [GemmaThoughtTestTokenizer.turnClose, GemmaThoughtTestTokenizer.eos], defaultMaxTokens: 64,
+ let bridge = EngineV2Bridge(engine: engine, modelId: served.modelID, tokenizer: served.tokenizer,
+ eosTokenIds: served.eosTokenIds, defaultMaxTokens: 64,
maxConcurrentRequests: 1, emitTelemetry: { telemetry.add($0) })
- let id = modelID
- let tokenizer = Self.tokenizer
let scheduler = MultiModelBatchSchedulerEngine(registryProvider: {
- [id: .init(tokenizer: tokenizer, modelType: modelType, engineV2Bridge: bridge)]
+ [served.modelID: .init(tokenizer: served.tokenizer, modelType: served.modelType, engineV2Bridge: bridge)]
})
- var outcome = try await consume(scheduler, maxTokens: maxTokens)
+ var outcome = try await consume(scheduler, served: served, maxTokens: maxTokens)
await bridge.shutdown()
outcome.loopGuardStops = telemetry.loopGuardStops
return outcome
}
- private func consume(_ scheduler: MultiModelBatchSchedulerEngine, maxTokens: Int) async throws -> Outcome {
+ private func consume(
+ _ scheduler: MultiModelBatchSchedulerEngine, served: Served = Served(), maxTokens: Int
+ ) async throws -> Outcome {
let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: Data("""
- {"model":"\(modelID)","messages":[{"role":"user","content":"hi"}],"reasoning_parser":"gemma4",\
- "max_tokens":\(maxTokens)}
+ {"model":"\(served.modelID)","messages":[{"role":"user","content":"hi"}],\
+ "reasoning_parser":"\(served.parser.rawValue)","max_tokens":\(maxTokens)}
""".utf8))
var outcome = Outcome()
- var parser = StreamingReasoningParser(format: .gemma4)
+ var parser = StreamingReasoningParser(format: served.parser)
func apply(_ parsed: ParsedReasoning) {
outcome.content += parsed.content
outcome.reasoning += parsed.reasoningContent ?? ""
@@ -365,10 +392,50 @@ struct GenerationLoopExitThinkingServingTests {
#expect(outcome.content == "Answer: B")
}
+ @Test("Qwen 3.5: a loop inside the thought ends it with `\\n\\n\\n`, and stops apply to the answer")
+ func qwenThoughtLoopEndsInAnAnswer() async throws {
+ let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, family: .qwen)
+ let outcome = try await serve(engine, served: Self.qwen)
+ #expect(outcome.error == nil)
+ #expect(engine.cancelCount == 1)
+ let requests = engine.requests
+ #expect(requests.count == 2)
+ let first = try #require(requests.first)
+ let continuation = try #require(requests.last)
+ let firstOutput = try #require(engine.outputs.first)
+ // The row's tokens, then the close as Qwen's template writes it: the
+ // marker is its own special token.
+ #expect(continuation.promptTokens == first.promptTokens + firstOutput + [10, 248_069, 10, 10])
+ #expect(continuation.maxTokens == first.maxTokens - firstOutput.count - 4)
+ // The row's output starts inside the thought the prompt opened; the
+ // continuation's starts after ``, so stop strings apply to it.
+ #expect(first.stopStringScope
+ == CBv2StopStringScope(excluding: [ReasoningStopScope.think], startingInside: true))
+ #expect(continuation.stopStringScope
+ == CBv2StopStringScope(excluding: [ReasoningStopScope.think], startingInside: false))
+ #expect(outcome.reasoning.hasPrefix("Wait, the carbon count is 19."))
+ // As after a thought the model closes itself: the answer follows `\n\n`.
+ #expect(outcome.content == "\n\nAnswer: B")
+ #expect(outcome.info?.stopReason == "stop")
+ #expect(outcome.info?.completionTokens == firstOutput.count + 4 + 9)
+ #expect(outcome.loopGuardStops == [true])
+ }
+
+ @Test("Qwen 3.5: a loop in the answer, after ``, still ends as length")
+ func qwenAnswerLoopEndsAsLength() async throws {
+ let engine = ThoughtLoopCBv2Engine(loopInsideThought: false, family: .qwen)
+ let outcome = try await serve(engine, served: Self.qwen)
+ #expect(outcome.error == nil)
+ #expect(engine.requests.count == 1)
+ #expect(outcome.info?.stopReason == "length")
+ #expect(outcome.loopGuardStops == [false])
+ }
+
@Test("a family without the exit keeps today's length")
func otherFamilyKeepsLength() async throws {
let engine = ThoughtLoopCBv2Engine(loopInsideThought: true)
- let outcome = try await serve(engine, modelType: "qwen3_5")
+ // Qwen 3.8: its thought loops are rare in production, so it has no exit.
+ let outcome = try await serve(engine, served: Served(modelType: "qwen4_exp"))
#expect(engine.requests.count == 1)
#expect(outcome.info?.stopReason == "length")
#expect(outcome.loopGuardStops == [false])
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
index 6c499059a0..07f2f98c9c 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
@@ -177,7 +177,7 @@ struct GenerationLoopExitThinkingTests {
modelType: modelType, tokenizer: tokenizer, promptTokens: prompt, logprobs: logprobs, setting: setting)
}
- @Test("on by default for Gemma 4 only, with its close marker as the exit")
+ @Test("on by default for Gemma 4, with its close marker as the exit; not for families without a listed marker")
func defaultModelTypes() throws {
for modelType in ["gemma4", "gemma4_text", "GEMMA4"] {
let exit = try #require(resolve(modelType), "\(modelType)")
@@ -185,8 +185,7 @@ struct GenerationLoopExitThinkingTests {
#expect(exit.exitText == "")
#expect(!exit.startsInside)
}
- for modelType in ["qwen3_5", "qwen3_5_moe", "qwen4_exp", "gpt_oss", "nemotron_h", "glm5_next", "mimo_v2",
- "diffusion_gemma", "llama"] {
+ for modelType in ["qwen4_exp", "gpt_oss", "nemotron_h", "glm5_next", "mimo_v2", "diffusion_gemma", "llama"] {
#expect(resolve(modelType) == nil, "\(modelType)")
}
#expect(resolve(nil) == nil)
@@ -207,7 +206,7 @@ struct GenerationLoopExitThinkingTests {
#expect(resolve("gemma4", setting: listed) == nil)
#expect(resolve("gemma4_text", setting: listed) != nil)
// A listed family without a known marker stays off.
- #expect(resolve("qwen3_5", setting: listed) == nil)
+ #expect(resolve("llama", setting: .modelTypes(["llama"])) == nil)
}
@Test("never with logprobs, and never without the marker token")
@@ -228,6 +227,60 @@ struct GenerationLoopExitThinkingTests {
#expect(resolve("gemma4", prompt: Self.prompt)?.startsInside == false)
}
+ // MARK: The `` families
+
+ private static let qwen = QwenByteTestTokenizer()
+ private static let qwenThinking = QwenByteTestTokenizer.tokens(QwenByteTestTokenizer.prompt(thinking: true))
+
+ private func qwenExit(_ modelType: String = "qwen3_5_moe") -> GenerationLoopExitThinking? {
+ GenerationLoopExitThinkingPolicy.resolve(
+ modelType: modelType, tokenizer: Self.qwen, promptTokens: Self.qwenThinking, logprobs: false,
+ setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes))
+ }
+
+ @Test("Qwen 3.5/3.6 end the thought as their template does: `\\n\\n\\n`, the marker as its own token")
+ func qwenFamilies() throws {
+ for modelType in ["qwen3_5", "qwen3_5_moe"] {
+ let exit = try #require(qwenExit(modelType), "\(modelType)")
+ #expect(exit.exitText == "\n\n\n")
+ #expect(exit.exitTokens == [10, 248069, 10, 10])
+ #expect(exit.closeToken == 248069)
+ // The served template opens the thought in the prompt.
+ #expect(exit.startsInside)
+ }
+ let closed = QwenByteTestTokenizer.tokens(QwenByteTestTokenizer.prompt(thinking: false))
+ #expect(GenerationLoopExitThinkingPolicy.resolve(
+ modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: closed, logprobs: false,
+ setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes))?.startsInside == false)
+ // Qwen 3.8 (`qwen4_exp`) is not listed: its thought loops are rare in production.
+ #expect(qwenExit("qwen4_exp") == nil)
+ // The env list still turns Qwen's off and keeps Gemma's.
+ let gemmaOnly = GenerationLoopExitThinkingPolicy.setting(
+ environment: [GenerationLoopExitThinkingPolicy.environmentKey: "gemma4,gemma4_text"])
+ #expect(GenerationLoopExitThinkingPolicy.resolve(
+ modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: Self.qwenThinking, logprobs: false,
+ setting: gemmaOnly) == nil)
+ #expect(resolve("gemma4", setting: gemmaOnly) != nil)
+ }
+
+ @Test("a Qwen thought that loops asks to end the thought; a loop after `` does not")
+ func qwenGuard() throws {
+ var inThought = GenerationLoopGuard(
+ modelType: "qwen3_5_moe", toolCallMarkers: GenerationLoopGuardPolicy.genericToolCallMarkers,
+ exitThinking: try #require(qwenExit()))
+ let (thoughtStop, _) = run(clause(8_000), into: &inThought)
+ #expect(thoughtStop != nil)
+ #expect(inThought.endsThought)
+
+ var inAnswer = GenerationLoopGuard(
+ modelType: "qwen3_5_moe", toolCallMarkers: GenerationLoopGuardPolicy.genericToolCallMarkers,
+ exitThinking: try #require(qwenExit()))
+ let closing: [(String, [Int])] = [("ok\n", [111, 107, 10]), ("", [248069]), ("\n\n", [10, 10])]
+ let (answerStop, _) = run(closing + clause(8_000), into: &inAnswer)
+ #expect(answerStop != nil)
+ #expect(!inAnswer.endsThought)
+ }
+
@Test("darkbloom start passes the loop guard's and the exit's switches to the launchd daemon")
func launchdPassthrough() {
for key in [GenerationLoopExitThinkingPolicy.environmentKey, GenerationLoopGuardPolicy.environmentKey] {
From eac6e9f1412ae9d6c7a3f1efe1f5d14ae5b1706c Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Thu, 12 Nov 2026 20:56:19 -0800
Subject: [PATCH 02/14] feat(provider): a repeating Qwen 3.5/3.6 thought ends
in an answer
As #2040 does for Gemma 4: when the loop guard stops a verbatim loop inside
a Qwen 3.5 or 3.6 thought (`qwen3_5`, `qwen3_5_moe`), the request continues
with the thought closed and the model answers, instead of ending `length`
with no answer.
- The exit is the close as Qwen's template writes it, `\n\n\n`
(both served models' chat_template.jinja: '\n\n' + reasoning +
'\n\n\n' + content; generation prompt `\n`). `` is
an added token (248069, special: false); the text on each side is
tokenized on its own, as in the whole string (`Markers.before/after`;
[198, 248069, 271] with the real tokenizer).
- Only the close marker's own token in the row's in-flight tokens means the
row closed its thought itself (`closeToken`): with a multi-token exit a
newline would have.
- The continuation's stop strings are scoped from outside the thought
(`reasoningPrefix: nil`): the row's scope starts inside, as Qwen's prompt
opens ``, which would have kept a client's stop strings off for
the whole answer.
- Default list: gemma4, gemma4_text, qwen3_5, qwen3_5_moe. Not Qwen 3.8
(`qwen4_exp`): 1.4 per 1,000 GPQA-shaped requests end that way.
DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text keeps Gemma's alone.
- Docs (loop guard section) and a changelog fragment.
Co-Authored-By: Claude Opus 5.5
---
changelog.d/loop-guard-exit-thinking-qwen.md | 6 ++++
docs/architecture/inference.md | 36 +++++++++++--------
.../LoopExitThinkingContinuation.swift | 16 +++++----
.../MultiModelBatchSchedulerEngine.swift | 6 +++-
.../GenerationLoopExitThinking.swift | 26 ++++++++++----
5 files changed, 62 insertions(+), 28 deletions(-)
create mode 100644 changelog.d/loop-guard-exit-thinking-qwen.md
diff --git a/changelog.d/loop-guard-exit-thinking-qwen.md b/changelog.d/loop-guard-exit-thinking-qwen.md
new file mode 100644
index 0000000000..cc175d4edf
--- /dev/null
+++ b/changelog.d/loop-guard-exit-thinking-qwen.md
@@ -0,0 +1,6 @@
+### A Qwen 3.5 or 3.6 thought that repeats itself verbatim now ends in an answer
+
+- As for Gemma 4 in 0.10.13: when the loop guard stops a verbatim loop inside a Qwen 3.5 or 3.6 thought, the request no longer ends as `length` with no answer. The provider ends the thought as Qwen's template does (`\n\n\n`), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
+- Since 0.10.12, 1.6–3.0 % of GPQA-shaped Qwen 3.5/3.6 requests ended that way with no answer.
+- Qwen 3.5 and 3.6 (`qwen3_5`, `qwen3_5_moe`). Not Qwen 3.8, whose thought loops are rare. Never with logprobs or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text` keeps Gemma's alone; `0` turns both off.
+- Stop strings apply to the answer from its first token.
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index a88327753d..1bf16bc19e 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -3252,10 +3252,12 @@ stops such a row early.
(Super, text only), `glm5_next` and `mimo_v2`. `DARKBLOOM_LOOP_GUARD=0`
(or `off`) turns it off; a comma-separated list of `model_type`s replaces
the default list.
-- **A loop inside a Gemma 4 thought ends the thought, not the answer**
- (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`). For
- `gemma4` and `gemma4_text`, the guard also follows the thought channel
- (`<|channel>` … ``; the prompt's tail seeds the state) and records
+- **A loop inside a Gemma 4 or Qwen 3.5/3.6 thought ends the thought, not the
+ answer** (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`).
+ For `gemma4`, `gemma4_text`, `qwen3_5` and `qwen3_5_moe`, the guard also
+ follows the thought channel (`<|channel>` … ``, `` …
+ ``; the prompt's tail seeds the state: Qwen's served template opens
+ `` in the prompt) and records
every token the row produces, the in-flight ones after its stop included. A
detection inside the thought stops the row as above; the scheduler
(`prepareCompletion`) then holds the row's `length` terminal, waits until the
@@ -3264,24 +3266,30 @@ stops such a row early.
service charge; a row with a retirement handle, the coordinator's atomic
admission path, ends its stream before that; at most 5 s), and submits one
continuation on the same bridge: the prompt, every generated
- token and ``, with `max_tokens` = the output the bridge resolved
- for the row minus the tokens produced minus 1, at most 8,192; the same
- sampling, stop strings and cache scope; and a loop guard without the exit, so
- a loop in the answer still ends as `length`. The client's stream carries the
- thought, a `` chunk and the answer, then one terminal: the original
- prompt, completion = the row's tokens + 1 + the answer's, the continuation's
- finish reason. The continuation is an ordinary row, so exact MTP drafting
+ token and the family's end of thinking (the exit tokens: Gemma's
+ ``; Qwen's `\n\n\n`, as its template closes a thought, with
+ `` as its own token and the newlines tokenized on each side), with
+ `max_tokens` = the output the bridge resolved for the row minus the tokens
+ produced minus the exit tokens, at most 8,192; the same sampling, stop strings
+ and cache scope, the stop strings scoped as for output that starts outside the
+ thought; and a loop guard without the exit, so a loop in the answer still ends
+ as `length`. The client's stream carries the thought, the exit text as one
+ chunk and the answer, then one terminal: the original prompt, completion =
+ the row's tokens + the exit tokens + the answer's, the continuation's finish
+ reason. The continuation is an ordinary row, so exact MTP drafting
stays on for it and its batch; a cancelled row donates no KV, so the
continuation prefills the thought again (its prompt part can hit the prefix
cache). When the continuation cannot start (under 256 tokens of budget left,
- the row closed its thought itself, the row did not release its slot in time,
+ the row closed its thought itself (its in-flight tokens after the stop hold
+ the close marker's token), the row did not release its slot in time,
a refused submission, a failure before its first token, a cancel), the held
`length` terminal is
delivered as before; a failure after its first token ends the answer there,
as `length` (only the client's cancel keeps its error). Never with
- logprobs or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=0` (or `off`)
+ logprobs or on a cluster pair. Not for Qwen 3.8 (`qwen4_exp`), whose
+ thought loops are rare. `DARKBLOOM_LOOP_EXIT_THINKING=0` (or `off`)
turns it off; a comma-separated list keeps it to the listed `model_type`s
- that have a marker. `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
+ that have a marker (`gemma4,gemma4_text` keeps Gemma's alone). `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
to the launchd daemon (`LaunchAgent.inferencePassthroughEnvKeys`). One `darkbloom.loop-guard.exit-thinking` line per ended
thought gives the outcome.
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
index 3dcd68dcdb..4cfe1d6837 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
@@ -12,11 +12,12 @@ import Logging
/// for the row's stream to finish, and submits one continuation (its `submit`
/// first waits for the row to release its serving slot:
/// `EngineV2Bridge.waitForRowRelease`): the same prompt, every token the row
-/// produced, then the family's end-of-thinking marker, with the output budget
-/// the row left (at most `GenerationLoopExitThinking.answerTokenLimit`). The
-/// client sees one answer: the thought, the marker, then the continuation's
-/// text, and one terminal whose usage is the original prompt and every token
-/// produced (the row's, the marker, the continuation's).
+/// produced, then the family's end of thinking (`GenerationLoopExitThinking.exitTokens`),
+/// with the output budget the row left (at most
+/// `GenerationLoopExitThinking.answerTokenLimit`). The client sees one answer:
+/// the thought, the exit text, then the continuation's text, and one terminal
+/// whose usage is the original prompt and every token produced (the row's, the
+/// exit's, the continuation's).
///
/// Anything that keeps the continuation from starting (under
/// `minimumAnswerBudget` tokens of budget left, a row that closed its thought
@@ -126,9 +127,10 @@ enum LoopExitThinkingContinuation {
}
let generated = exit.record.generatedTokens
// A row that closed its thought itself, in the tokens it produced
- // after the stop, has no thought left to end.
+ // after the stop, has no thought left to end. Only the marker's own
+ // token says so: the text around it (Qwen's newlines) is any text.
if let detection = exit.record.requested,
- generated.dropFirst(detection.generatedTokens).contains(where: exit.exitTokens.contains) {
+ generated.dropFirst(detection.generatedTokens).contains(exit.closeToken) {
return endAsLength("the row closed its thought itself")
}
let budget = min(outputBudget - held.completion - exit.exitTokens.count, exit.answerTokenLimit)
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
index e7ea281696..bca197729c 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
@@ -1118,6 +1118,10 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
let cacheScope = requestCacheScope
let cacheEnabled = cacheEnabled
let donationDemand = donationDemand
+ // The continuation's output starts after the end of thinking, so
+ // stop strings apply from its first token, whatever the prompt opened.
+ let continuationStopScope = ReasoningStopScope.scope(
+ reasoningParser: request.reasoningParser, reasoningPrefix: nil, parsesToolCalls: toolHandler != nil)
let spliced = LoopExitThinkingContinuation.splice(
first: upstream,
cancelFirst: cancelUpstream,
@@ -1148,7 +1152,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
requestId: continuationId,
cacheScope: cacheScope,
cacheEnabled: cacheEnabled,
- stopStringScope: stopStringScope,
+ stopStringScope: continuationStopScope,
donationDemand: donationDemand,
firstContentDeadline: nil,
measurementPurpose: measurementPurpose,
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
index 8cdc89e3ca..e71b404f36 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
@@ -75,10 +75,12 @@ public final class GenerationLoopExitRecord: @unchecked Sendable {
/// Which requests may end a repeating thought instead of the whole answer.
///
-/// On by default for Gemma 4 only, whose thought closes with one special
-/// token (``). The guard keeps ending every other loop as `length`:
-/// a loop outside the thought, a family without a listed marker, a request
-/// that asked for logprobs (the forced token has none), a pair's request.
+/// On by default for Gemma 4, whose thought closes with one special token
+/// (``), and Qwen 3.5/3.6, whose template closes it with
+/// `\n\n\n` (`` is one special token). The guard keeps ending
+/// every other loop as `length`: a loop outside the thought, a family without a
+/// listed marker (Qwen 3.8's thought loops are rare), a request that asked for
+/// logprobs (the forced tokens have none), a pair's request.
///
/// `DARKBLOOM_LOOP_EXIT_THINKING`: unset, `1` or `on` keeps the default list;
/// `0` or `off` turns it off; any other value is the comma-separated list of
@@ -99,9 +101,15 @@ enum GenerationLoopExitThinkingPolicy {
static let markersByModelType: [String: Markers] = [
"gemma4": .init(open: "<|channel>", close: ""),
"gemma4_text": .init(open: "<|channel>", close: ""),
+ "qwen3_5": qwenThink,
+ "qwen3_5_moe": qwenThink,
]
- static let defaultModelTypes: Set = ["gemma4", "gemma4_text"]
+ /// As the Qwen 3.5/3.6 template writes a closed thought:
+ /// `\n…\n\n\n` before the answer.
+ static let qwenThink = Markers(open: "", close: "", before: "\n", after: "\n\n")
+
+ static let defaultModelTypes: Set = ["gemma4", "gemma4_text", "qwen3_5", "qwen3_5_moe"]
/// The answer's own cap. Gemma's GPQA answers after a thought are under
/// 1,000 tokens; a Tau2 reply or call is shorter.
@@ -145,9 +153,15 @@ enum GenerationLoopExitThinkingPolicy {
let tail = tokenizer.decode(
tokenIds: Array(promptTokens.suffix(ReasoningPromptProbe.tailTokenCount)),
skipSpecialTokens: false)
+ // The marker is its own token, so the text on each side tokenizes as
+ // it does in the template's whole closing text.
+ func spell(_ text: String) -> [Int] {
+ text.isEmpty ? [] : tokenizer.encode(text: text, addSpecialTokens: false)
+ }
return GenerationLoopExitThinking(
openMarker: markers.open, closeMarker: markers.close,
- exitTokens: [close], exitText: markers.close,
+ exitTokens: spell(markers.before) + [close] + spell(markers.after),
+ exitText: markers.before + markers.close + markers.after, closeToken: close,
startsInside: endsInside(tail, open: markers.open, close: markers.close),
record: GenerationLoopExitRecord())
}
From e2225639450ae391ffec491bd6aaa69defbf358b Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Thu, 12 Nov 2026 21:18:25 -0800
Subject: [PATCH 03/14] test(provider): exit-thinking for Qwen, the review's
findings (red)
A fresh-context review of eac6e9f141 (REQUEST CHANGES) found:
- 1 (major): `qwen3_5` is not only Qwen 3.5 9B but also Qwen 3.8 27B
(EigenLabs/Qwen3.8-27B-4bit[-mtp]; `qwen4_exp` is Flash-Next), so the
default turned the exit on for a model with rare loops and an unchecked
template, and the 9B is not in the A/B.
- 3 (minor): the "closed its thought itself" check reads tokens only. A
`` whose text the detokenizer has not released when the guard
fires, or one spelled as ordinary pieces after the stop, would get a
second close.
- 4 (minor): a client stop string that ends the continuation is not the
request's matched stop sequence (the row ended `length`).
- 6 (nit): nothing checks that the exit's tokens spell its text.
Red tests and the API they need, with no behaviour yet:
- Only `qwen3_5_moe` (Qwen 3.5/3.6 35B) is on by default; `qwen3_5` through
the env list. Served: Qwen 3.8 27B keeps `length`.
- A close token in the stopping delta whose text has not arrived keeps the
stop a `length`; `` in the in-flight text after the stop marks the
record (`GenerationLoopExitRecord.closedAfterStop`), and the splice then
does not continue.
- With `stop: ["B"]`, the continuation's matched stop is the request's.
- A tokenizer whose encode adds a prefix gets no exit.
- Coverage: a multi-turn prompt with `` in its history starts
inside; a thought the model opens itself after a thinking-off prompt can
be ended; a split `` closes it. The serving tests use Qwen 3.6
(`qwen3_5_moe`); the marker-less family is GPT-OSS.
Co-Authored-By: Claude Opus 5.5
---
.../GenerationLoopExitThinking.swift | 8 ++
.../LoopExitThinkingContinuationTests.swift | 12 +++
...nerationLoopExitThinkingServingTests.swift | 48 +++++++---
.../GenerationLoopExitThinkingTests.swift | 93 ++++++++++++++++++-
4 files changed, 149 insertions(+), 12 deletions(-)
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
index e71b404f36..f8f13ccf16 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
@@ -56,6 +56,7 @@ public final class GenerationLoopExitRecord: @unchecked Sendable {
private let lock = NSLock()
private var tokens: [Int] = []
private var detection: GenerationLoopDetector.Detection?
+ private var closedAfter = false
func append(_ new: [Int]) {
guard !new.isEmpty else { return }
@@ -71,6 +72,13 @@ public final class GenerationLoopExitRecord: @unchecked Sendable {
/// Every token the row produced, the in-flight ones after the stop included.
var generatedTokens: [Int] { lock.withLock { tokens } }
+
+ func noteClosedAfterStop() {
+ lock.withLock { closedAfter = true }
+ }
+
+ /// The row's text after the stop closed the thought.
+ var closedAfterStop: Bool { lock.withLock { closedAfter } }
}
/// Which requests may end a repeating thought instead of the whole answer.
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
index fd71696607..a8aa567c1a 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
@@ -197,6 +197,18 @@ struct LoopExitThinkingContinuationTests {
#expect(closed.submits.isEmpty)
}
+ @Test("a row whose in-flight text closed its thought, without the close token, is not continued")
+ func closedInFlightText() async {
+ let calls = Calls()
+ let exit = exit(requested: true, tokens: thought)
+ exit.record.noteClosedAfterStop()
+ let first = stream([.chunk("thinkA"),
+ .info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")])
+ let out = await drain(splice(first: first, exit: exit, calls: calls) { self.stream([.chunk("never")]) }.events)
+ #expect(out == ["chunk:thinkA", "info:5/4200/length"])
+ #expect(calls.submits.isEmpty)
+ }
+
@Test("no output budget left: nothing is submitted")
func noBudget() async {
let calls = Calls()
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
index 2cb082afc0..4515520de2 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
@@ -222,9 +222,9 @@ struct GenerationLoopExitThinkingServingTests {
var parser = ReasoningParserFormat.gemma4
}
- /// Qwen 3.5 with thinking on: the prompt ends `\n`.
+ /// Qwen 3.6 35B with thinking on: the prompt ends `\n`.
private static let qwen = Served(
- modelID: "EigenLabs/Qwen3.5-9B-MLX-4bit-mtp", modelType: "qwen3_5",
+ modelID: "qwen3.6-35b-a3b-vl-mtp-mxfp8", modelType: "qwen3_5_moe",
tokenizer: TokenizerHandle(QwenByteTestTokenizer()), eosTokenIds: [248_046, 248_044], parser: .qwen3)
private struct Outcome {
@@ -249,7 +249,8 @@ struct GenerationLoopExitThinkingServingTests {
}
private func serve(
- _ engine: ThoughtLoopCBv2Engine, served: Served = Served(), maxTokens: Int = 8_192
+ _ engine: ThoughtLoopCBv2Engine, served: Served = Served(), maxTokens: Int = 8_192, extra: String = "",
+ usage: EngineV2RequestUsageSignal? = nil
) async throws -> Outcome {
let telemetry = TelemetrySink()
let bridge = EngineV2Bridge(engine: engine, modelId: served.modelID, tokenizer: served.tokenizer,
@@ -257,19 +258,20 @@ struct GenerationLoopExitThinkingServingTests {
maxConcurrentRequests: 1, emitTelemetry: { telemetry.add($0) })
let scheduler = MultiModelBatchSchedulerEngine(registryProvider: {
[served.modelID: .init(tokenizer: served.tokenizer, modelType: served.modelType, engineV2Bridge: bridge)]
- })
- var outcome = try await consume(scheduler, served: served, maxTokens: maxTokens)
+ }, engineV2Usage: usage)
+ var outcome = try await consume(scheduler, served: served, maxTokens: maxTokens, extra: extra)
await bridge.shutdown()
outcome.loopGuardStops = telemetry.loopGuardStops
return outcome
}
+ /// `extra`: more top-level request fields, each with its leading comma.
private func consume(
- _ scheduler: MultiModelBatchSchedulerEngine, served: Served = Served(), maxTokens: Int
+ _ scheduler: MultiModelBatchSchedulerEngine, served: Served = Served(), maxTokens: Int, extra: String = ""
) async throws -> Outcome {
let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: Data("""
{"model":"\(served.modelID)","messages":[{"role":"user","content":"hi"}],\
- "reasoning_parser":"\(served.parser.rawValue)","max_tokens":\(maxTokens)}
+ "reasoning_parser":"\(served.parser.rawValue)","max_tokens":\(maxTokens)\(extra)}
""".utf8))
var outcome = Outcome()
var parser = StreamingReasoningParser(format: served.parser)
@@ -392,7 +394,7 @@ struct GenerationLoopExitThinkingServingTests {
#expect(outcome.content == "Answer: B")
}
- @Test("Qwen 3.5: a loop inside the thought ends it with `\\n\\n\\n`, and stops apply to the answer")
+ @Test("Qwen 3.6: a loop inside the thought ends it with `\\n\\n\\n`, and stops apply to the answer")
func qwenThoughtLoopEndsInAnAnswer() async throws {
let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, family: .qwen)
let outcome = try await serve(engine, served: Self.qwen)
@@ -421,7 +423,7 @@ struct GenerationLoopExitThinkingServingTests {
#expect(outcome.loopGuardStops == [true])
}
- @Test("Qwen 3.5: a loop in the answer, after ``, still ends as length")
+ @Test("Qwen 3.6: a loop in the answer, after ``, still ends as length")
func qwenAnswerLoopEndsAsLength() async throws {
let engine = ThoughtLoopCBv2Engine(loopInsideThought: false, family: .qwen)
let outcome = try await serve(engine, served: Self.qwen)
@@ -431,11 +433,35 @@ struct GenerationLoopExitThinkingServingTests {
#expect(outcome.loopGuardStops == [false])
}
+ @Test("a stop string that ends the answer is the request's matched stop sequence")
+ func qwenStopInTheAnswer() async throws {
+ let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, family: .qwen)
+ let usage = EngineV2RequestUsageSignal()
+ let outcome = try await serve(engine, served: Self.qwen, extra: #","stop":["B"]"#, usage: usage)
+ #expect(outcome.error == nil)
+ #expect(engine.requests.count == 2)
+ #expect(engine.requests.last?.stopStrings == ["B"])
+ #expect(outcome.info?.stopReason == "stop")
+ // The row ended `length`; the stop that ended the answer is the continuation's.
+ #expect(usage.matchedStopSequence == "B")
+ }
+
+ @Test("Qwen 3.8 27B shares `qwen3_5` with the 9B and keeps today's length by default")
+ func qwen38KeepsLength() async throws {
+ let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, family: .qwen)
+ var served = Self.qwen
+ served.modelID = "EigenLabs/Qwen3.8-27B-4bit-mtp"
+ served.modelType = "qwen3_5"
+ let outcome = try await serve(engine, served: served)
+ #expect(engine.requests.count == 1)
+ #expect(outcome.info?.stopReason == "length")
+ #expect(outcome.loopGuardStops == [false])
+ }
+
@Test("a family without the exit keeps today's length")
func otherFamilyKeepsLength() async throws {
let engine = ThoughtLoopCBv2Engine(loopInsideThought: true)
- // Qwen 3.8: its thought loops are rare in production, so it has no exit.
- let outcome = try await serve(engine, served: Served(modelType: "qwen4_exp"))
+ let outcome = try await serve(engine, served: Served(modelType: "gpt_oss"))
#expect(engine.requests.count == 1)
#expect(outcome.info?.stopReason == "length")
#expect(outcome.loopGuardStops == [false])
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
index 07f2f98c9c..69950eb524 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
@@ -241,13 +241,26 @@ struct GenerationLoopExitThinkingTests {
@Test("Qwen 3.5/3.6 end the thought as their template does: `\\n\\n\\n`, the marker as its own token")
func qwenFamilies() throws {
for modelType in ["qwen3_5", "qwen3_5_moe"] {
- let exit = try #require(qwenExit(modelType), "\(modelType)")
+ let exit = try #require(GenerationLoopExitThinkingPolicy.resolve(
+ modelType: modelType, tokenizer: Self.qwen, promptTokens: Self.qwenThinking, logprobs: false,
+ setting: .modelTypes([modelType])), "\(modelType)")
#expect(exit.exitText == "\n\n\n")
#expect(exit.exitTokens == [10, 248069, 10, 10])
#expect(exit.closeToken == 248069)
// The served template opens the thought in the prompt.
#expect(exit.startsInside)
}
+ // On by default for the two 35B models (`qwen3_5_moe`) only: `qwen3_5`
+ // also covers Qwen 3.8 27B, whose loops are rare, and the 9B was not A/B'd.
+ #expect(qwenExit("qwen3_5_moe") != nil)
+ #expect(qwenExit("qwen3_5") == nil)
+ // A prompt whose earlier turns closed their thoughts still opens this one.
+ let history = QwenByteTestTokenizer.tokens("<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n"
+ + "\nok\n\n\nhello<|im_end|>\n<|im_start|>user\nmore<|im_end|>\n"
+ + "<|im_start|>assistant\n\n")
+ #expect(GenerationLoopExitThinkingPolicy.resolve(
+ modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: history, logprobs: false,
+ setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes))?.startsInside == true)
let closed = QwenByteTestTokenizer.tokens(QwenByteTestTokenizer.prompt(thinking: false))
#expect(GenerationLoopExitThinkingPolicy.resolve(
modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: closed, logprobs: false,
@@ -281,6 +294,84 @@ struct GenerationLoopExitThinkingTests {
#expect(!inAnswer.endsThought)
}
+ @Test("a Qwen thought the model opens itself, after a thinking-off prompt, can be ended; a split `` closes it")
+ func qwenChannelEdges() throws {
+ let closedPrompt = QwenByteTestTokenizer.tokens(QwenByteTestTokenizer.prompt(thinking: false))
+ let exit = try #require(GenerationLoopExitThinkingPolicy.resolve(
+ modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: closedPrompt, logprobs: false,
+ setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes)))
+ #expect(!exit.startsInside)
+ var reopened = GenerationLoopGuard(
+ modelType: "qwen3_5_moe", toolCallMarkers: GenerationLoopGuardPolicy.genericToolCallMarkers, exitThinking: exit)
+ let (inside, _) = run([("", [248068]), ("\n", [10])] + clause(8_000), into: &reopened)
+ #expect(inside != nil)
+ #expect(reopened.endsThought)
+
+ var split = GenerationLoopGuard(
+ modelType: "qwen3_5_moe", toolCallMarkers: GenerationLoopGuardPolicy.genericToolCallMarkers,
+ exitThinking: try #require(qwenExit()))
+ let pieces: [(String, [Int])] = [("ok\n\n\n", [110, 107, 62, 10, 10])]
+ let (outside, _) = run(pieces + clause(8_000), into: &split)
+ #expect(outside != nil)
+ #expect(!split.endsThought)
+ }
+
+ @Test("a `` whose text has not arrived yet keeps the stop a length: in the stopping delta or after it")
+ func qwenCloseTheTextHasNotShown() throws {
+ // The stopping delta carries the close token, but the detokenizer has
+ // not released its text yet: the row is not stopped inside its thought.
+ let held = try #require(qwenExit())
+ var stopping = GenerationLoopGuard(
+ modelType: "qwen3_5_moe", toolCallMarkers: GenerationLoopGuardPolicy.genericToolCallMarkers, exitThinking: held)
+ var fired: GenerationLoopDetector.Detection?
+ for (index, (text, tokens)) in clause(8_000).enumerated() {
+ // Every delta from the 4,096th on could be the one that fires.
+ let closing = index >= 4_095 ? tokens + [248069] : tokens
+ if let detection = stopping.observe(text: text, tokens: closing) { fired = detection; break }
+ }
+ #expect(fired != nil)
+ #expect(!stopping.endsThought)
+ #expect(held.record.requested == nil)
+
+ // After the stop: `` spelled as ordinary pieces (no close
+ // token) still closes the thought, in the text the guard follows.
+ let after = try #require(qwenExit())
+ var spelled = GenerationLoopGuard(
+ modelType: "qwen3_5_moe", toolCallMarkers: GenerationLoopGuardPolicy.genericToolCallMarkers, exitThinking: after)
+ let (stop, _) = run(clause(8_000), into: &spelled)
+ #expect(stop != nil)
+ #expect(spelled.endsThought)
+ #expect(!after.record.closedAfterStop)
+ #expect(spelled.observe(text: "\n", tokens: [10, 1_000]) == nil)
+ #expect(spelled.observe(text: "think>\n\nB", tokens: [1_001, 1_002, 66]) == nil)
+ #expect(after.record.closedAfterStop)
+ }
+
+ @Test("the exit's tokens must spell its text: a tokenizer that adds a prefix gets no exit")
+ func exitTokensSpellTheText() {
+ struct Prefixing: MLXLMCommon.Tokenizer {
+ let inner = QwenByteTestTokenizer()
+ func encode(text: String, addSpecialTokens: Bool) -> [Int] {
+ [248044] + inner.encode(text: text, addSpecialTokens: addSpecialTokens)
+ }
+ func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String {
+ inner.decode(tokenIds: tokenIds, skipSpecialTokens: skipSpecialTokens)
+ }
+ func convertTokenToId(_ token: String) -> Int? { inner.convertTokenToId(token) }
+ func convertIdToToken(_ id: Int) -> String? { inner.convertIdToToken(id) }
+ var bosToken: String? { nil }
+ var eosToken: String? { inner.eosToken }
+ var unknownToken: String? { nil }
+ func applyChatTemplate(messages: [[String: any Sendable]], tools: [[String: any Sendable]]?,
+ additionalContext: [String: any Sendable]?) throws -> [Int] {
+ try inner.applyChatTemplate(messages: messages, tools: tools, additionalContext: additionalContext)
+ }
+ }
+ #expect(GenerationLoopExitThinkingPolicy.resolve(
+ modelType: "qwen3_5_moe", tokenizer: Prefixing(), promptTokens: Self.qwenThinking, logprobs: false,
+ setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes)) == nil)
+ }
+
@Test("darkbloom start passes the loop guard's and the exit's switches to the launchd daemon")
func launchdPassthrough() {
for key in [GenerationLoopExitThinkingPolicy.environmentKey, GenerationLoopGuardPolicy.environmentKey] {
From c4769c16086db1f3b1d9b8564954aa17fa92b7f9 Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Thu, 12 Nov 2026 21:46:25 -0800
Subject: [PATCH 04/14] fix(provider): exit-thinking for Qwen, the review's
findings
- 1: `qwen3_5` keeps its marker but is off by default. It is Qwen 3.5 9B
and also Qwen 3.8 27B (EigenLabs/Qwen3.8-27B-4bit[-mtp]), whose loops are
rare and whose template was not checked; the 9B is not in the A/B. On by
default: gemma4, gemma4_text, qwen3_5_moe (Qwen 3.5 35B, Qwen 3.6 35B).
`DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text,qwen3_5_moe,qwen3_5` adds
the 9B and Qwen 3.8 27B. Wording fixed (Qwen 3.8 is not `qwen4_exp`).
- 3: the guard does not ask to end the thought when the stopping delta
carries the close token whose text the detokenizer still holds back; after
the stop it keeps following the in-flight text, and a close there (a
`` spelled as ordinary pieces, or one that arrived late) marks the
record, so the splice ends the request `length` instead of closing twice.
- 4: the continuation has its own usage signal (one per engine request);
when it ends the answer, its matched stop sequence is the request's, so
the coordinator sees the stop that ended the answer (Gemma 4's too).
- 6: no exit unless its tokens decode to its text.
- 7: the channel-carry comment is right for ``.
- Docs and the changelog fragment.
Also: 0.10.12's "a reasoning loop is stopped in the engine and ends as
length" serving test (`qwen3_5`, Qwen 3.5 9B) failed on eac6e9f141, which
had `qwen3_5` on; it holds again.
Co-Authored-By: Claude Opus 5.5
---
changelog.d/loop-guard-exit-thinking-qwen.md | 10 ++++----
docs/architecture/inference.md | 21 +++++++++-------
.../LoopExitThinkingContinuation.swift | 10 ++++----
.../MultiModelBatchSchedulerEngine.swift | 7 ++++++
.../GenerationLoopExitThinking.swift | 24 ++++++++++++-------
.../Streaming/GenerationLoopGuard.swift | 19 +++++++++++----
6 files changed, 60 insertions(+), 31 deletions(-)
diff --git a/changelog.d/loop-guard-exit-thinking-qwen.md b/changelog.d/loop-guard-exit-thinking-qwen.md
index cc175d4edf..8109da61fb 100644
--- a/changelog.d/loop-guard-exit-thinking-qwen.md
+++ b/changelog.d/loop-guard-exit-thinking-qwen.md
@@ -1,6 +1,6 @@
-### A Qwen 3.5 or 3.6 thought that repeats itself verbatim now ends in an answer
+### A Qwen 3.5 or 3.6 35B thought that repeats itself verbatim now ends in an answer
-- As for Gemma 4 in 0.10.13: when the loop guard stops a verbatim loop inside a Qwen 3.5 or 3.6 thought, the request no longer ends as `length` with no answer. The provider ends the thought as Qwen's template does (`\n\n\n`), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
-- Since 0.10.12, 1.6–3.0 % of GPQA-shaped Qwen 3.5/3.6 requests ended that way with no answer.
-- Qwen 3.5 and 3.6 (`qwen3_5`, `qwen3_5_moe`). Not Qwen 3.8, whose thought loops are rare. Never with logprobs or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text` keeps Gemma's alone; `0` turns both off.
-- Stop strings apply to the answer from its first token.
+- As for Gemma 4 in 0.10.13: when the loop guard stops a verbatim loop inside a Qwen 3.5 or 3.6 35B thought, the request no longer ends as `length` with no answer. The provider ends the thought as Qwen's template does (`\n\n\n`), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
+- Since 0.10.12, 1.6–2.6 % of GPQA-shaped requests to these two models ended that way with no answer.
+- On by default for `qwen3_5_moe` (Qwen 3.5 35B, Qwen 3.6 35B). Not by default for `qwen3_5` (Qwen 3.5 9B, Qwen 3.8 27B). Never with logprobs or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text` keeps Gemma's alone; `gemma4,gemma4_text,qwen3_5_moe,qwen3_5` adds the 9B and Qwen 3.8 27B; `0` turns it off.
+- Client stop strings apply to the answer from its first token, and a stop string that ends the answer is reported as the matched stop sequence (Gemma 4's too).
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index 1bf16bc19e..94ef609dcf 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -3252,9 +3252,10 @@ stops such a row early.
(Super, text only), `glm5_next` and `mimo_v2`. `DARKBLOOM_LOOP_GUARD=0`
(or `off`) turns it off; a comma-separated list of `model_type`s replaces
the default list.
-- **A loop inside a Gemma 4 or Qwen 3.5/3.6 thought ends the thought, not the
- answer** (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`).
- For `gemma4`, `gemma4_text`, `qwen3_5` and `qwen3_5_moe`, the guard also
+- **A loop inside a Gemma 4 or Qwen 3.5/3.6 35B thought ends the thought, not
+ the answer** (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`).
+ For `gemma4`, `gemma4_text` and `qwen3_5_moe` (on by default) and `qwen3_5`
+ (Qwen 3.5 9B and Qwen 3.8 27B: listed, off by default), the guard also
follows the thought channel (`<|channel>` … ``, `` …
``; the prompt's tail seeds the state: Qwen's served template opens
`` in the prompt) and records
@@ -3272,7 +3273,8 @@ stops such a row early.
`max_tokens` = the output the bridge resolved for the row minus the tokens
produced minus the exit tokens, at most 8,192; the same sampling, stop strings
and cache scope, the stop strings scoped as for output that starts outside the
- thought; and a loop guard without the exit, so a loop in the answer still ends
+ thought (a stop that ends the answer is the request's matched stop sequence);
+ and a loop guard without the exit, so a loop in the answer still ends
as `length`. The client's stream carries the thought, the exit text as one
chunk and the answer, then one terminal: the original prompt, completion =
the row's tokens + the exit tokens + the answer's, the continuation's finish
@@ -3281,15 +3283,18 @@ stops such a row early.
continuation prefills the thought again (its prompt part can hit the prefix
cache). When the continuation cannot start (under 256 tokens of budget left,
the row closed its thought itself (its in-flight tokens after the stop hold
- the close marker's token), the row did not release its slot in time,
+ the close marker's token, or its in-flight text closes the thought; a close
+ token in the stopping delta whose text has not arrived keeps the stop a
+ `length`), the row did not release its slot in time,
a refused submission, a failure before its first token, a cancel), the held
`length` terminal is
delivered as before; a failure after its first token ends the answer there,
as `length` (only the client's cancel keeps its error). Never with
- logprobs or on a cluster pair. Not for Qwen 3.8 (`qwen4_exp`), whose
- thought loops are rare. `DARKBLOOM_LOOP_EXIT_THINKING=0` (or `off`)
+ logprobs or on a cluster pair. Never when the exit's tokens do not decode to
+ its text. `DARKBLOOM_LOOP_EXIT_THINKING=0` (or `off`)
turns it off; a comma-separated list keeps it to the listed `model_type`s
- that have a marker (`gemma4,gemma4_text` keeps Gemma's alone). `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
+ that have a marker (`gemma4,gemma4_text` keeps Gemma's alone;
+ `gemma4,gemma4_text,qwen3_5_moe,qwen3_5` adds the 9B and Qwen 3.8 27B). `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
to the launchd daemon (`LaunchAgent.inferencePassthroughEnvKeys`). One `darkbloom.loop-guard.exit-thinking` line per ended
thought gives the outcome.
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
index 4cfe1d6837..683e9b4538 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
@@ -126,11 +126,11 @@ enum LoopExitThinkingContinuation {
onOutcome?(.endedAsLength(reason: reason))
}
let generated = exit.record.generatedTokens
- // A row that closed its thought itself, in the tokens it produced
- // after the stop, has no thought left to end. Only the marker's own
- // token says so: the text around it (Qwen's newlines) is any text.
- if let detection = exit.record.requested,
- generated.dropFirst(detection.generatedTokens).contains(exit.closeToken) {
+ // A row that closed its thought itself after the stop has no thought
+ // left to end: the marker's own token says so (not the text around
+ // it: Qwen's newlines are any text), or the text the guard followed.
+ if let detection = exit.record.requested, exit.record.closedAfterStop
+ || generated.dropFirst(detection.generatedTokens).contains(exit.closeToken) {
return endAsLength("the row closed its thought itself")
}
let budget = min(outputBudget - held.completion - exit.exitTokens.count, exit.answerTokenLimit)
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
index bca197729c..3acf8dcb9c 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
@@ -1122,6 +1122,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// stop strings apply from its first token, whatever the prompt opened.
let continuationStopScope = ReasoningStopScope.scope(
reasoningParser: request.reasoningParser, reasoningPrefix: nil, parsesToolCalls: toolHandler != nil)
+ // A usage signal belongs to one engine request: the continuation
+ // has its own, and the stop that ended the answer is the request's.
+ let continuationUsage = EngineV2RequestUsageSignal()
let spliced = LoopExitThinkingContinuation.splice(
first: upstream,
cancelFirst: cancelUpstream,
@@ -1152,6 +1155,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
requestId: continuationId,
cacheScope: cacheScope,
cacheEnabled: cacheEnabled,
+ usageSignal: continuationUsage,
stopStringScope: continuationStopScope,
donationDemand: donationDemand,
firstContentDeadline: nil,
@@ -1164,6 +1168,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
},
cancelContinuation: { await bridge.cancel(requestId: continuationId) },
onOutcome: { outcome in
+ if case .continued = outcome {
+ requestUsage.record(matchedStopSequence: continuationUsage.matchedStopSequence)
+ }
LoopExitThinkingContinuation.logger.notice(
"loop guard ended a thought", metadata: [
"request_id": .string(requestId), "outcome": .string(outcome.description)])
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
index f8f13ccf16..9365872f82 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
@@ -77,18 +77,21 @@ public final class GenerationLoopExitRecord: @unchecked Sendable {
lock.withLock { closedAfter = true }
}
- /// The row's text after the stop closed the thought.
+ /// The row's text after the stop closed the thought: a close whose token
+ /// came before its text, or one spelled as ordinary pieces.
var closedAfterStop: Bool { lock.withLock { closedAfter } }
}
/// Which requests may end a repeating thought instead of the whole answer.
///
/// On by default for Gemma 4, whose thought closes with one special token
-/// (``), and Qwen 3.5/3.6, whose template closes it with
-/// `\n\n\n` (`` is one special token). The guard keeps ending
-/// every other loop as `length`: a loop outside the thought, a family without a
-/// listed marker (Qwen 3.8's thought loops are rare), a request that asked for
-/// logprobs (the forced tokens have none), a pair's request.
+/// (``), and the Qwen 3.5/3.6 35B models (`qwen3_5_moe`), whose
+/// template closes it with `\n\n\n` (`` is one special token).
+/// `qwen3_5` has the marker but is off by default: it is Qwen 3.5 9B and also
+/// Qwen 3.8 27B, whose thought loops are rare. The guard keeps ending every
+/// other loop as `length`: a loop outside the thought, a family that is not
+/// on, a request that asked for logprobs (the forced tokens have none), a
+/// pair's request.
///
/// `DARKBLOOM_LOOP_EXIT_THINKING`: unset, `1` or `on` keeps the default list;
/// `0` or `off` turns it off; any other value is the comma-separated list of
@@ -117,7 +120,7 @@ enum GenerationLoopExitThinkingPolicy {
/// `\n…\n\n\n` before the answer.
static let qwenThink = Markers(open: "", close: "", before: "\n", after: "\n\n")
- static let defaultModelTypes: Set = ["gemma4", "gemma4_text", "qwen3_5", "qwen3_5_moe"]
+ static let defaultModelTypes: Set = ["gemma4", "gemma4_text", "qwen3_5_moe"]
/// The answer's own cap. Gemma's GPQA answers after a thought are under
/// 1,000 tokens; a Tau2 reply or call is shorter.
@@ -166,10 +169,13 @@ enum GenerationLoopExitThinkingPolicy {
func spell(_ text: String) -> [Int] {
text.isEmpty ? [] : tokenizer.encode(text: text, addSpecialTokens: false)
}
+ let exitTokens = spell(markers.before) + [close] + spell(markers.after)
+ let exitText = markers.before + markers.close + markers.after
+ // The model must be fed what the client is shown.
+ guard tokenizer.decode(tokenIds: exitTokens, skipSpecialTokens: false) == exitText else { return nil }
return GenerationLoopExitThinking(
openMarker: markers.open, closeMarker: markers.close,
- exitTokens: spell(markers.before) + [close] + spell(markers.after),
- exitText: markers.before + markers.close + markers.after, closeToken: close,
+ exitTokens: exitTokens, exitText: exitText, closeToken: close,
startsInside: endsInside(tail, open: markers.open, close: markers.close),
record: GenerationLoopExitRecord())
}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift
index e064ed9115..297c03538c 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift
@@ -59,7 +59,15 @@ public struct GenerationLoopGuard: Sendable {
if let exitThinking, !sawToolCall {
exitThinking.record.append(tokens)
}
- guard !disarmed else { return nil }
+ guard !disarmed else {
+ // After a stop that ended the thought, the in-flight text still
+ // says whether the row closed it itself.
+ if endsThought, let exitThinking, !text.isEmpty {
+ followChannel(text, markers: exitThinking)
+ if !insideThinking { exitThinking.record.noteClosedAfterStop() }
+ }
+ return nil
+ }
if !toolCallMarkers.isEmpty, !text.isEmpty {
let scanned = carry + text
let bytes = markerBytes
@@ -76,7 +84,9 @@ public struct GenerationLoopGuard: Sendable {
}
guard let detection = detector.append(tokens) else { return nil }
disarmed = true
- if let exitThinking, insideThinking {
+ // A close token in this delta whose text the detokenizer still holds
+ // back: the thought has ended, so the stop stays a `length`.
+ if let exitThinking, insideThinking, !tokens.contains(exitThinking.closeToken) {
endsThought = true
exitThinking.record.requestExit(detection)
}
@@ -85,8 +95,9 @@ public struct GenerationLoopGuard: Sendable {
/// The last channel marker seen decides whether the row is inside its
/// thought. A marker split across deltas is seen through `channelCarry`,
- /// which is one character shorter than the longest marker, so a marker
- /// is never counted from the carry alone.
+ /// one character shorter than the longest marker. A shorter marker (Qwen's
+ /// ``) can be seen again from the carry alone; it was already the
+ /// last marker then, so the state does not change.
private mutating func followChannel(_ text: String, markers: GenerationLoopExitThinking) {
let scanned = channelCarry + text
if scanned.utf8.contains(UInt8(ascii: "<")) {
From f52e7d17044b9ea34913a5f2b3b00c3eb5b78a8b Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Thu, 12 Nov 2026 22:57:01 -0800
Subject: [PATCH 05/14] test(provider): exit-thinking for Nemotron 3.5 Super's
own route (red)
Super has the highest rate of any family: on 0.10.12, 29.6 per 1,000
GPQA-shaped requests (24/812, the last 12 h) end with the loop guard's stop
and no answer, all `success` below the cap; identical prompts stop at the
same count. Its GPQA rolling score is 82.7 against an 82.8 derank cutoff.
Super's requests take its owner's route (NemotronSuperLocalImageHTTP ->
NemotronSuperLocalBinding), not the scheduler's text path, so #2040/#2046's
continuation never reaches them. Red tests and the API they need, with no
behaviour yet:
- Super's exit is `` alone, as its pinned template writes a closed
thought ("\n" + reasoning + "" + content); the thinking-on
prompt opens the thought, thinking off starts outside; never with
logprobs; the env list can leave Super's off; the guard carries it
(`NemotronSuperRequestPlan.exitThinking(promptTokens:tokenizer:)`,
`loopGuard(exitThinking:)`).
- End to end through the binding (a scripted Super engine): a repeating
thought is continued on the same bridge with the prompt, the row's tokens
and ``; the client gets `...Answer: B` and one terminal
with every token; a stop that ends the answer is the request's matched
stop sequence.
Co-Authored-By: Claude Opus 5.5
---
.../Prompting/NemotronSuperRequestPlan.swift | 19 ++-
.../NemotronSuperLoopGuardTests.swift | 141 ++++++++++++++++++
2 files changed, 158 insertions(+), 2 deletions(-)
diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperRequestPlan.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperRequestPlan.swift
index 3090b4ac81..33b878ff7a 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperRequestPlan.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperRequestPlan.swift
@@ -60,12 +60,27 @@ struct NemotronSuperRequestPlan: Sendable {
/// The text request's loop guard: the scheduler's text path policy
/// (`GenerationLoopGuardPolicy`), so the same model list, exclusions and
/// `DARKBLOOM_LOOP_GUARD` switch. Media requests get none, as there.
+ /// `exitThinking`: this request's way out of a repeating thought
+ /// (`exitThinking(promptTokens:tokenizer:)`).
func loopGuard(
- setting: GenerationLoopGuardPolicy.Setting = GenerationLoopGuardPolicy.current
+ setting: GenerationLoopGuardPolicy.Setting = GenerationLoopGuardPolicy.current,
+ exitThinking: GenerationLoopExitThinking? = nil
) -> GenerationLoopGuard? {
guard !hasMedia else { return nil }
return GenerationLoopGuardPolicy.resolve(modelType: Self.modelType, request: request,
- prepared: toolPolicy, tokenConstraint: nil, setting: setting)
+ prepared: toolPolicy, tokenConstraint: nil, setting: setting, exitThinking: exitThinking)
+ }
+
+ /// The exit for a text request's rendered prompt, as the scheduler's text
+ /// path resolves it (`GenerationLoopExitThinkingPolicy`): never with
+ /// logprobs, or with media.
+ func exitThinking(
+ promptTokens: [Int], tokenizer: any MLXLMCommon.Tokenizer,
+ setting: GenerationLoopExitThinkingPolicy.Setting = GenerationLoopExitThinkingPolicy.current
+ ) -> GenerationLoopExitThinking? {
+ guard !hasMedia else { return nil }
+ return GenerationLoopExitThinkingPolicy.resolve(modelType: Self.modelType, tokenizer: tokenizer,
+ promptTokens: promptTokens, logprobs: topLogprobs > 0, setting: setting)
}
/// The request the bridge executes, for text and media alike. `translate`
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift
index 00b7dfe555..a366b2eac2 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift
@@ -63,6 +63,80 @@ private final class SuperLoopingEngine: CBv2Engine, @unchecked Sendable {
func shutdown() async {}
}
+/// Super's markers in a byte-spelled test vocabulary below Super's 131,072
+/// (the binding refuses ids outside it).
+private enum SuperThoughtVocabulary {
+ static let think = 1012
+ static let thinkClose = 1013
+ static let imEnd = 1011
+ static let markers: [(String, Int)] = [("", think), ("", thinkClose), ("<|im_end|>", imEnd)]
+ static let tokenizer = GemmaThoughtTestTokenizer(markers: markers)
+ static func tokens(_ text: String) -> [Int] { GemmaThoughtTestTokenizer.tokens(text, markers: markers) }
+ /// Super's generation prompt with thinking on: the thought is open.
+ static let thinkingPrompt = tokens("<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n")
+}
+
+/// A Super row that repeats one clause verbatim inside the thought its prompt
+/// opened, one token per delta; the guard's cancel ends it `.cancelled`. Any
+/// later submission is the continuation: it answers "Answer: B" and stops.
+private final class SuperThoughtLoopEngine: CBv2Engine, @unchecked Sendable {
+ private let lock = NSLock()
+ private var continuations: [AsyncStream.Continuation] = []
+ private var submitted: [CBv2Request] = []
+ private var produced: [[Int]] = []
+
+ var requests: [CBv2Request] { lock.withLock { submitted } }
+ var outputs: [[Int]] { lock.withLock { produced } }
+
+ func submit(_ request: CBv2Request) throws -> AsyncStream {
+ let (stream, continuation) = AsyncStream.makeStream()
+ let index = lock.withLock {
+ submitted.append(request)
+ continuations.append(continuation)
+ produced.append([])
+ return submitted.count - 1
+ }
+ func emit(_ text: String) {
+ let tokens = SuperThoughtVocabulary.tokens(text)
+ lock.withLock { produced[index] += tokens }
+ continuation.yield(.delta(text: text, tokens: tokens, logprobs: nil))
+ }
+ if index == 0 {
+ let clause = Array("Wait, the reaction is: CO + Cu -> CO2 + Cu (No). ")
+ for position in 0..<4_200 { emit(String(clause[position % clause.count])) }
+ Task { [weak self] in
+ try? await Task.sleep(for: .seconds(3))
+ self?.finish(index, .length)
+ }
+ } else {
+ for character in "Answer: B" { emit(String(character)) }
+ finish(index, .stop)
+ }
+ return stream
+ }
+
+ private func finish(_ index: Int, _ reason: CBv2FinishReason) {
+ let (continuation, prompt, completion) = lock.withLock {
+ defer { continuations[index] = AsyncStream.makeStream().continuation }
+ return (continuations[index], submitted[index].promptTokens.count, produced[index].count)
+ }
+ continuation.yield(.finished(
+ reason: reason, usage: CBv2Usage(promptTokens: prompt, completionTokens: completion)))
+ continuation.finish()
+ }
+
+ func cancel(_ id: CBv2RequestID) {
+ let index = lock.withLock { submitted.lastIndex { $0.id == id } }
+ if let index { finish(index, .cancelled) }
+ }
+
+ func capacity() -> CBv2CapacitySnapshot {
+ .init(activeRequests: 0, waitingRequests: 0, kvBytesInUse: 0, kvBytesCapacity: 0, activeTokens: 0)
+ }
+
+ func shutdown() async {}
+}
+
private actor SuperLoopEvents {
var text = ""
var stopReason: String?
@@ -150,6 +224,73 @@ struct NemotronSuperLoopGuardTests {
#expect(await events.text.utf8.count > 4_096)
}
+ // MARK: Ending a repeating thought
+
+ private static let exitDefaults = GenerationLoopExitThinkingPolicy.Setting.modelTypes(
+ GenerationLoopExitThinkingPolicy.defaultModelTypes)
+
+ @Test("Super's exit is `` alone, as its template writes a thought; its prompt opens the thought")
+ func superExit() throws {
+ let plan = try plan()
+ let exit = try #require(plan.exitThinking(
+ promptTokens: SuperThoughtVocabulary.thinkingPrompt, tokenizer: SuperThoughtVocabulary.tokenizer,
+ setting: Self.exitDefaults))
+ #expect(exit.exitTokens == [SuperThoughtVocabulary.thinkClose])
+ #expect(exit.exitText == "")
+ #expect(exit.startsInside)
+ // Thinking off: the prompt closed an empty thought.
+ let off = SuperThoughtVocabulary.tokens("<|im_start|>assistant\n")
+ #expect(plan.exitThinking(promptTokens: off, tokenizer: SuperThoughtVocabulary.tokenizer,
+ setting: Self.exitDefaults)?.startsInside == false)
+ // Never with logprobs; the env list can leave Super's off.
+ #expect(try self.plan(",\"logprobs\":true,\"top_logprobs\":2").exitThinking(
+ promptTokens: SuperThoughtVocabulary.thinkingPrompt, tokenizer: SuperThoughtVocabulary.tokenizer,
+ setting: Self.exitDefaults) == nil)
+ #expect(plan.exitThinking(
+ promptTokens: SuperThoughtVocabulary.thinkingPrompt, tokenizer: SuperThoughtVocabulary.tokenizer,
+ setting: .modelTypes(["gemma4", "gemma4_text", "qwen3_5_moe"])) == nil)
+ // The guard carries it.
+ let loopGuard = try #require(plan.loopGuard(setting: Self.defaults, exitThinking: exit))
+ #expect(loopGuard.exitThinking?.record === exit.record)
+ }
+
+ @Test("a repeating Super thought ends in an answer on the owner's route; a stop in the answer is the request's")
+ func superThoughtLoopEndsInAnAnswer() async throws {
+ let engine = SuperThoughtLoopEngine()
+ let modelID = NemotronSuperLocalBinding.modelID
+ let tokenizer = TokenizerHandle(SuperThoughtVocabulary.tokenizer)
+ let bridge = EngineV2Bridge(engine: engine, modelId: modelID, tokenizer: tokenizer,
+ eosTokenIds: [SuperThoughtVocabulary.imEnd], defaultMaxTokens: 64, maxConcurrentRequests: 1)
+ let binding = NemotronSuperLocalBinding(acquire: { model in
+ .init(tokenizer: tokenizer, releaseToken: OneShotRelease(release: { _ in }, modelId: model),
+ engineV2Bridge: bridge)
+ })
+ let plan = try plan(#","stop":["B"]"#)
+ let prompt = SuperThoughtVocabulary.thinkingPrompt
+ let exit = plan.exitThinking(promptTokens: prompt, tokenizer: SuperThoughtVocabulary.tokenizer,
+ setting: Self.exitDefaults)
+ let usage = EngineV2RequestUsageSignal()
+ let events = SuperLoopEvents()
+ try await binding.run(request: plan.bridgeRequest, promptTokens: prompt, usageSignal: usage,
+ loopGuard: plan.loopGuard(setting: Self.defaults, exitThinking: exit),
+ onEvent: { await events.record($0) })
+ await bridge.shutdown()
+ let requests = engine.requests
+ #expect(requests.count == 2)
+ let first = try #require(requests.first)
+ let continuation = try #require(requests.last)
+ let firstOutput = try #require(engine.outputs.first)
+ // The same prompt, every token the row produced, then ``.
+ #expect(continuation.promptTokens == first.promptTokens + firstOutput + [SuperThoughtVocabulary.thinkClose])
+ #expect(continuation.maxTokens == first.maxTokens - firstOutput.count - 1)
+ #expect(continuation.stopStrings == ["B"])
+ #expect(await events.errors == 0)
+ #expect(await events.text.hasSuffix("Answer: B"))
+ #expect(await events.stopReason == "stop")
+ #expect(await events.completionTokens == firstOutput.count + 1 + 9)
+ #expect(usage.matchedStopSequence == "B")
+ }
+
@Test("with the switch off the row runs to the engine's own end")
func switchOffKeepsTodaysBehavior() async throws {
let engine = SuperLoopingEngine(tokens: 4_200)
From 66274c90ff562e469016de24de47aecbecbbac03 Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Thu, 12 Nov 2026 23:02:31 -0800
Subject: [PATCH 06/14] feat(provider): a repeating Nemotron 3.5 Super thought
ends in an answer
Super's requests take its owner's route, so the scheduler's continuation
(#2040, #2046) never reached them. Now:
- `nemotron_h_omni`'s exit is `` alone: Super's pinned template
writes "\n" + reasoning + "" + content, nothing around the
marker (`` is an added token, 13, special: false). On by default,
subject to the A/B.
- NemotronSuperRequestPlan.exitThinking(promptTokens:tokenizer:) resolves it
from the rendered text prompt (never with logprobs or media), and the
route passes it in the request's guard (`loopGuard(exitThinking:)`).
- NemotronSuperLocalBinding.executeBridge continues the answer as the
scheduler does (LoopExitThinkingContinuation), within the same admitted
request and on the same bridge: it waits for the stopped row's slot
(waitForRowRelease, 5 s), submits the prompt + the row's tokens +
`` with the budget the row left (at most 8,192), its own usage
signal (its matched stop becomes the request's) and a plain guard
(GenerationLoopGuard.withoutExit(), so a loop in the answer still ends
`length`). A cancel stops whichever row runs, and the request waits for
both rows' terminal observations. Never on a pair.
- Docs (loop guard section) and a changelog fragment.
Co-Authored-By: Claude Opus 5.5
---
changelog.d/loop-guard-exit-thinking-super.md | 5 ++
docs/architecture/inference.md | 8 +-
.../Bridge/NemotronSuperLocalBinding.swift | 74 ++++++++++++++++++-
.../GenerationLoopExitThinking.swift | 8 +-
.../Streaming/GenerationLoopGuard.swift | 7 ++
.../Server/NemotronSuperLocalImageHTTP.swift | 3 +-
6 files changed, 97 insertions(+), 8 deletions(-)
create mode 100644 changelog.d/loop-guard-exit-thinking-super.md
diff --git a/changelog.d/loop-guard-exit-thinking-super.md b/changelog.d/loop-guard-exit-thinking-super.md
new file mode 100644
index 0000000000..d04abda4e5
--- /dev/null
+++ b/changelog.d/loop-guard-exit-thinking-super.md
@@ -0,0 +1,5 @@
+### A Nemotron 3.5 Super thought that repeats itself verbatim now ends in an answer
+
+- As for Gemma 4 and the Qwen 3.5/3.6 35B models: when the loop guard stops a verbatim loop inside Super's thought, the request no longer ends as `length` with no answer. The provider ends the thought (``, as Super's template does), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
+- Since 0.10.12, 3.0 % of GPQA-shaped Super requests ended that way with no answer.
+- On by default for `nemotron_h_omni`. Never with logprobs, media or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text,qwen3_5_moe` leaves Super's off; `0` turns all of them off.
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index 94ef609dcf..60427d3a7a 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -3294,7 +3294,13 @@ stops such a row early.
its text. `DARKBLOOM_LOOP_EXIT_THINKING=0` (or `off`)
turns it off; a comma-separated list keeps it to the listed `model_type`s
that have a marker (`gemma4,gemma4_text` keeps Gemma's alone;
- `gemma4,gemma4_text,qwen3_5_moe,qwen3_5` adds the 9B and Qwen 3.8 27B). `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
+ `gemma4,gemma4_text,qwen3_5_moe,qwen3_5` adds the 9B and Qwen 3.8 27B).
+ Nemotron 3.5 Super (`nemotron_h_omni`, on by default) takes its owner's own
+ route: its request plan resolves the exit from the rendered prompt
+ (`NemotronSuperRequestPlan.exitThinking`; the exit is `` alone, as its
+ template writes a thought) and `NemotronSuperLocalBinding` continues the
+ answer the same way, within the same admitted request, then waits for both
+ rows' terminal observations. `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
to the launchd daemon (`LaunchAgent.inferencePassthroughEnvKeys`). One `darkbloom.loop-guard.exit-thinking` line per ended
thought gives the outcome.
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift
index e4020a6b65..2029f84499 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift
@@ -6,6 +6,35 @@ import Foundation
/// come from the existing atomic provider acquire path after its container/bridge builder
/// has gained a qualified Super adapter. Installing SDK weights alone cannot provide it.
/// This type neither loads weights nor manufactures admission, trust, or registry entries.
+private extension ChatCompletionRequest {
+ /// The same request with another output budget.
+ func withMaxTokens(_ maxTokens: Int) -> ChatCompletionRequest {
+ ChatCompletionRequest(
+ model: model, messages: messages, temperature: temperature, top_p: top_p, top_k: top_k,
+ max_tokens: maxTokens, repetition_penalty: repetition_penalty, presence_penalty: presence_penalty,
+ frequency_penalty: frequency_penalty, stream: stream, stop: stop, seed: seed, tools: tools,
+ tool_choice: tool_choice, response_format: response_format, user: user,
+ prompt_cache_key: prompt_cache_key, logit_bias: logit_bias, logprobs: logprobs,
+ top_logprobs: top_logprobs, min_p: min_p)
+ }
+}
+
+/// Cancels the request's running row: the first, or once a continuation can
+/// start, both (`LoopExitThinkingContinuation.splice`'s cancel).
+private final class RowCancel: @unchecked Sendable {
+ private let lock = NSLock()
+ private var action: @Sendable () async -> Void
+
+ init(_ action: @escaping @Sendable () async -> Void) { self.action = action }
+
+ func replace(with action: @escaping @Sendable () async -> Void) { lock.withLock { self.action = action } }
+
+ func run() async {
+ let action = lock.withLock { self.action }
+ await action()
+ }
+}
+
actor NemotronSuperLocalBinding {
/// The qualification hook's model id; a managed slot serves its registry id.
static let modelID = "nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4"
@@ -62,7 +91,9 @@ actor NemotronSuperLocalBinding {
/// receives the engine's prefix-cache outcome and drives its receipts;
/// `donationDemand` is the coordinator's fleet repeat hint for a durable
/// checkpoint write (nil: write). `loopGuard` stops a row that repeats
- /// verbatim (`NemotronSuperRequestPlan.loopGuard()`; nil: none).
+ /// verbatim (`NemotronSuperRequestPlan.loopGuard()`; nil: none); one that
+ /// carries an exit continues a thought it stopped as the scheduler's text
+ /// path does (`LoopExitThinkingContinuation`), within this request.
func run(request: ChatCompletionRequest, promptTokens: [Int],
hasMedia: Bool = false, cacheScope: String? = "", logprobs: EngineV2LogprobsChannel? = nil,
usageSignal: EngineV2RequestUsageSignal? = nil,
@@ -183,11 +214,45 @@ actor NemotronSuperLocalBinding {
onEvent: @escaping @Sendable (GenerationEvent) async -> Void
) async throws {
let usage = usageSignal ?? EngineV2RequestUsageSignal()
+ // A usage signal belongs to one engine request: a continuation has its own.
+ let continuationUsage = EngineV2RequestUsageSignal()
+ let cancel = RowCancel { await bridge.cancel(requestId: requestID) }
await withTaskCancellationHandler {
- let stream = await bridge.submitTokenized(
+ var stream = await bridge.submitTokenized(
promptTokens: tokens, request: request, requestId: requestID,
cacheScope: cacheScope ?? "", cacheEnabled: cacheScope != nil,
usageSignal: usage, donationDemand: donationDemand, loopGuard: loopGuard)
+ if let loopGuard, let exit = loopGuard.exitThinking, !(await bridge.servesDistributedPair) {
+ let continuationID = requestID + "-exit"
+ let spliced = LoopExitThinkingContinuation.splice(
+ first: stream,
+ cancelFirst: { await bridge.cancel(requestId: requestID) },
+ exit: exit,
+ promptTokens: tokens,
+ outputBudget: bridge.outputTokens(requested: request.max_tokens, promptTokens: tokens.count),
+ submit: { continuationPrompt, budget in
+ guard await bridge.waitForRowRelease(requestId: requestID, within: .seconds(5)) else {
+ throw LoopExitThinkingContinuation.RowNotReleased()
+ }
+ return await bridge.submitTokenized(
+ promptTokens: continuationPrompt, request: request.withMaxTokens(budget),
+ requestId: continuationID,
+ cacheScope: cacheScope ?? "", cacheEnabled: cacheScope != nil,
+ usageSignal: continuationUsage, donationDemand: donationDemand,
+ loopGuard: loopGuard.withoutExit())
+ },
+ cancelContinuation: { await bridge.cancel(requestId: continuationID) },
+ onOutcome: { outcome in
+ if case .continued = outcome {
+ usage.record(matchedStopSequence: continuationUsage.matchedStopSequence)
+ }
+ LoopExitThinkingContinuation.logger.notice(
+ "loop guard ended a thought", metadata: [
+ "request_id": .string(requestID), "outcome": .string(outcome.description)])
+ })
+ stream = spliced.events
+ cancel.replace(with: spliced.cancel)
+ }
for await event in stream {
if Task.isCancelled { break }
// The bridge yields a delta's entries just before its text;
@@ -195,11 +260,12 @@ actor NemotronSuperLocalBinding {
if case .logprobs(let entries) = event { logprobs?.append(entries); continue }
await onEvent(event)
}
- if Task.isCancelled { await bridge.cancel(requestId: requestID) }
+ if Task.isCancelled { await cancel.run() }
// A terminal event alone does not prove pump/native cleanup has completed.
await usage.waitForTerminalObservation()
+ await continuationUsage.waitForTerminalObservation()
} onCancel: {
- Task { await bridge.cancel(requestId: requestID) }
+ Task { await cancel.run() }
}
try Task.checkCancellation()
}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
index 9365872f82..ae4f092b58 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
@@ -91,7 +91,9 @@ public final class GenerationLoopExitRecord: @unchecked Sendable {
/// Qwen 3.8 27B, whose thought loops are rare. The guard keeps ending every
/// other loop as `length`: a loop outside the thought, a family that is not
/// on, a request that asked for logprobs (the forced tokens have none), a
-/// pair's request.
+/// pair's request. Nemotron 3.5 Super (`nemotron_h_omni`) takes its owner's
+/// own route (`NemotronSuperLocalBinding`), which continues the answer the
+/// same way.
///
/// `DARKBLOOM_LOOP_EXIT_THINKING`: unset, `1` or `on` keeps the default list;
/// `0` or `off` turns it off; any other value is the comma-separated list of
@@ -114,13 +116,15 @@ enum GenerationLoopExitThinkingPolicy {
"gemma4_text": .init(open: "<|channel>", close: ""),
"qwen3_5": qwenThink,
"qwen3_5_moe": qwenThink,
+ // Super's template writes `reasoning + "" + content`: nothing around the marker.
+ "nemotron_h_omni": .init(open: "", close: ""),
]
/// As the Qwen 3.5/3.6 template writes a closed thought:
/// `\n…\n\n\n` before the answer.
static let qwenThink = Markers(open: "", close: "", before: "\n", after: "\n\n")
- static let defaultModelTypes: Set = ["gemma4", "gemma4_text", "qwen3_5_moe"]
+ static let defaultModelTypes: Set = ["gemma4", "gemma4_text", "qwen3_5_moe", "nemotron_h_omni"]
/// The answer's own cap. Gemma's GPQA answers after a thought are under
/// 1,000 tokens; a Tau2 reply or call is shorter.
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift
index 297c03538c..98f33eea2c 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuard.swift
@@ -51,6 +51,13 @@ public struct GenerationLoopGuard: Sendable {
self.insideThinking = exitThinking?.startsInside ?? false
}
+ /// A fresh guard for the same request without the exit: the continuation's,
+ /// so a loop in the answer still ends as `length`.
+ func withoutExit() -> GenerationLoopGuard {
+ GenerationLoopGuard(modelType: modelType, toolCallMarkers: toolCallMarkers,
+ thresholds: detector.thresholds)
+ }
+
/// One delta of the row: its text and the tokens behind it. Returns the
/// detection that should stop the row, at most once.
mutating func observe(text: String, tokens: [Int]) -> GenerationLoopDetector.Detection? {
diff --git a/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift b/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift
index 482054add8..22238e19af 100644
--- a/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift
+++ b/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift
@@ -179,7 +179,8 @@ private struct SuperHTTPEngine: MLXServerEngine {
let translated = plan.bridgeRequest
let cacheScope = self.cacheScope, usageSignal = self.usageSignal ?? EngineV2RequestUsageSignal()
let donationDemand = self.donationDemand
- let loopGuard = plan.loopGuard()
+ let loopGuard = plan.loopGuard(
+ exitThinking: plan.exitThinking(promptTokens: tokens, tokenizer: tokenizer.inner))
textUsage = usageSignal
execute = { onEvent in
try await binding.run(request: translated, promptTokens: tokens,
From 251b698f1435ce6c87aba583553fe86647da53f8 Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Fri, 13 Nov 2026 00:20:31 -0800
Subject: [PATCH 07/14] test(provider): exit-thinking for Qwen is listed but
off by default (red)
The A/B (Mac B, signed 0.10.12 vs this branch) found too few Qwen thought
loops to show rescues: Qwen 3.6 never looped in 198 greedy GPQA draws, nor in
135 at T 0.5; Qwen 3.5 35B looped on 3 of 198 greedy draws, and of those only
one looped again on the candidate, whose answer then looped too. Corrected
production rates (the guard's stops only; cut-short streams were counted
before): Qwen 3.6 1.6 and Qwen 3.5 35B 8.3 per 1,000 GPQA-shaped requests.
So per the D1 rule (default-on only per the A/B), Qwen's exit stays listed
and off by default; the env list turns it on.
Red tests and the API they need, with no behaviour yet:
- The default list leaves `qwen3_5_moe` (and `qwen3_5`) off; the env list
turns it on.
- Served: Qwen 3.5/3.6 keep today's `length` by default.
- MultiModelBatchSchedulerEngine.exitThinkingSetting (the process's
DARKBLOOM_LOOP_EXIT_THINKING unless a test sets it): the Qwen serving
tests turn Qwen's exit on through it.
Co-Authored-By: Claude Opus 5.5
---
.../MultiModelBatchSchedulerEngine.swift | 3 ++
...nerationLoopExitThinkingServingTests.swift | 29 ++++++++++++++-----
.../GenerationLoopExitThinkingTests.swift | 24 ++++++++++-----
3 files changed, 42 insertions(+), 14 deletions(-)
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
index 3acf8dcb9c..b3d068db81 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
@@ -119,6 +119,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
/// `prompt_tokens_details.cached_tokens` into the trailing SSE usage
/// chunk. Same out-of-band pattern as `engineV2Logprobs`.
private let engineV2Usage: EngineV2RequestUsageSignal?
+ /// Which families may end a repeating thought (`GenerationLoopExitThinkingPolicy`):
+ /// the process's `DARKBLOOM_LOOP_EXIT_THINKING` unless a test sets it.
+ var exitThinkingSetting = GenerationLoopExitThinkingPolicy.current
/// Per-request logprobs plumbing. Non-nil means the sealed request asked for
/// logprobs: the v2 translation flips `logprobs`/`top_logprobs` on so
/// the engine captures them, and the bridge yields OpenAI-shaped entries
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
index 4515520de2..e6ea3dc41f 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
@@ -248,17 +248,22 @@ struct GenerationLoopExitThinkingServingTests {
}
}
+ /// Qwen's exit is listed but off by default: the Qwen tests turn it on.
+ private static let qwenOn = GenerationLoopExitThinkingPolicy.Setting.modelTypes(
+ GenerationLoopExitThinkingPolicy.defaultModelTypes.union(["qwen3_5_moe"]))
+
private func serve(
_ engine: ThoughtLoopCBv2Engine, served: Served = Served(), maxTokens: Int = 8_192, extra: String = "",
- usage: EngineV2RequestUsageSignal? = nil
+ usage: EngineV2RequestUsageSignal? = nil, exitThinking: GenerationLoopExitThinkingPolicy.Setting? = nil
) async throws -> Outcome {
let telemetry = TelemetrySink()
let bridge = EngineV2Bridge(engine: engine, modelId: served.modelID, tokenizer: served.tokenizer,
eosTokenIds: served.eosTokenIds, defaultMaxTokens: 64,
maxConcurrentRequests: 1, emitTelemetry: { telemetry.add($0) })
- let scheduler = MultiModelBatchSchedulerEngine(registryProvider: {
+ var scheduler = MultiModelBatchSchedulerEngine(registryProvider: {
[served.modelID: .init(tokenizer: served.tokenizer, modelType: served.modelType, engineV2Bridge: bridge)]
}, engineV2Usage: usage)
+ if let exitThinking { scheduler.exitThinkingSetting = exitThinking }
var outcome = try await consume(scheduler, served: served, maxTokens: maxTokens, extra: extra)
await bridge.shutdown()
outcome.loopGuardStops = telemetry.loopGuardStops
@@ -397,7 +402,7 @@ struct GenerationLoopExitThinkingServingTests {
@Test("Qwen 3.6: a loop inside the thought ends it with `\\n\\n\\n`, and stops apply to the answer")
func qwenThoughtLoopEndsInAnAnswer() async throws {
let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, family: .qwen)
- let outcome = try await serve(engine, served: Self.qwen)
+ let outcome = try await serve(engine, served: Self.qwen, exitThinking: Self.qwenOn)
#expect(outcome.error == nil)
#expect(engine.cancelCount == 1)
let requests = engine.requests
@@ -426,7 +431,7 @@ struct GenerationLoopExitThinkingServingTests {
@Test("Qwen 3.6: a loop in the answer, after ``, still ends as length")
func qwenAnswerLoopEndsAsLength() async throws {
let engine = ThoughtLoopCBv2Engine(loopInsideThought: false, family: .qwen)
- let outcome = try await serve(engine, served: Self.qwen)
+ let outcome = try await serve(engine, served: Self.qwen, exitThinking: Self.qwenOn)
#expect(outcome.error == nil)
#expect(engine.requests.count == 1)
#expect(outcome.info?.stopReason == "length")
@@ -437,7 +442,8 @@ struct GenerationLoopExitThinkingServingTests {
func qwenStopInTheAnswer() async throws {
let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, family: .qwen)
let usage = EngineV2RequestUsageSignal()
- let outcome = try await serve(engine, served: Self.qwen, extra: #","stop":["B"]"#, usage: usage)
+ let outcome = try await serve(engine, served: Self.qwen, extra: #","stop":["B"]"#, usage: usage,
+ exitThinking: Self.qwenOn)
#expect(outcome.error == nil)
#expect(engine.requests.count == 2)
#expect(engine.requests.last?.stopStrings == ["B"])
@@ -446,13 +452,22 @@ struct GenerationLoopExitThinkingServingTests {
#expect(usage.matchedStopSequence == "B")
}
- @Test("Qwen 3.8 27B shares `qwen3_5` with the 9B and keeps today's length by default")
+ @Test("Qwen 3.5/3.6 35B keep today's length by default: the exit is listed, not on")
+ func qwenKeepsLengthByDefault() async throws {
+ let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, family: .qwen)
+ let outcome = try await serve(engine, served: Self.qwen)
+ #expect(engine.requests.count == 1)
+ #expect(outcome.info?.stopReason == "length")
+ #expect(outcome.loopGuardStops == [false])
+ }
+
+ @Test("Qwen 3.8 27B shares `qwen3_5` with the 9B and keeps today's length")
func qwen38KeepsLength() async throws {
let engine = ThoughtLoopCBv2Engine(loopInsideThought: true, family: .qwen)
var served = Self.qwen
served.modelID = "EigenLabs/Qwen3.8-27B-4bit-mtp"
served.modelType = "qwen3_5"
- let outcome = try await serve(engine, served: served)
+ let outcome = try await serve(engine, served: served, exitThinking: Self.qwenOn)
#expect(engine.requests.count == 1)
#expect(outcome.info?.stopReason == "length")
#expect(outcome.loopGuardStops == [false])
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
index 69950eb524..6b8291d175 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
@@ -232,10 +232,15 @@ struct GenerationLoopExitThinkingTests {
private static let qwen = QwenByteTestTokenizer()
private static let qwenThinking = QwenByteTestTokenizer.tokens(QwenByteTestTokenizer.prompt(thinking: true))
- private func qwenExit(_ modelType: String = "qwen3_5_moe") -> GenerationLoopExitThinking? {
+ /// Qwen's exit is listed but off by default: these tests turn it on.
+ private static let qwenOn = GenerationLoopExitThinkingPolicy.Setting.modelTypes(
+ GenerationLoopExitThinkingPolicy.defaultModelTypes.union(["qwen3_5_moe"]))
+
+ private func qwenExit(_ modelType: String = "qwen3_5_moe",
+ setting: GenerationLoopExitThinkingPolicy.Setting = Self.qwenOn) -> GenerationLoopExitThinking? {
GenerationLoopExitThinkingPolicy.resolve(
modelType: modelType, tokenizer: Self.qwen, promptTokens: Self.qwenThinking, logprobs: false,
- setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes))
+ setting: setting)
}
@Test("Qwen 3.5/3.6 end the thought as their template does: `\\n\\n\\n`, the marker as its own token")
@@ -250,8 +255,13 @@ struct GenerationLoopExitThinkingTests {
// The served template opens the thought in the prompt.
#expect(exit.startsInside)
}
- // On by default for the two 35B models (`qwen3_5_moe`) only: `qwen3_5`
- // also covers Qwen 3.8 27B, whose loops are rare, and the 9B was not A/B'd.
+ // Off by default (the A/B found too few Qwen loops to show rescues):
+ // the env list turns the 35B models (`qwen3_5_moe`) on. `qwen3_5` also
+ // covers Qwen 3.8 27B.
+ let defaults = GenerationLoopExitThinkingPolicy.Setting.modelTypes(
+ GenerationLoopExitThinkingPolicy.defaultModelTypes)
+ #expect(qwenExit("qwen3_5_moe", setting: defaults) == nil)
+ #expect(qwenExit("qwen3_5", setting: defaults) == nil)
#expect(qwenExit("qwen3_5_moe") != nil)
#expect(qwenExit("qwen3_5") == nil)
// A prompt whose earlier turns closed their thoughts still opens this one.
@@ -260,7 +270,7 @@ struct GenerationLoopExitThinkingTests {
+ "<|im_start|>assistant\n\n")
#expect(GenerationLoopExitThinkingPolicy.resolve(
modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: history, logprobs: false,
- setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes))?.startsInside == true)
+ setting: Self.qwenOn)?.startsInside == true)
let closed = QwenByteTestTokenizer.tokens(QwenByteTestTokenizer.prompt(thinking: false))
#expect(GenerationLoopExitThinkingPolicy.resolve(
modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: closed, logprobs: false,
@@ -299,7 +309,7 @@ struct GenerationLoopExitThinkingTests {
let closedPrompt = QwenByteTestTokenizer.tokens(QwenByteTestTokenizer.prompt(thinking: false))
let exit = try #require(GenerationLoopExitThinkingPolicy.resolve(
modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: closedPrompt, logprobs: false,
- setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes)))
+ setting: Self.qwenOn))
#expect(!exit.startsInside)
var reopened = GenerationLoopGuard(
modelType: "qwen3_5_moe", toolCallMarkers: GenerationLoopGuardPolicy.genericToolCallMarkers, exitThinking: exit)
@@ -369,7 +379,7 @@ struct GenerationLoopExitThinkingTests {
}
#expect(GenerationLoopExitThinkingPolicy.resolve(
modelType: "qwen3_5_moe", tokenizer: Prefixing(), promptTokens: Self.qwenThinking, logprobs: false,
- setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes)) == nil)
+ setting: Self.qwenOn) == nil)
}
@Test("darkbloom start passes the loop guard's and the exit's switches to the launchd daemon")
From 2b3c7a7c5d4b5d221e2ea3a2c1baf889fd2cae4d Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Fri, 13 Nov 2026 00:20:31 -0800
Subject: [PATCH 08/14] feat(provider): exit-thinking for Qwen: off by default,
per the A/B
- GenerationLoopExitThinkingPolicy.defaultModelTypes is gemma4, gemma4_text:
Qwen 3.5/3.6 (`qwen3_5_moe`, `qwen3_5`) keep their marker and exit, off by
default. DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text,qwen3_5_moe turns
it on for the 35B models; ...,qwen3_5 adds the 9B and Qwen 3.8 27B.
- The scheduler resolves the exit with its `exitThinkingSetting`.
- Docs and the changelog fragment (with the corrected production rates:
0.16 % for Qwen 3.6, 0.83 % for Qwen 3.5 35B).
Co-Authored-By: Claude Opus 5.5
---
changelog.d/loop-guard-exit-thinking-qwen.md | 8 ++++----
docs/architecture/inference.md | 5 +++--
.../Scheduler/MultiModelBatchSchedulerEngine.swift | 2 +-
.../Streaming/GenerationLoopExitThinking.swift | 14 +++++++-------
4 files changed, 15 insertions(+), 14 deletions(-)
diff --git a/changelog.d/loop-guard-exit-thinking-qwen.md b/changelog.d/loop-guard-exit-thinking-qwen.md
index 8109da61fb..c7c01f30ab 100644
--- a/changelog.d/loop-guard-exit-thinking-qwen.md
+++ b/changelog.d/loop-guard-exit-thinking-qwen.md
@@ -1,6 +1,6 @@
-### A Qwen 3.5 or 3.6 35B thought that repeats itself verbatim now ends in an answer
+### A Qwen 3.5 or 3.6 thought that repeats itself verbatim can end in an answer (off by default)
-- As for Gemma 4 in 0.10.13: when the loop guard stops a verbatim loop inside a Qwen 3.5 or 3.6 35B thought, the request no longer ends as `length` with no answer. The provider ends the thought as Qwen's template does (`\n\n\n`), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
-- Since 0.10.12, 1.6–2.6 % of GPQA-shaped requests to these two models ended that way with no answer.
-- On by default for `qwen3_5_moe` (Qwen 3.5 35B, Qwen 3.6 35B). Not by default for `qwen3_5` (Qwen 3.5 9B, Qwen 3.8 27B). Never with logprobs or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text` keeps Gemma's alone; `gemma4,gemma4_text,qwen3_5_moe,qwen3_5` adds the 9B and Qwen 3.8 27B; `0` turns it off.
+- Once turned on, as for Gemma 4 in 0.10.13: when the loop guard stops a verbatim loop inside a Qwen 3.5 or 3.6 35B thought, the request no longer ends as `length` with no answer. The provider ends the thought as Qwen's template does (`\n\n\n`), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
+- Since 0.10.12, 0.16 % (Qwen 3.6 35B) and 0.83 % (Qwen 3.5 35B) of GPQA-shaped requests ended that way with no answer.
+- Off by default: the A/B on Qwen 3.5/3.6 35B found too few thought loops to show rescues (Qwen 3.6 never looped in 198 greedy GPQA draws; Qwen 3.5 35B looped 3 times, once on the candidate, whose answer looped again). `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text,qwen3_5_moe` turns it on for the 35B models; `…,qwen3_5` adds the 9B and Qwen 3.8 27B; `0` turns all of it off. Never with logprobs or on a cluster pair.
- Client stop strings apply to the answer from its first token, and a stop string that ends the answer is reported as the matched stop sequence (Gemma 4's too).
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index 94ef609dcf..16b5d5b413 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -3254,8 +3254,9 @@ stops such a row early.
the default list.
- **A loop inside a Gemma 4 or Qwen 3.5/3.6 35B thought ends the thought, not
the answer** (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`).
- For `gemma4`, `gemma4_text` and `qwen3_5_moe` (on by default) and `qwen3_5`
- (Qwen 3.5 9B and Qwen 3.8 27B: listed, off by default), the guard also
+ For `gemma4` and `gemma4_text` (on by default) and `qwen3_5_moe` (Qwen 3.5/3.6
+ 35B) and `qwen3_5` (Qwen 3.5 9B, Qwen 3.8 27B), listed and off by default (their
+ thought loops were too rare in the A/B to show rescues), the guard also
follows the thought channel (`<|channel>` … ``, `` …
``; the prompt's tail seeds the state: Qwen's served template opens
`` in the prompt) and records
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
index b3d068db81..fef26beae2 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
@@ -1028,7 +1028,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// single Mac's text row without logprobs (`GenerationLoopExitThinkingPolicy`).
var exitThinking = GenerationLoopExitThinkingPolicy.resolve(
modelType: modelType, tokenizer: tokenizer.inner, promptTokens: promptTokens,
- logprobs: engineV2Logprobs != nil)
+ logprobs: engineV2Logprobs != nil, setting: exitThinkingSetting)
if exitThinking != nil, await engineV2Bridge?.servesDistributedPair != false { exitThinking = nil }
let loopGuard = GenerationLoopGuardPolicy.resolve(
modelType: modelType, request: request, prepared: prepared, tokenConstraint: tokenConstraint,
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
index 9365872f82..cfdcbfcd65 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
@@ -85,12 +85,12 @@ public final class GenerationLoopExitRecord: @unchecked Sendable {
/// Which requests may end a repeating thought instead of the whole answer.
///
/// On by default for Gemma 4, whose thought closes with one special token
-/// (``), and the Qwen 3.5/3.6 35B models (`qwen3_5_moe`), whose
-/// template closes it with `\n\n\n` (`` is one special token).
-/// `qwen3_5` has the marker but is off by default: it is Qwen 3.5 9B and also
-/// Qwen 3.8 27B, whose thought loops are rare. The guard keeps ending every
-/// other loop as `length`: a loop outside the thought, a family that is not
-/// on, a request that asked for logprobs (the forced tokens have none), a
+/// (``). Qwen 3.5/3.6 (`qwen3_5_moe`, `qwen3_5`), whose template
+/// closes a thought with `\n\n\n` (`` is one special token),
+/// are listed but off by default: their thought loops were too rare in the A/B
+/// to show rescues, and `qwen3_5` is also Qwen 3.8 27B. The guard keeps ending
+/// every other loop as `length`: a loop outside the thought, a family that is
+/// not on, a request that asked for logprobs (the forced tokens have none), a
/// pair's request.
///
/// `DARKBLOOM_LOOP_EXIT_THINKING`: unset, `1` or `on` keeps the default list;
@@ -120,7 +120,7 @@ enum GenerationLoopExitThinkingPolicy {
/// `\n…\n\n\n` before the answer.
static let qwenThink = Markers(open: "", close: "", before: "\n", after: "\n\n")
- static let defaultModelTypes: Set = ["gemma4", "gemma4_text", "qwen3_5_moe"]
+ static let defaultModelTypes: Set = ["gemma4", "gemma4_text"]
/// The answer's own cap. Gemma's GPQA answers after a thought are under
/// 1,000 tokens; a Tau2 reply or call is shorter.
From e40e4d12312cca4ad35148a775391187b3536402 Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Fri, 13 Nov 2026 00:21:07 -0800
Subject: [PATCH 09/14] test(provider): Super's exit-thinking, the review's
findings (red)
A fresh-context review of #2061 (REQUEST CHANGES) found:
- 1 (blocker): on by default for all Super traffic before its A/B. Super's
continuation re-prefills a 120B hybrid model's whole thought, and its
answer quality and pause are unmeasured.
- 2 (major): a cancel or drain during the hand-off (the stopped row's
release wait, the submission) could return the owner's admission before
the second row was submitted: the splice's task was not joined, and a
continuation submitted after the cancel was cancelled only later.
- 3 (minor): the tests overwrote the terminal (one `info` not checked), and
did not cover the answer loop or thinking off on Super's route, the real
`` id (13), or the sampling the continuation keeps.
Red tests and the API they need, with no behaviour yet:
- Super's exit is listed but off by default; the env list turns it on.
- On the binding: one terminal `info`; the continuation keeps temperature,
seed, top-p/k and penalties; Super's real ids (`` 13); with the
exit on, a loop in the answer or after a thinking-off prompt still ends
`length` with one submission.
- The splice: a cancel during the hand-off starts no continuation, and
`finished` (new; a stub here) returns only once the submission returned
and was cancelled.
Co-Authored-By: Claude Opus 5.5
---
.../LoopExitThinkingContinuation.swift | 8 +-
.../LoopExitThinkingContinuationTests.swift | 74 ++++++++++++++-
.../NemotronSuperLoopGuardTests.swift | 92 +++++++++++++++----
3 files changed, 151 insertions(+), 23 deletions(-)
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
index 683e9b4538..98da0f2073 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
@@ -61,7 +61,8 @@ enum LoopExitThinkingContinuation {
/// worth it: the request ends as `length`, as before.
static let minimumAnswerBudget = 256
- /// The spliced stream and its cancel, which stops whichever row is running.
+ /// The spliced stream; its cancel, which stops whichever row is running;
+ /// and `finished`, which returns once the splice is over.
static func splice(
first: AsyncStream,
cancelFirst: @escaping @Sendable () async -> Void,
@@ -71,7 +72,8 @@ enum LoopExitThinkingContinuation {
submit: @escaping Submit,
cancelContinuation: @escaping @Sendable () async -> Void,
onOutcome: (@Sendable (Outcome) -> Void)? = nil
- ) -> (events: AsyncStream, cancel: @Sendable () async -> Void) {
+ ) -> (events: AsyncStream, cancel: @Sendable () async -> Void,
+ finished: @Sendable () async -> Void) {
let (events, out) = AsyncStream.makeStream()
let control = Control()
let task = Task {
@@ -90,7 +92,7 @@ enum LoopExitThinkingContinuation {
task.cancel()
Task { await cancel() }
}
- return (events, cancel)
+ return (events, cancel, {})
}
private static func run(
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
index a8aa567c1a..1fcf31b446 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift
@@ -26,6 +26,52 @@ struct LoopExitThinkingContinuationTests {
private struct Refused: Error {}
+ /// Holds a submission until released.
+ private final class HandOffGate: @unchecked Sendable {
+ private let lock = NSLock()
+ private var entered = false
+ private var released = false
+ private var enteredWaiters: [CheckedContinuation] = []
+ private var releaseWaiters: [CheckedContinuation] = []
+
+ func enterAndWait() async {
+ let waiters = lock.withLock { () -> [CheckedContinuation] in
+ entered = true
+ defer { enteredWaiters.removeAll() }
+ return enteredWaiters
+ }
+ waiters.forEach { $0.resume() }
+ await withCheckedContinuation { continuation in
+ let now = lock.withLock { () -> Bool in
+ if released { return true }
+ releaseWaiters.append(continuation)
+ return false
+ }
+ if now { continuation.resume() }
+ }
+ }
+
+ func waitUntilEntered() async {
+ await withCheckedContinuation { continuation in
+ let now = lock.withLock { () -> Bool in
+ if entered { return true }
+ enteredWaiters.append(continuation)
+ return false
+ }
+ if now { continuation.resume() }
+ }
+ }
+
+ func release() {
+ let waiters = lock.withLock { () -> [CheckedContinuation] in
+ released = true
+ defer { releaseWaiters.removeAll() }
+ return releaseWaiters
+ }
+ waiters.forEach { $0.resume() }
+ }
+ }
+
private final class Seen: @unchecked Sendable {
private let lock = NSLock()
private var events = 0
@@ -68,7 +114,8 @@ struct LoopExitThinkingContinuationTests {
private func splice(
first: AsyncStream, exit: GenerationLoopExitThinking, outputBudget: Int = 8_192,
calls: Calls, continuation: @escaping @Sendable () throws -> AsyncStream
- ) -> (events: AsyncStream, cancel: @Sendable () async -> Void) {
+ ) -> (events: AsyncStream, cancel: @Sendable () async -> Void,
+ finished: @Sendable () async -> Void) {
LoopExitThinkingContinuation.splice(
first: first, cancelFirst: { calls.cancelFirst() }, exit: exit, promptTokens: Self.prompt,
outputBudget: outputBudget,
@@ -304,6 +351,31 @@ struct LoopExitThinkingContinuationTests {
#expect(terminal == ["chunk:", "chunk:A", "info:5/4203/length"])
}
+ @Test("a cancel during the hand-off starts no continuation, and the splice's end waits for the submission")
+ func cancelDuringHandOff() async throws {
+ let calls = Calls()
+ let gate = HandOffGate()
+ let first = stream([.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")])
+ let spliced = LoopExitThinkingContinuation.splice(
+ first: first, cancelFirst: { calls.cancelFirst() }, exit: exit(requested: true, tokens: thought),
+ promptTokens: Self.prompt, outputBudget: 8_192,
+ submit: { prompt, maxTokens in
+ // The owner's hand-off (the row's release, the submission) is still running.
+ await gate.enterAndWait()
+ calls.submit(prompt, maxTokens)
+ return self.stream([.chunk("never")], finish: false)
+ },
+ cancelContinuation: { calls.cancelContinuation() })
+ await gate.waitUntilEntered()
+ await spliced.cancel()
+ gate.release()
+ await spliced.finished()
+ // The submission returned after the cancel: it was cancelled before the splice ended.
+ #expect(calls.submits.count == 1)
+ #expect(calls.cancels.continuation == 1)
+ #expect(await drain(spliced.events) == ["info:5/4200/length"])
+ }
+
@Test("a cancel before the continuation starts keeps it from starting")
func cancelBeforeStart() async {
let calls = Calls()
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift
index a366b2eac2..f441458ffd 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift
@@ -63,12 +63,12 @@ private final class SuperLoopingEngine: CBv2Engine, @unchecked Sendable {
func shutdown() async {}
}
-/// Super's markers in a byte-spelled test vocabulary below Super's 131,072
-/// (the binding refuses ids outside it).
+/// Super's markers at their real ids (`<|im_end|>` 11, `` 12, ``
+/// 13) in a byte-spelled test vocabulary; the test text holds no byte 11-13.
private enum SuperThoughtVocabulary {
- static let think = 1012
- static let thinkClose = 1013
- static let imEnd = 1011
+ static let think = 12
+ static let thinkClose = 13
+ static let imEnd = 11
static let markers: [(String, Int)] = [("", think), ("", thinkClose), ("<|im_end|>", imEnd)]
static let tokenizer = GemmaThoughtTestTokenizer(markers: markers)
static func tokens(_ text: String) -> [Int] { GemmaThoughtTestTokenizer.tokens(text, markers: markers) }
@@ -84,6 +84,10 @@ private final class SuperThoughtLoopEngine: CBv2Engine, @unchecked Sendable {
private var continuations: [AsyncStream.Continuation] = []
private var submitted: [CBv2Request] = []
private var produced: [[Int]] = []
+ /// The row closes its thought first and loops in its answer.
+ let loopInAnswer: Bool
+
+ init(loopInAnswer: Bool = false) { self.loopInAnswer = loopInAnswer }
var requests: [CBv2Request] { lock.withLock { submitted } }
var outputs: [[Int]] { lock.withLock { produced } }
@@ -102,6 +106,10 @@ private final class SuperThoughtLoopEngine: CBv2Engine, @unchecked Sendable {
continuation.yield(.delta(text: text, tokens: tokens, logprobs: nil))
}
if index == 0 {
+ if loopInAnswer {
+ emit("ok.")
+ emit("")
+ }
let clause = Array("Wait, the reaction is: CO + Cu -> CO2 + Cu (No). ")
for position in 0..<4_200 { emit(String(clause[position % clause.count])) }
Task { [weak self] in
@@ -142,10 +150,13 @@ private actor SuperLoopEvents {
var stopReason: String?
var completionTokens = 0
var errors = 0
+ /// Terminal `info` events: a spliced answer has exactly one.
+ var infos = 0
func record(_ event: GenerationEvent) {
switch event {
case .chunk(let chunk): text += chunk
case .info(_, let completion, _, let reason):
+ infos += 1
stopReason = reason
completionTokens = completion
case .error, .terminal: errors += 1
@@ -228,24 +239,31 @@ struct NemotronSuperLoopGuardTests {
private static let exitDefaults = GenerationLoopExitThinkingPolicy.Setting.modelTypes(
GenerationLoopExitThinkingPolicy.defaultModelTypes)
+ /// Super's exit is listed but off by default until its A/B.
+ private static let exitOn = GenerationLoopExitThinkingPolicy.Setting.modelTypes(
+ GenerationLoopExitThinkingPolicy.defaultModelTypes.union(["nemotron_h_omni"]))
@Test("Super's exit is `` alone, as its template writes a thought; its prompt opens the thought")
func superExit() throws {
let plan = try plan()
+ // Off by default until its A/B.
+ #expect(plan.exitThinking(
+ promptTokens: SuperThoughtVocabulary.thinkingPrompt, tokenizer: SuperThoughtVocabulary.tokenizer,
+ setting: Self.exitDefaults) == nil)
let exit = try #require(plan.exitThinking(
promptTokens: SuperThoughtVocabulary.thinkingPrompt, tokenizer: SuperThoughtVocabulary.tokenizer,
- setting: Self.exitDefaults))
+ setting: Self.exitOn))
#expect(exit.exitTokens == [SuperThoughtVocabulary.thinkClose])
#expect(exit.exitText == "")
#expect(exit.startsInside)
// Thinking off: the prompt closed an empty thought.
let off = SuperThoughtVocabulary.tokens("<|im_start|>assistant\n")
#expect(plan.exitThinking(promptTokens: off, tokenizer: SuperThoughtVocabulary.tokenizer,
- setting: Self.exitDefaults)?.startsInside == false)
+ setting: Self.exitOn)?.startsInside == false)
// Never with logprobs; the env list can leave Super's off.
#expect(try self.plan(",\"logprobs\":true,\"top_logprobs\":2").exitThinking(
promptTokens: SuperThoughtVocabulary.thinkingPrompt, tokenizer: SuperThoughtVocabulary.tokenizer,
- setting: Self.exitDefaults) == nil)
+ setting: Self.exitOn) == nil)
#expect(plan.exitThinking(
promptTokens: SuperThoughtVocabulary.thinkingPrompt, tokenizer: SuperThoughtVocabulary.tokenizer,
setting: .modelTypes(["gemma4", "gemma4_text", "qwen3_5_moe"])) == nil)
@@ -254,9 +272,16 @@ struct NemotronSuperLoopGuardTests {
#expect(loopGuard.exitThinking?.record === exit.record)
}
- @Test("a repeating Super thought ends in an answer on the owner's route; a stop in the answer is the request's")
- func superThoughtLoopEndsInAnAnswer() async throws {
- let engine = SuperThoughtLoopEngine()
+ private struct Served {
+ let engine: SuperThoughtLoopEngine
+ let events: SuperLoopEvents
+ let usage: EngineV2RequestUsageSignal
+ let prompt: [Int]
+ }
+
+ /// One text request through the binding, with Super's exit on.
+ private func serveExit(_ engine: SuperThoughtLoopEngine, prompt: [Int] = SuperThoughtVocabulary.thinkingPrompt,
+ fields: String = "") async throws -> Served {
let modelID = NemotronSuperLocalBinding.modelID
let tokenizer = TokenizerHandle(SuperThoughtVocabulary.tokenizer)
let bridge = EngineV2Bridge(engine: engine, modelId: modelID, tokenizer: tokenizer,
@@ -265,30 +290,59 @@ struct NemotronSuperLoopGuardTests {
.init(tokenizer: tokenizer, releaseToken: OneShotRelease(release: { _ in }, modelId: model),
engineV2Bridge: bridge)
})
- let plan = try plan(#","stop":["B"]"#)
- let prompt = SuperThoughtVocabulary.thinkingPrompt
+ let plan = try plan(fields)
let exit = plan.exitThinking(promptTokens: prompt, tokenizer: SuperThoughtVocabulary.tokenizer,
- setting: Self.exitDefaults)
+ setting: Self.exitOn)
let usage = EngineV2RequestUsageSignal()
let events = SuperLoopEvents()
try await binding.run(request: plan.bridgeRequest, promptTokens: prompt, usageSignal: usage,
loopGuard: plan.loopGuard(setting: Self.defaults, exitThinking: exit),
onEvent: { await events.record($0) })
await bridge.shutdown()
- let requests = engine.requests
+ return Served(engine: engine, events: events, usage: usage, prompt: prompt)
+ }
+
+ @Test("a repeating Super thought ends in an answer on the owner's route; a stop in the answer is the request's")
+ func superThoughtLoopEndsInAnAnswer() async throws {
+ let served = try await serveExit(SuperThoughtLoopEngine(), fields: #","stop":["B"],"temperature":0.5,"seed":7"#)
+ let requests = served.engine.requests
#expect(requests.count == 2)
let first = try #require(requests.first)
let continuation = try #require(requests.last)
- let firstOutput = try #require(engine.outputs.first)
- // The same prompt, every token the row produced, then ``.
- #expect(continuation.promptTokens == first.promptTokens + firstOutput + [SuperThoughtVocabulary.thinkClose])
+ let firstOutput = try #require(served.engine.outputs.first)
+ // The same prompt, every token the row produced, then `` (13).
+ #expect(continuation.promptTokens == first.promptTokens + firstOutput + [13])
#expect(continuation.maxTokens == first.maxTokens - firstOutput.count - 1)
+ // The same sampling and stops.
#expect(continuation.stopStrings == ["B"])
+ #expect(continuation.sampling.temperature == 0.5)
+ #expect(continuation.sampling.seed == 7)
+ #expect(continuation.sampling.temperature == first.sampling.temperature)
+ #expect(continuation.sampling.topP == first.sampling.topP)
+ #expect(continuation.sampling.topK == first.sampling.topK)
+ #expect(continuation.sampling.presencePenalty == first.sampling.presencePenalty)
+ #expect(continuation.sampling.repetitionPenalty == first.sampling.repetitionPenalty)
+ let events = served.events
#expect(await events.errors == 0)
+ #expect(await events.infos == 1)
#expect(await events.text.hasSuffix("Answer: B"))
#expect(await events.stopReason == "stop")
#expect(await events.completionTokens == firstOutput.count + 1 + 9)
- #expect(usage.matchedStopSequence == "B")
+ #expect(served.usage.matchedStopSequence == "B")
+ }
+
+ @Test("with Super's exit on, a loop in the answer or after a thinking-off prompt still ends as length")
+ func superExitKeepsLengthOutsideTheThought() async throws {
+ let answer = try await serveExit(SuperThoughtLoopEngine(loopInAnswer: true))
+ #expect(answer.engine.requests.count == 1)
+ #expect(await answer.events.infos == 1)
+ #expect(await answer.events.stopReason == "length")
+
+ let thinkingOff = SuperThoughtVocabulary.tokens(
+ "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n")
+ let off = try await serveExit(SuperThoughtLoopEngine(), prompt: thinkingOff)
+ #expect(off.engine.requests.count == 1)
+ #expect(await off.events.stopReason == "length")
}
@Test("with the switch off the row runs to the engine's own end")
From de5c48374a61425e439ac89b781164e8e3e66744 Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Fri, 13 Nov 2026 01:05:53 -0800
Subject: [PATCH 10/14] test(provider): the Qwen thinking-off check turns
Qwen's exit on
With Qwen's exit off by default, the check that a thinking-off prompt starts
outside the thought must turn it on, as the other Qwen policy checks do.
Co-Authored-By: Claude Opus 5.5
---
.../Inference/Streaming/GenerationLoopExitThinkingTests.swift | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
index 6b8291d175..43f8852462 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingTests.swift
@@ -274,7 +274,7 @@ struct GenerationLoopExitThinkingTests {
let closed = QwenByteTestTokenizer.tokens(QwenByteTestTokenizer.prompt(thinking: false))
#expect(GenerationLoopExitThinkingPolicy.resolve(
modelType: "qwen3_5_moe", tokenizer: Self.qwen, promptTokens: closed, logprobs: false,
- setting: .modelTypes(GenerationLoopExitThinkingPolicy.defaultModelTypes))?.startsInside == false)
+ setting: Self.qwenOn)?.startsInside == false)
// Qwen 3.8 (`qwen4_exp`) is not listed: its thought loops are rare in production.
#expect(qwenExit("qwen4_exp") == nil)
// The env list still turns Qwen's off and keeps Gemma's.
From 47f665f7df2f8746c4d577bd3557af84a635e3c4 Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Fri, 13 Nov 2026 01:25:29 -0800
Subject: [PATCH 11/14] fix(provider): Super's exit-thinking, the review's
findings
- 1: Super's exit is listed but off by default until its A/B (Mac B, in
progress); DARKBLOOM_LOOP_EXIT_THINKING=...,nemotron_h_omni turns it on.
- 2: the splice returns `finished`, which joins its task; the Super binding
joins it before waiting for both rows' terminal observations, so a
continuation a cancel or drain overtook during the hand-off is cancelled
before the owner's admission returns. After the stopped row's release
wait, the hand-off checks the request's cancel (the binding's RowCancel,
the scheduler's task) and submits no second row.
- 4: Super's continuation is submitted with the request's prompt progress
and the owner's make-room hook cleared, as the scheduler's is.
- 7: the continuation's prompt passes the binding's own token checks.
- 6: the binding's type doc stays on the actor (helpers moved below it).
- 8: the docs note that the guard follows the last thought marker, Super's
reasoning channel the first ``.
- Docs and the changelog fragment (off by default).
Not here (listed in the PR): 5 (`answerFinished` set at the first row's
`length`; shared with #2040), 9 (the continuation's checkpoint writes),
outcome telemetry (#2040's F3).
Co-Authored-By: Claude Opus 5.5
---
changelog.d/loop-guard-exit-thinking-super.md | 6 +-
docs/architecture/inference.md | 13 ++-
.../Bridge/NemotronSuperLocalBinding.swift | 94 ++++++++++++-------
.../LoopExitThinkingContinuation.swift | 6 +-
.../MultiModelBatchSchedulerEngine.swift | 2 +
.../GenerationLoopExitThinking.swift | 8 +-
6 files changed, 81 insertions(+), 48 deletions(-)
diff --git a/changelog.d/loop-guard-exit-thinking-super.md b/changelog.d/loop-guard-exit-thinking-super.md
index d04abda4e5..8d7f81c2d4 100644
--- a/changelog.d/loop-guard-exit-thinking-super.md
+++ b/changelog.d/loop-guard-exit-thinking-super.md
@@ -1,5 +1,5 @@
-### A Nemotron 3.5 Super thought that repeats itself verbatim now ends in an answer
+### A Nemotron 3.5 Super thought that repeats itself verbatim can end in an answer (off by default)
-- As for Gemma 4 and the Qwen 3.5/3.6 35B models: when the loop guard stops a verbatim loop inside Super's thought, the request no longer ends as `length` with no answer. The provider ends the thought (``, as Super's template does), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
+- As for Gemma 4 and the Qwen 3.5/3.6 35B models, once turned on: when the loop guard stops a verbatim loop inside Super's thought, the request no longer ends as `length` with no answer. The provider ends the thought (``, as Super's template does), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
- Since 0.10.12, 3.0 % of GPQA-shaped Super requests ended that way with no answer.
-- On by default for `nemotron_h_omni`. Never with logprobs, media or on a cluster pair. `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text,qwen3_5_moe` leaves Super's off; `0` turns all of them off.
+- Off by default until its A/B: `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text,qwen3_5_moe,nemotron_h_omni` turns it on beside the default families; `0` turns all of them off. Never with logprobs, media or on a cluster pair.
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index 02551f08dd..53a9a491b7 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -3296,12 +3296,17 @@ stops such a row early.
turns it off; a comma-separated list keeps it to the listed `model_type`s
that have a marker (`gemma4,gemma4_text` keeps Gemma's alone;
`gemma4,gemma4_text,qwen3_5_moe,qwen3_5` adds the 9B and Qwen 3.8 27B).
- Nemotron 3.5 Super (`nemotron_h_omni`, on by default) takes its owner's own
- route: its request plan resolves the exit from the rendered prompt
+ Nemotron 3.5 Super (`nemotron_h_omni`: listed, off by default until its A/B;
+ `…,nemotron_h_omni` turns it on) takes its owner's own route: its request
+ plan resolves the exit from the rendered prompt
(`NemotronSuperRequestPlan.exitThinking`; the exit is `` alone, as its
template writes a thought) and `NemotronSuperLocalBinding` continues the
- answer the same way, within the same admitted request, then waits for both
- rows' terminal observations. `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
+ answer the same way, within the same admitted request. A cancel or drain
+ during the hand-off submits no second row; the request joins the splice and
+ then waits for both rows' terminal observations before the owner's admission
+ returns. The guard follows the last thought marker, Super's reasoning channel
+ the first ``: a model that writes `` in its answer and then
+ loops is continued, and its `` reaches the client as content. `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
to the launchd daemon (`LaunchAgent.inferencePassthroughEnvKeys`). One `darkbloom.loop-guard.exit-thinking` line per ended
thought gives the outcome.
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift
index 2029f84499..5844d3f9a2 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift
@@ -6,35 +6,6 @@ import Foundation
/// come from the existing atomic provider acquire path after its container/bridge builder
/// has gained a qualified Super adapter. Installing SDK weights alone cannot provide it.
/// This type neither loads weights nor manufactures admission, trust, or registry entries.
-private extension ChatCompletionRequest {
- /// The same request with another output budget.
- func withMaxTokens(_ maxTokens: Int) -> ChatCompletionRequest {
- ChatCompletionRequest(
- model: model, messages: messages, temperature: temperature, top_p: top_p, top_k: top_k,
- max_tokens: maxTokens, repetition_penalty: repetition_penalty, presence_penalty: presence_penalty,
- frequency_penalty: frequency_penalty, stream: stream, stop: stop, seed: seed, tools: tools,
- tool_choice: tool_choice, response_format: response_format, user: user,
- prompt_cache_key: prompt_cache_key, logit_bias: logit_bias, logprobs: logprobs,
- top_logprobs: top_logprobs, min_p: min_p)
- }
-}
-
-/// Cancels the request's running row: the first, or once a continuation can
-/// start, both (`LoopExitThinkingContinuation.splice`'s cancel).
-private final class RowCancel: @unchecked Sendable {
- private let lock = NSLock()
- private var action: @Sendable () async -> Void
-
- init(_ action: @escaping @Sendable () async -> Void) { self.action = action }
-
- func replace(with action: @escaping @Sendable () async -> Void) { lock.withLock { self.action = action } }
-
- func run() async {
- let action = lock.withLock { self.action }
- await action()
- }
-}
-
actor NemotronSuperLocalBinding {
/// The qualification hook's model id; a managed slot serves its registry id.
static let modelID = "nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4"
@@ -218,6 +189,7 @@ actor NemotronSuperLocalBinding {
let continuationUsage = EngineV2RequestUsageSignal()
let cancel = RowCancel { await bridge.cancel(requestId: requestID) }
await withTaskCancellationHandler {
+ var spliceFinished: (@Sendable () async -> Void)?
var stream = await bridge.submitTokenized(
promptTokens: tokens, request: request, requestId: requestID,
cacheScope: cacheScope ?? "", cacheEnabled: cacheScope != nil,
@@ -234,12 +206,24 @@ actor NemotronSuperLocalBinding {
guard await bridge.waitForRowRelease(requestId: requestID, within: .seconds(5)) else {
throw LoopExitThinkingContinuation.RowNotReleased()
}
- return await bridge.submitTokenized(
- promptTokens: continuationPrompt, request: request.withMaxTokens(budget),
- requestId: continuationID,
- cacheScope: cacheScope ?? "", cacheEnabled: cacheScope != nil,
- usageSignal: continuationUsage, donationDemand: donationDemand,
- loopGuard: loopGuard.withoutExit())
+ // A request cancelled or drained during the wait gets no second row.
+ guard !cancel.cancelled else { throw CancellationError() }
+ // As `run` checks the first prompt.
+ guard !continuationPrompt.contains(18),
+ continuationPrompt.allSatisfy({ (0..<131072).contains($0) })
+ else { throw Failure.invalidTokens }
+ // As the scheduler's continuation: the request's prompt progress
+ // has ended, and the owner's make-room hook is the first row's.
+ return await LocalPrefillProgress.$current.withValue(nil) {
+ await MeFirstOwnerRequest.$makeRoom.withValue(nil) {
+ await bridge.submitTokenized(
+ promptTokens: continuationPrompt, request: request.withMaxTokens(budget),
+ requestId: continuationID,
+ cacheScope: cacheScope ?? "", cacheEnabled: cacheScope != nil,
+ usageSignal: continuationUsage, donationDemand: donationDemand,
+ loopGuard: loopGuard.withoutExit())
+ }
+ }
},
cancelContinuation: { await bridge.cancel(requestId: continuationID) },
onOutcome: { outcome in
@@ -252,6 +236,7 @@ actor NemotronSuperLocalBinding {
})
stream = spliced.events
cancel.replace(with: spliced.cancel)
+ spliceFinished = spliced.finished
}
for await event in stream {
if Task.isCancelled { break }
@@ -261,6 +246,9 @@ actor NemotronSuperLocalBinding {
await onEvent(event)
}
if Task.isCancelled { await cancel.run() }
+ // A continuation a cancel overtook during the hand-off is cancelled by
+ // the time the splice is over: only then can its row have a pump.
+ await spliceFinished?()
// A terminal event alone does not prove pump/native cleanup has completed.
await usage.waitForTerminalObservation()
await continuationUsage.waitForTerminalObservation()
@@ -270,3 +258,39 @@ actor NemotronSuperLocalBinding {
try Task.checkCancellation()
}
}
+
+private extension ChatCompletionRequest {
+ /// The same request with another output budget.
+ func withMaxTokens(_ maxTokens: Int) -> ChatCompletionRequest {
+ ChatCompletionRequest(
+ model: model, messages: messages, temperature: temperature, top_p: top_p, top_k: top_k,
+ max_tokens: maxTokens, repetition_penalty: repetition_penalty, presence_penalty: presence_penalty,
+ frequency_penalty: frequency_penalty, stream: stream, stop: stop, seed: seed, tools: tools,
+ tool_choice: tool_choice, response_format: response_format, user: user,
+ prompt_cache_key: prompt_cache_key, logit_bias: logit_bias, logprobs: logprobs,
+ top_logprobs: top_logprobs, min_p: min_p)
+ }
+}
+
+/// Cancels the request's running row: the first, or once a continuation can
+/// start, both (`LoopExitThinkingContinuation.splice`'s cancel). Once run, a
+/// continuation still being handed off is not submitted.
+private final class RowCancel: @unchecked Sendable {
+ private let lock = NSLock()
+ private var action: @Sendable () async -> Void
+ private var ran = false
+
+ init(_ action: @escaping @Sendable () async -> Void) { self.action = action }
+
+ func replace(with action: @escaping @Sendable () async -> Void) { lock.withLock { self.action = action } }
+
+ var cancelled: Bool { lock.withLock { ran } }
+
+ func run() async {
+ let action = lock.withLock { () -> @Sendable () async -> Void in
+ ran = true
+ return self.action
+ }
+ await action()
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
index 98da0f2073..1d5f093f7b 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift
@@ -62,7 +62,9 @@ enum LoopExitThinkingContinuation {
static let minimumAnswerBudget = 256
/// The spliced stream; its cancel, which stops whichever row is running;
- /// and `finished`, which returns once the splice is over.
+ /// and `finished`, which returns once the splice is over: a continuation
+ /// that a cancel overtook during the hand-off has been cancelled by then.
+ /// An owner that returns its admission when the request ends joins it.
static func splice(
first: AsyncStream,
cancelFirst: @escaping @Sendable () async -> Void,
@@ -92,7 +94,7 @@ enum LoopExitThinkingContinuation {
task.cancel()
Task { await cancel() }
}
- return (events, cancel, {})
+ return (events, cancel, { await task.value })
}
private static func run(
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
index fef26beae2..00fb99b084 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
@@ -1143,6 +1143,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
guard await bridge.waitForRowRelease(requestId: requestId, within: .seconds(5)) else {
throw LoopExitThinkingContinuation.RowNotReleased()
}
+ // A client that left during the wait gets no continuation row.
+ try Task.checkCancellation()
var next = base
next.maxTokens = budget
// As model calibration submits: the request's prompt progress
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
index f8f38a6b4f..a5892d4776 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift
@@ -91,9 +91,9 @@ public final class GenerationLoopExitRecord: @unchecked Sendable {
/// to show rescues, and `qwen3_5` is also Qwen 3.8 27B. The guard keeps ending
/// every other loop as `length`: a loop outside the thought, a family that is
/// not on, a request that asked for logprobs (the forced tokens have none), a
-/// pair's request. Nemotron 3.5 Super (`nemotron_h_omni`) takes its owner's
-/// own route (`NemotronSuperLocalBinding`), which continues the answer the
-/// same way.
+/// pair's request. Nemotron 3.5 Super (`nemotron_h_omni`) has the marker and
+/// is off by default until its A/B; it takes its owner's own route
+/// (`NemotronSuperLocalBinding`), which continues the answer the same way.
///
/// `DARKBLOOM_LOOP_EXIT_THINKING`: unset, `1` or `on` keeps the default list;
/// `0` or `off` turns it off; any other value is the comma-separated list of
@@ -124,7 +124,7 @@ enum GenerationLoopExitThinkingPolicy {
/// `\n…\n\n\n` before the answer.
static let qwenThink = Markers(open: "", close: "", before: "\n", after: "\n\n")
- static let defaultModelTypes: Set = ["gemma4", "gemma4_text", "nemotron_h_omni"]
+ static let defaultModelTypes: Set = ["gemma4", "gemma4_text"]
/// The answer's own cap. Gemma's GPQA answers after a thought are under
/// 1,000 tokens; a Tau2 reply or call is shorter.
From 2cbefa1c16faa4b1310ffee63e5ba09a1b6132e5 Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Fri, 13 Nov 2026 01:40:46 -0800
Subject: [PATCH 12/14] test(provider): the exit-thinking serving tests take a
clean process's setting
The scheduler's exit-thinking setting defaults to the process's environment
(DARKBLOOM_LOOP_EXIT_THINKING). The serving tests that rely on the default
(the `serve` helper's, and the full-Mac admission test's own scheduler) now take
a clean process's setting (`setting(environment: [:])`) unless they pass one,
so a runner with the variable set gets the same results.
Red, on de5c48374a's build with the variable set on the test run:
`gemma4,gemma4_text,qwen3_5_moe` fails "Qwen 3.5/3.6 35B keep today's length
by default"; `0` fails three of Gemma's serving tests.
Review (fresh context) n2.
Co-Authored-By: Claude Opus 5.5
---
.../GenerationLoopExitThinkingServingTests.swift | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
index e6ea3dc41f..ad145e510b 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift
@@ -252,6 +252,11 @@ struct GenerationLoopExitThinkingServingTests {
private static let qwenOn = GenerationLoopExitThinkingPolicy.Setting.modelTypes(
GenerationLoopExitThinkingPolicy.defaultModelTypes.union(["qwen3_5_moe"]))
+ /// A clean process's setting. The scheduler's default reads the process's environment; these tests take this
+ /// one unless they pass their own, so a runner with DARKBLOOM_LOOP_EXIT_THINKING set (an A/B box) gets the same
+ /// results.
+ private static let cleanProcess = GenerationLoopExitThinkingPolicy.setting(environment: [:])
+
private func serve(
_ engine: ThoughtLoopCBv2Engine, served: Served = Served(), maxTokens: Int = 8_192, extra: String = "",
usage: EngineV2RequestUsageSignal? = nil, exitThinking: GenerationLoopExitThinkingPolicy.Setting? = nil
@@ -263,7 +268,7 @@ struct GenerationLoopExitThinkingServingTests {
var scheduler = MultiModelBatchSchedulerEngine(registryProvider: {
[served.modelID: .init(tokenizer: served.tokenizer, modelType: served.modelType, engineV2Bridge: bridge)]
}, engineV2Usage: usage)
- if let exitThinking { scheduler.exitThinkingSetting = exitThinking }
+ scheduler.exitThinkingSetting = exitThinking ?? Self.cleanProcess
var outcome = try await consume(scheduler, served: served, maxTokens: maxTokens, extra: extra)
await bridge.shutdown()
outcome.loopGuardStops = telemetry.loopGuardStops
@@ -388,9 +393,10 @@ struct GenerationLoopExitThinkingServingTests {
await bridge.updatePrefillTpsEwma(2_000, isolated: true)
let id = modelID
let tokenizer = Self.tokenizer
- let scheduler = MultiModelBatchSchedulerEngine(
+ var scheduler = MultiModelBatchSchedulerEngine(
registryProvider: { [id: .init(tokenizer: tokenizer, modelType: "gemma4", engineV2Bridge: bridge)] },
firstContentDeadline: FirstContentDeadline(relativeBudgetMilliseconds: 60_000))
+ scheduler.exitThinkingSetting = Self.cleanProcess
let outcome = try await consume(scheduler, maxTokens: 8_192)
await bridge.shutdown()
#expect(outcome.error == nil)
From b4cc61883cb2941067d7cbede345de4caa8a4840 Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Fri, 13 Nov 2026 01:40:46 -0800
Subject: [PATCH 13/14] docs: exit-thinking is on for Gemma 4; Qwen 3.5/3.6
only when listed
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The bullet's heading read as if Qwen's exit were on by default, and so did
the env list's examples: `gemma4,gemma4_text` is the default; `…,qwen3_5_moe`
adds the Qwen 3.5/3.6 35B models, and `…,qwen3_5` the 9B and Qwen 3.8 27B.
Review (fresh context) n1; the delta review's n-a.
Co-Authored-By: Claude Opus 5.5
---
docs/architecture/inference.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index 16b5d5b413..f72f6be15c 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -3252,8 +3252,8 @@ stops such a row early.
(Super, text only), `glm5_next` and `mimo_v2`. `DARKBLOOM_LOOP_GUARD=0`
(or `off`) turns it off; a comma-separated list of `model_type`s replaces
the default list.
-- **A loop inside a Gemma 4 or Qwen 3.5/3.6 35B thought ends the thought, not
- the answer** (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`).
+- **A loop inside a Gemma 4 thought (or a listed Qwen 3.5/3.6 one) ends the
+ thought, not the answer** (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`).
For `gemma4` and `gemma4_text` (on by default) and `qwen3_5_moe` (Qwen 3.5/3.6
35B) and `qwen3_5` (Qwen 3.5 9B, Qwen 3.8 27B), listed and off by default (their
thought loops were too rare in the A/B to show rescues), the guard also
@@ -3294,8 +3294,8 @@ stops such a row early.
logprobs or on a cluster pair. Never when the exit's tokens do not decode to
its text. `DARKBLOOM_LOOP_EXIT_THINKING=0` (or `off`)
turns it off; a comma-separated list keeps it to the listed `model_type`s
- that have a marker (`gemma4,gemma4_text` keeps Gemma's alone;
- `gemma4,gemma4_text,qwen3_5_moe,qwen3_5` adds the 9B and Qwen 3.8 27B). `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
+ that have a marker (`gemma4,gemma4_text` is the default; `…,qwen3_5_moe`
+ adds the Qwen 3.5/3.6 35B models, and `…,qwen3_5` the 9B and Qwen 3.8 27B). `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
to the launchd daemon (`LaunchAgent.inferencePassthroughEnvKeys`). One `darkbloom.loop-guard.exit-thinking` line per ended
thought gives the outcome.
From 1a8734918c63c46cab3ff91fa61bc95fde938a9d Mon Sep 17 00:00:00 2001
From: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Date: Fri, 13 Nov 2026 01:58:27 -0800
Subject: [PATCH 14/14] docs: Super's exit-thinking switch and the hand-off's
cancel, as they are
- The changelog's value turned Qwen 3.5/3.6 35B's exit on too: Super alone
beside Gemma 4's is `gemma4,gemma4_text,nemotron_h_omni`.
- inference.md: the bullet's heading names the listed families; a cancel or
drain during the stopped row's release wait submits no second row, and one
that races the submission cancels it at once.
- The scheduler's comment after the release wait: the task check covers a
consumer that stopped reading the spliced stream; a cancel that reaches only
the splice's control (the local API's disconnect hook) is seen once the row
is submitted, and cancels it at once (closing that window is a follow-up).
Review (fresh context) n1, and m1's comment; the delta review's n-b.
Co-Authored-By: Claude Opus 5.5
---
changelog.d/loop-guard-exit-thinking-super.md | 4 ++--
docs/architecture/inference.md | 9 +++++----
.../Scheduler/MultiModelBatchSchedulerEngine.swift | 7 ++++++-
3 files changed, 13 insertions(+), 7 deletions(-)
diff --git a/changelog.d/loop-guard-exit-thinking-super.md b/changelog.d/loop-guard-exit-thinking-super.md
index 8d7f81c2d4..a67a4139de 100644
--- a/changelog.d/loop-guard-exit-thinking-super.md
+++ b/changelog.d/loop-guard-exit-thinking-super.md
@@ -1,5 +1,5 @@
### A Nemotron 3.5 Super thought that repeats itself verbatim can end in an answer (off by default)
-- As for Gemma 4 and the Qwen 3.5/3.6 35B models, once turned on: when the loop guard stops a verbatim loop inside Super's thought, the request no longer ends as `length` with no answer. The provider ends the thought (``, as Super's template does), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
+- Once turned on, as for Gemma 4 in 0.10.13 (and the Qwen 3.5/3.6 35B models, when listed): when the loop guard stops a verbatim loop inside Super's thought, the request no longer ends as `length` with no answer. The provider ends the thought (``, as Super's template does), and the model writes its answer in the same response. The usage counts every token produced, as one completion. A loop in the answer still ends as `length`.
- Since 0.10.12, 3.0 % of GPQA-shaped Super requests ended that way with no answer.
-- Off by default until its A/B: `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text,qwen3_5_moe,nemotron_h_omni` turns it on beside the default families; `0` turns all of them off. Never with logprobs, media or on a cluster pair.
+- Off by default until its A/B: `DARKBLOOM_LOOP_EXIT_THINKING=gemma4,gemma4_text,nemotron_h_omni` turns it on beside Gemma 4's (the default); adding `qwen3_5_moe` turns on the Qwen 3.5/3.6 35B models' too; `0` turns all of them off. Never with logprobs, media or on a cluster pair.
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index d821ee34dc..38d716744f 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -3252,8 +3252,8 @@ stops such a row early.
(Super, text only), `glm5_next` and `mimo_v2`. `DARKBLOOM_LOOP_GUARD=0`
(or `off`) turns it off; a comma-separated list of `model_type`s replaces
the default list.
-- **A loop inside a Gemma 4 thought (or a listed Qwen 3.5/3.6 one) ends the
- thought, not the answer** (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`).
+- **A loop inside a Gemma 4 thought (or a listed Qwen 3.5/3.6 or Nemotron 3.5
+ Super one) ends the thought, not the answer** (`GenerationLoopExitThinkingPolicy`, `LoopExitThinkingContinuation`).
For `gemma4` and `gemma4_text` (on by default) and `qwen3_5_moe` (Qwen 3.5/3.6
35B) and `qwen3_5` (Qwen 3.5 9B, Qwen 3.8 27B), listed and off by default (their
thought loops were too rare in the A/B to show rescues), the guard also
@@ -3302,8 +3302,9 @@ stops such a row early.
(`NemotronSuperRequestPlan.exitThinking`; the exit is `` alone, as its
template writes a thought) and `NemotronSuperLocalBinding` continues the
answer the same way, within the same admitted request. A cancel or drain
- during the hand-off submits no second row; the request joins the splice and
- then waits for both rows' terminal observations before the owner's admission
+ during the stopped row's release wait submits no second row (one that races
+ the submission cancels it at once); the request joins the splice and then
+ waits for both rows' terminal observations before the owner's admission
returns. The guard follows the last thought marker, Super's reasoning channel
the first ``: a model that writes `` in its answer and then
loops is continued, and its `` reaches the client as content. `darkbloom start` passes it, and `DARKBLOOM_LOOP_GUARD`,
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
index 00fb99b084..16a34bd88e 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
@@ -1143,7 +1143,12 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
guard await bridge.waitForRowRelease(requestId: requestId, within: .seconds(5)) else {
throw LoopExitThinkingContinuation.RowNotReleased()
}
- // A client that left during the wait gets no continuation row.
+ // A consumer that stopped reading the spliced stream (its
+ // `onTermination(.cancelled)` cancels this task) gets no
+ // continuation row. A cancel that reaches only the splice's
+ // `Control` (the local API's disconnect hook) is seen once the
+ // row is submitted, and cancels it at once (closing that
+ // window is a follow-up).
try Task.checkCancellation()
var next = base
next.maxTokens = budget