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..c7c01f30ab --- /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 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\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/changelog.d/loop-guard-exit-thinking-super.md b/changelog.d/loop-guard-exit-thinking-super.md new file mode 100644 index 0000000000..a67a4139de --- /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 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 (``, 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. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a88327753d..38d716744f 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -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>` … ``; 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>` … ``, `` … + ``; 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 +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 ``, 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 (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 `` 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 ``: 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 e4020a6b65..5844d3f9a2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding.swift @@ -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, @@ -183,11 +185,59 @@ 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; @@ -195,12 +245,52 @@ 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 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() + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/LoopExitThinkingContinuation.swift index 3dcd68dcdb..1d5f093f7b 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 @@ -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, cancelFirst: @escaping @Sendable () async -> Void, @@ -70,7 +74,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 { @@ -89,7 +94,7 @@ enum LoopExitThinkingContinuation { task.cancel() Task { await cancel() } } - return (events, cancel) + return (events, cancel, { await task.value }) } private static func run( @@ -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) diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e7ea281696..16a34bd88e 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 @@ -1025,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, @@ -1118,6 +1121,13 @@ 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) + // 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, @@ -1133,6 +1143,13 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { guard await bridge.waitForRowRelease(requestId: requestId, within: .seconds(5)) else { throw LoopExitThinkingContinuation.RowNotReleased() } + // 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 // As model calibration submits: the request's prompt progress @@ -1148,7 +1165,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { requestId: continuationId, cacheScope: cacheScope, cacheEnabled: cacheEnabled, - stopStringScope: stopStringScope, + usageSignal: continuationUsage, + stopStringScope: continuationStopScope, donationDemand: donationDemand, firstContentDeadline: nil, measurementPurpose: measurementPurpose, @@ -1160,6 +1178,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/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/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopExitThinking.swift index c49856b7c5..a5892d4776 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 @@ -37,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 } @@ -52,14 +72,28 @@ 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: 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 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 +/// (``). 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. 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 @@ -70,14 +104,26 @@ 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`. static let markersByModelType: [String: Markers] = [ "gemma4": .init(open: "<|channel>", close: ""), "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"] /// The answer's own cap. Gemma's GPQA answers after a thought are under @@ -122,9 +168,18 @@ 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) + } + 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: [close], exitText: markers.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..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? { @@ -59,7 +66,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 +91,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 +102,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: "<")) { 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, diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/LoopExitThinkingContinuationTests.swift index 8d239293e9..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, @@ -160,6 +207,55 @@ 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("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() @@ -255,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/GenerationLoopExitThinkingServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GenerationLoopExitThinkingServingTests.swift index f3bc093458..ad145e510b 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.6 35B with thinking on: the prompt ends `\n`. + private static let qwen = Served( + 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 { var content = "" var reasoning = "" @@ -221,31 +248,43 @@ 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"])) + + /// 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, modelType: String = "gemma4", maxTokens: Int = 8_192 + _ engine: ThoughtLoopCBv2Engine, served: Served = Served(), maxTokens: Int = 8_192, extra: String = "", + usage: EngineV2RequestUsageSignal? = nil, exitThinking: GenerationLoopExitThinkingPolicy.Setting? = nil ) 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)] - }) - var outcome = try await consume(scheduler, maxTokens: maxTokens) + var scheduler = MultiModelBatchSchedulerEngine(registryProvider: { + [served.modelID: .init(tokenizer: served.tokenizer, modelType: served.modelType, engineV2Bridge: bridge)] + }, engineV2Usage: usage) + scheduler.exitThinkingSetting = exitThinking ?? Self.cleanProcess + var outcome = try await consume(scheduler, served: served, maxTokens: maxTokens, extra: extra) await bridge.shutdown() outcome.loopGuardStops = telemetry.loopGuardStops return outcome } - private func consume(_ scheduler: MultiModelBatchSchedulerEngine, maxTokens: Int) async throws -> Outcome { + /// `extra`: more top-level request fields, each with its leading comma. + private func consume( + _ scheduler: MultiModelBatchSchedulerEngine, served: Served = Served(), maxTokens: Int, extra: String = "" + ) 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)\(extra)} """.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 ?? "" @@ -354,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) @@ -365,10 +405,84 @@ struct GenerationLoopExitThinkingServingTests { #expect(outcome.content == "Answer: B") } + @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, exitThinking: Self.qwenOn) + #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.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, exitThinking: Self.qwenOn) + #expect(outcome.error == nil) + #expect(engine.requests.count == 1) + #expect(outcome.info?.stopReason == "length") + #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, + exitThinking: Self.qwenOn) + #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.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, exitThinking: Self.qwenOn) + #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") + 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 6c499059a0..43f8852462 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,161 @@ 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)) + + /// 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: setting) + } + + @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(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) + } + // 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. + 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: 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, + 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. + 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("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: Self.qwenOn)) + #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\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: Self.qwenOn) == 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] { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift index 00b7dfe555..f441458ffd 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NemotronSuperLoopGuardTests.swift @@ -63,15 +63,100 @@ private final class SuperLoopingEngine: CBv2Engine, @unchecked Sendable { func shutdown() async {} } +/// 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 = 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) } + /// 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]] = [] + /// 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 } } + + 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 { + 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 + 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? 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 @@ -150,6 +235,116 @@ struct NemotronSuperLoopGuardTests { #expect(await events.text.utf8.count > 4_096) } + // MARK: Ending a repeating thought + + 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.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.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.exitOn) == 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) + } + + 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, + 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(fields) + let exit = plan.exitThinking(promptTokens: prompt, tokenizer: SuperThoughtVocabulary.tokenizer, + 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() + 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(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(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") func switchOffKeepsTodaysBehavior() async throws { let engine = SuperLoopingEngine(tokens: 4_200)