Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions changelog.d/qwen-forced-tool-thinking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Added opt-in `DARKBLOOM_QWEN_FORCED_TOOL_THINKING` for qwen forced-call thinking. Forced required/named tool requests retain the caller’s resolved thinking setting. Nested reasoning.enabled takes precedence over enable_thinking and effort. The existing native router separates reasoning before validating a trailing tool call. Default-off behavior is unchanged.
7 changes: 7 additions & 0 deletions docs/architecture/hardware-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -1617,3 +1617,10 @@ memory is free. Admission limits and native memory guards are unchanged. See
[planned cluster stop ordering](inference.md#planned-cluster-stop-ordering) and
`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift`
(`ClusterService.stopLocalPart`).


## Qwen forced-call thinking

The [qwen forced-call thinking](inference.md#qwen-forced-call-thinking) switch changes prompt/output
processing only. It adds no hardware capability or memory grant; parser
fixtures do not qualify model residency, throughput or concurrent GPU loads.
8 changes: 8 additions & 0 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -9981,3 +9981,11 @@ Each tensor-parallel rank reserves only the request state it holds (`QwenTensorP
Concurrent speculative requests verify their draft windows in one target forward, and each request must emit exactly the tokens it emits alone. MLX picks a quantized matmul kernel from the product's total row count. Up to the device's vector limit (`get_qmv_batch_limit`: 12 rows at Qwen27's widths on the M3 Ultra, 13 on the M5 Max) a product runs `qmv_wide`; at or beyond it, split-K QMM, with a different reduction order. One request's three-column window is 3 rows; four requests' windows in one product are 12, so on the M3 they took the other kernel. In an installed run before this change, 5 of 30 concurrent requests, all in waves with four-request cohorts, chose a different near-tie token. `QwenTensorParallelTargetWindow.beginBatch` therefore runs the batched verify forward under `Qwen35BatchDecodeScope.verifyRows`. Every projection computes each request's `[1, S, H]` rows as that request's own window would, the row-parallel projections concatenate those partials into one collective per projection (two per dense layer), and the LM head follows the same rule. Below the vector limit, `qmv_wide` (and `qmv` before Apple GPU family 15) computes each vector the same way at any vector count: its tile size only decides which vectors share a weight read. So requests share a quantized call while their windows' total rows stay below the limit (`Qwen35QuantizedVectorLimit`, which mirrors `get_qmv_batch_limit` for the device MLX reads, including `MLX_METAL_GPU_ARCH`). At Qwen27's widths with depth 3 that is two four-column windows per call on the M3 Ultra and three on the M5 Max. `qmv_wide` still reads the weights once per tile of up to five vectors, so sharing saves launches and some weight reads rather than whole passes; the installed round profile (`darkbloom-tp-mtp-profile-v1`, c35) still shows about 44 ms of verify time per additional row. Only exact base `QuantizedLinear` modules in affine mode on the GPU share calls; the CPU, other quantizers, overridden forwards and MLX's 64/128-wide quad kernel keep one call per row. `QwenTensorParallelBatchMTPWindowTests.sharedWindowCallsKeepEveryRowsQuantizedArithmetic` checks the shared calls byte for byte against each row's own call at Qwen27's projection shapes. Attention and the recurrent layers were already per-request, so only the projection row count changed between alone and together. `QwenTensorParallelBatchMTPWindowTests.everyRectangleRowEqualsItsOwnSingleRequestWindowBitwise` compares every row of eight-request rectangles with its own window, byte for byte, on both ranks. The agreement carries `verify-rows=single-window-v1`.

Where it measured faster and byte-equal, a cohort's verify rows go through one kernel instead of MLX's own calls (`Qwen35WideQuantizedKernel`, a port of `qmv_wide_impl`): each vector keeps `qmv_wide`'s lanes, sub-chunk sums and shuffle ladder, but up to eight vectors (two four-column windows) share a weight read instead of five, and a thread may carry two output rows so each input value is converted once for both. The layout follows the GPU family (`Qwen35WideQuantizedKernel.layout`). On the M5 Max (family 17), one row a thread for bfloat16 and float32 inputs, up to 20% faster than MLX's calls. On the M3 Ultra (family 15), two rows a thread for the row-parallel float32 partials, 1.5-2.1x faster, while its bfloat16 projections keep MLX's calls, which measured as fast or faster; one row a thread was up to 1.6x slower there. Other families keep MLX's calls. The figures come from `QwenTensorParallelVerifyBenchTests` (opt-in) on each Mac with Qwen27's shard shapes, and `QwenTensorParallelBatchMTPWindowTests.wideKernelRowsEqualEachRowsOwnWindowCall` checks both layouts byte for byte against each row's own call on whichever GPU runs it.


## Qwen forced-call thinking

Forced required/named calls on qwen3_5 and qwen3_5_moe retain the resolved thinking setting. Nested reasoning.enabled takes precedence over enable_thinking and effort. The family tool parser and its accepted XML override classify reasoning before validating the call; a complete trailing call at a natural stop uses the existing promotion rule.

The [rollout switch](../reference/configuration.md#qwen-forced-call-thinking) defaults off.
CPU parser fixtures do not establish full-model output quality or GPU performance.
8 changes: 8 additions & 0 deletions docs/provider/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -4420,3 +4420,11 @@ Source: `provider-swift/Sources/darkbloom/ClusterServiceCommand.swift`
for the bounds and process custody rules.

Qwen3.8 27B automatic cluster capacity changes keep the current tensor split and native request execution path. Widening occurs only when the complete reservation fits that split; otherwise the current capacity remains available. No additional command or user setting is required. Implementation: `DistributedAutomaticBatchPlanner` and `ClusterPlacementFlow` in `provider-swift/Sources/ProviderCore/Inference/Distributed/`.


## Qwen forced-call thinking

The daemon allow-list forwards `DARKBLOOM_QWEN_FORCED_TOOL_THINKING`; see its
[values, default and behavior](../reference/configuration.md#qwen-forced-call-thinking).
Set it before starting or restarting the daemon. An environment change does
not alter an already-running daemon.
7 changes: 7 additions & 0 deletions docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -1847,3 +1847,10 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/C
The wizard’s optional local stopDrain token is saved with stopped intent and retained after a local timeout. Leases preserve the peer’s prior intent until the local supervisor retires its owned part and outstanding lease. The token is not a wire or user-facing configuration field; older records decode without it. A new serve is refused while it remains, and a model change retries the shared stop first.

Every write of the wizard's record (`~/.darkbloom/cluster-setup/wizard.json`) takes the `wizard.json.lock` flock. When another writer holds that lock, the write waits up to 2 seconds for it (`ClusterSetupStore.recordLockWaitSeconds`). After 2 seconds the write fails with "Configuration or native device lease is currently held". The cluster service writes the record while it holds its own service lock, so it tries once and writes again on its next supervision cycle. Source: `provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift` (`ClusterSetupStore.updateRecord`).


## Qwen forced-call thinking

| Variable | Values | Default | Reader | Scope |
|---|---|---|---|---|
| `DARKBLOOM_QWEN_FORCED_TOOL_THINKING` | `1`, `on`, `true`, `yes` enable, ignoring case and surrounding whitespace; other values disable | off (existing behavior) | `Qwen35TemplateFix.preservesForcedThinking` | [Qwen forced-call thinking](../architecture/inference.md#qwen-forced-call-thinking); forwarded by `LaunchAgent` |
Original file line number Diff line number Diff line change
Expand Up @@ -160,12 +160,11 @@ extension MultiModelBatchSchedulerEngine {
// reasons, at the model's lowest level, and is not rewritten to false.
if requiresToolCall && Qwen35TemplateFix.applies(to: fixContext)
&& !ToolChoiceEnforcementPolicy.nativeStructuredTarget(fixContext)
&& !Qwen35TemplateFix.preservesForcedThinking(fixContext)
{
// Legacy Qwen text routing cannot separate reasoning before XML
// tool parsing. Native Qwen4/Nemotron use NativeToolStreamRouter,
// so they preserve caller thinking controls instead of inheriting
// this older tool-only workaround. Visible prose still fails the
// forced-call contract; reasoning is a separate typed channel.
// Keep the existing prompt contract unless the Qwen reasoning-first
// route is opted in. That route already separates the thought from
// the call and validates forced calls before exposing them.
context["enable_thinking"] = false
} else if let nested = request.reasoning?.enabled {
context["enable_thinking"] = nested
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1312,8 +1312,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
nativeReasoningPrefix = ReasoningPromptProbe.streamingPrefix(forPromptTail:
tokenizer.inner.decode(tokenIds: Array(promptTokens.suffix(ReasoningPromptProbe.tailTokenCount)),
skipSpecialTokens: false)) ?? "<think></think>"
} else if toolHandler?.format == .qwen35,
ToolChoiceEnforcementPolicy.splitsQwenReasoningBeforeTools(modelContext) {
} else if Qwen35TemplateFix.routesReasoningBeforeTools(format: toolHandler?.format,
requiresToolCall: prepared.requiresToolCall, context: modelContext) {
// The think parser's own seed, the prompt's think state, starts the
// split: reasoning is classified before tool parsing, with call
// frames found by the Qwen parser's own scanner. Without a seed, or
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,31 @@
// fixes both families.

import Foundation
import MLXLMCommon
import MLXLMServer

enum Qwen35TemplateFix {
/// The accepted XML override needs the same reasoning-first route as the
/// family parser when forced-call thinking is enabled. Off keeps its
/// existing raw route; automatic XML calls are unchanged.
static func routesReasoningBeforeTools(format: ToolCallFormat?, requiresToolCall: Bool,
context: ChatTemplateFixContext) -> Bool {
guard ToolChoiceEnforcementPolicy.splitsQwenReasoningBeforeTools(context) else { return false }
return format == .qwen35 || (format == .xmlFunction && requiresToolCall && preservesForcedThinking(context))
}

static let forcedThinkingEnvironmentKey = "DARKBLOOM_QWEN_FORCED_TOOL_THINKING"

/// The reasoning-before-tools route is qualified for these model types.
/// Other template aliases retain the forced-thinking workaround.
static func preservesForcedThinking(_ context: ChatTemplateFixContext,
environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
guard ToolChoiceEnforcementPolicy.splitsQwenReasoningBeforeTools(context) else { return false }
return ["1", "on", "true", "yes"].contains(
environment[forcedThinkingEnvironmentKey]?.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased() ?? "")
}

static func applies(to context: ChatTemplateFixContext) -> Bool {
if let modelType = context.modelType?
.trimmingCharacters(in: .whitespacesAndNewlines)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,7 @@ public enum LaunchAgent: Sendable {
/// default; an off word (`off`, `false`, `0`, `none`, `no`, `disabled`)
/// refuses them and stops advertising them.
static let inferencePassthroughEnvKeys = [
Qwen35TemplateFix.forcedThinkingEnvironmentKey,
EngineV2Factory.maxPartialPrefillsKey,
EngineV2Factory.prefillChunkKey,
EngineV2Factory.stepTokenBudgetKey,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import Foundation
import MLXLMCommon
import MLXLMServer
import XCTest
@testable import ProviderCore

/// Run with XCTest's process-isolated runner. Restore the rollout flag after
/// each test; Swift Testing suites execute in their separate runner.
final class QwenForcedThinkingConformanceTests: XCTestCase {
private let flag = "DARKBLOOM_QWEN_FORCED_TOOL_THINKING"
private var previous: String?

override func setUp() {
super.setUp()
previous = ProcessInfo.processInfo.environment[flag]
setenv(flag, "1", 1)
}
override func tearDown() {
if let previous { setenv(flag, previous, 1) } else { unsetenv(flag) }
super.tearDown()
}

private func context(choice: String, reasoning: String, modelType: String = "qwen3_5_moe") throws -> [String: any Sendable]? {
let body = Data("""
{"model":"qwen3.6-35b-a3b-vl-mtp-mxfp8","messages":[{"role":"user","content":"Check Paris"}],
"tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"],"additionalProperties":false}}}],
"tool_choice":\(choice),\(reasoning)}
""".utf8)
let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: body)
let controls = try JSONDecoder().decode(ChatTemplateControls.self, from: body)
let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: modelType)
return MultiModelBatchSchedulerEngine.templateAdditionalContext(for: request, controls: controls,
modelType: modelType, requiresToolCall: prepared.requiresToolCall)
}

func testRequiredAndNamedCallsPreserveExplicitReasoning() throws {
for type in ["qwen3_5", "qwen3_5_moe"] {
for choice in [#""required""#, #"{"type":"function","function":{"name":"get_weather"}}"#] {
let value = try context(choice: choice, reasoning: #""reasoning":{"enabled":true},"enable_thinking":false"#, modelType: type)
XCTAssertEqual(value?["enable_thinking"] as? Bool, true)
}
}
}

func testNestedDisableAndNoToolChoiceRetainTheirMeaning() throws {
XCTAssertEqual(try context(choice: #""required""#,
reasoning: #""reasoning":{"enabled":false},"enable_thinking":true"#)?["enable_thinking"] as? Bool, false)
XCTAssertEqual(try context(choice: #""auto""#,
reasoning: #""reasoning":{"enabled":true}"#)?["enable_thinking"] as? Bool, true)
}

#if DEBUG
func testRequiredAndNamedThinkingEndsWithAValidatedCall() async throws {
let frame = "<tool_call><function=get_weather><parameter=city>Paris</parameter></function></tool_call>"
for choice in [#""required""#, #"{"type":"function","function":{"name":"get_weather"}}"#] {
for (parserName, closeThought) in [("qwen35", true), ("qwen35", false), ("xml_function", true)] {
let body = Data("""
{"model":"qwen3.6-35b-a3b-vl-mtp-mxfp8","messages":[{"role":"user","content":"Check Paris"}],
"tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}],
"tool_choice":\(choice),"reasoning":{"enabled":true},"stream":true,"tool_call_parser":"\(parserName)"}
""".utf8)
let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: body)
let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "qwen3_5_moe")
let handler = try ToolStreamPreparation.makeHandler(request: request, prepared: prepared,
modelType: "qwen3_5_moe", streamToolCalls: true)
let output = "Find the weather." + (closeThought ? "</think>" : "") + frame
let upstream = AsyncStream<GenerationEvent> { continuation in
for char in output { continuation.yield(.chunk(String(char))) }
continuation.yield(.info(promptTokens: 9, completionTokens: output.count,
tokensPerSecond: 0, finishReason: "stop"))
continuation.finish()
}
let stream = try MultiModelBatchSchedulerEngine(registryProvider: { [:] })._testMakeEventStream(
upstream: upstream, cancelUpstream: {}, prepared: prepared,
releaseBox: OneShotRelease(release: { _ in }, modelId: request.model),
reasoningPrefix: "<think>", toolHandler: handler,
nativeReasoningPrefix: Qwen35TemplateFix.routesReasoningBeforeTools(
format: handler?.format, requiresToolCall: prepared.requiresToolCall,
context: .init(modelId: request.model, modelType: "qwen3_5_moe")) ? "<think>" : nil,
promotesTrailingReasoningCalls: true)
var reasoning = ""
var calls = [ToolCall]()
for try await event in stream {
if case .parsed(let part) = event {
reasoning += part.reasoningContent ?? ""
XCTAssertTrue(part.content.isEmpty)
}
if case .toolCall(let call) = event { calls.append(call) }
}
XCTAssertEqual(reasoning, "Find the weather." + (closeThought ? "" : frame))
XCTAssertEqual(calls.count, 1)
XCTAssertEqual(calls.first?.function.name, "get_weather")
XCTAssertEqual(calls.first?.function.arguments["city"], .string("Paris"))
}
}
}
#endif

func testFlagIsFamilyScopedAndReachesTheDaemon() {
XCTAssertTrue(LaunchAgent.inferencePassthroughEnvKeys.contains(Qwen35TemplateFix.forcedThinkingEnvironmentKey))
for type in ["qwen3_vl_moe", "prism_hadamard_qwen35", "gpt_oss", "mimo_v2"] {
XCTAssertFalse(Qwen35TemplateFix.preservesForcedThinking(
.init(modelId: "qwen3.6-35b-a3b-vl-mtp-mxfp8", modelType: type)))
}
}

func testSwitchOffPreservesForcedThinkingOff() throws {
for value in ["0", "off", "false", "no"] {
setenv(flag, value, 1)
XCTAssertEqual(try context(choice: #""required""#,
reasoning: #""reasoning":{"enabled":true}"#)?["enable_thinking"] as? Bool, false)
}
unsetenv(flag)
XCTAssertEqual(try context(choice: #""required""#,
reasoning: #""reasoning":{"enabled":true}"#)?["enable_thinking"] as? Bool, false)
}
}
Loading