Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
1024fa6
test(provider): exit-thinking for Qwen 3.5/3.6's `</think>` (red)
jonathan308 Nov 13, 2026
eac6e9f
feat(provider): a repeating Qwen 3.5/3.6 thought ends in an answer
jonathan308 Nov 13, 2026
e222563
test(provider): exit-thinking for Qwen, the review's findings (red)
jonathan308 Nov 13, 2026
c4769c1
fix(provider): exit-thinking for Qwen, the review's findings
jonathan308 Nov 13, 2026
f52e7d1
test(provider): exit-thinking for Nemotron 3.5 Super's own route (red)
jonathan308 Nov 13, 2026
66274c9
feat(provider): a repeating Nemotron 3.5 Super thought ends in an answer
jonathan308 Nov 13, 2026
251b698
test(provider): exit-thinking for Qwen is listed but off by default (…
jonathan308 Nov 13, 2026
2b3c7a7
feat(provider): exit-thinking for Qwen: off by default, per the A/B
jonathan308 Nov 13, 2026
3783cb1
Merge #2046's head (Qwen's exit off by default) into the Super branch
jonathan308 Nov 13, 2026
e40e4d1
test(provider): Super's exit-thinking, the review's findings (red)
jonathan308 Nov 13, 2026
de5c483
test(provider): the Qwen thinking-off check turns Qwen's exit on
jonathan308 Nov 13, 2026
853ced2
Merge #2046's test fix (Qwen's thinking-off check turns its exit on)
Nov 13, 2026
47f665f
fix(provider): Super's exit-thinking, the review's findings
jonathan308 Nov 13, 2026
2cbefa1
test(provider): the exit-thinking serving tests take a clean process'…
jonathan308 Nov 13, 2026
b4cc618
docs: exit-thinking is on for Gemma 4; Qwen 3.5/3.6 only when listed
jonathan308 Nov 13, 2026
db2b69a
Merge #2046's head (the serving tests' clean setting; the docs' headi…
jonathan308 Nov 13, 2026
1a87349
docs: Super's exit-thinking switch and the hand-off's cancel, as they…
jonathan308 Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions changelog.d/loop-guard-exit-thinking-qwen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
### A Qwen 3.5 or 3.6 thought that repeats itself verbatim can end in an answer (off by default)

- 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</think>\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).
5 changes: 5 additions & 0 deletions changelog.d/loop-guard-exit-thinking-super.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### A Nemotron 3.5 Super thought that repeats itself verbatim can end in an answer (off by default)

- 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 (`</think>`, 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,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.
54 changes: 40 additions & 14 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -3252,10 +3252,14 @@ 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>` … `<channel|>`; the prompt's tail seeds the state) and records
- **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
follows the thought channel (`<|channel>` … `<channel|>`, `<think>` …
`</think>`; the prompt's tail seeds the state: Qwen's served template opens
`<think>` 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
Expand All @@ -3264,24 +3268,46 @@ 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 `<channel|>`, 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 `<channel|>` 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
`<channel|>`; Qwen's `\n</think>\n\n`, as its template closes a thought, with
`</think>` 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 (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
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, 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. `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. `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).
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 `</think>` 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 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 `</think>`: a model that writes `<think>` in its answer and then
loops is continued, and its `</think>` 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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,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,
Expand Down Expand Up @@ -183,24 +185,112 @@ 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 spliceFinished: (@Sendable () async -> Void)?
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()
}
// 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
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)
spliceFinished = spliced.finished
}
for await event in stream {
if Task.isCancelled { break }
// The bridge yields a delta's entries just before its text;
// they leave on the request's channel in that order.
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 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()
} onCancel: {
Task { await bridge.cancel(requestId: requestID) }
Task { await cancel.run() }
}
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()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -60,7 +61,10 @@ 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: 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<GenerationEvent>,
cancelFirst: @escaping @Sendable () async -> Void,
Expand All @@ -70,7 +74,8 @@ enum LoopExitThinkingContinuation {
submit: @escaping Submit,
cancelContinuation: @escaping @Sendable () async -> Void,
onOutcome: (@Sendable (Outcome) -> Void)? = nil
) -> (events: AsyncStream<GenerationEvent>, cancel: @Sendable () async -> Void) {
) -> (events: AsyncStream<GenerationEvent>, cancel: @Sendable () async -> Void,
finished: @Sendable () async -> Void) {
let (events, out) = AsyncStream<GenerationEvent>.makeStream()
let control = Control()
let task = Task {
Expand All @@ -89,7 +94,7 @@ enum LoopExitThinkingContinuation {
task.cancel()
Task { await cancel() }
}
return (events, cancel)
return (events, cancel, { await task.value })
}

private static func run(
Expand Down Expand Up @@ -125,10 +130,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.
if let detection = exit.record.requested,
generated.dropFirst(detection.generatedTokens).contains(where: exit.exitTokens.contains) {
// 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)
Expand Down
Loading
Loading