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
4 changes: 4 additions & 0 deletions changelog.d/qwen-constraint-spans.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Qwen constraint spans

- Add default-off `DARKBLOOM_CONSTRAINT_SPANS` support for eligible Qwen strict-auto tool requests and JSON reasoning. Ordinary reasoning and content may draft; tool framing/arguments and JSON values remain protected. Text after a completed call may draft again.
- Forward the flag into the installed provider service. Preserve existing grammar admission, masks, engine eligibility and off behavior. No full-model speedup is claimed.
26 changes: 26 additions & 0 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -4314,6 +4314,32 @@ the owner's go.

### Strict tool-call grammar

When the [constraint-span setting](../reference/configuration.md#engine-and-scheduler)
(`DARKBLOOM_CONSTRAINT_SPANS`) enables speculation, `QwenStrictToolConstraint`
exposes ordinary reasoning and content as free spans through
`CBv2FreeSpanTokenConstraint`. Its pure preview accepts only tokens that stay
in the same state without touching a marker prefix. Call openings, framing,
arguments and partial markers remain protected; text after a closed call can
become free again. `JSONAnswerConstraint` exposes only Qwen reasoning before
the answer: the JSON value, string bodies and trailing whitespace stay protected.
Other JSON families retain target-only decoding. Neither constraint mutates
its interned states while previewing a speculative token.

Disabling the setting retains request-wide target-only constrained decoding.
Existing grammar admission, masks and sampler/model/lifecycle eligibility remain
authoritative. Required/named calls acquire no new strict-auto grammar. An
eligible native Qwen assistant retains committed history through protected
spans, but starts no draft there. Engines with native completion tracking remain
ineligible. The LaunchAgent forwards the flag at installation; the SDK snapshots
it at engine construction.

`QwenConstraintSpanServingTests` checks streamed content, reasoning, calls and
accounting through the scheduler, bridge and engine. Coverage includes multiple
calls, thinking on/off, short budgets, cancellation and refusal recovery. Tiny
native Qwen target/assistant fixtures check committed history across protected
entry and return to free text. These are bounded integration fixtures, not
full-model throughput or production qualification.

A `strict` `auto` call is checked against the caller's schema only when its
frame closes ([streamed auto tool calls](#streamed-auto-tool-calls)), after the
answer has started, so on the Qwen 3.5 template family (`qwen3_5`,
Expand Down
15 changes: 15 additions & 0 deletions docs/developer/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,21 @@ No model weights or live provider state are needed.

## Provider And SDK

`QwenConstraintSpanServingTests` sends strict-auto and JSON requests through
the public scheduler, bridge and real `EngineV2`. Deterministic native targets
supply literal reasoning, content and call arguments; an unconstrained control
proves drafting works. Tests require drafting around protected calls, unchanged
off/on output and accounting, multiple calls, thinking on/off and JSON that
never returns to a free span after its value starts. Tiny Qwen target/inline
assistant fixtures also verify committed history through protected entry and
return to text, cancellation with request-ID reuse, short output budgets, and
bridge refusal recovery. `QwenJSONFreeSpanTests` checks preview purity, partial
markers, scalar/string answers, exhaustion and non-Qwen fallback.

Run these with the normal source-matched provider test products and isolated
runner below. Tiny fixtures do not qualify full-model throughput, production
resource use or native completion-tracked engines.

From the repository root, use the [MiMo regression fixture recipe](#mimo-regression-fixtures)
to prepare the inputs and run `make provider-test`.

Expand Down
3 changes: 2 additions & 1 deletion docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,8 @@ and rollback are defined in the [provider configuration reference](../provider/c
| `DARKBLOOM_NEMOTRON_SUPER_VIDEO_PRUNING` | number in [0, 1) (surrounding spaces ignored) | `0.5` (`NemotronSuperVideoPreprocessing.defaultPruningRate`) | `provider-swift/Sources/ProviderCore/Inference/Vision/NemotronSuperVideoFeatures.swift` (`validatedPruningRate`) | EVS pruning rate `q` of Super video requests, in the managed slot and the qualification hook: a video of `T` tubelets of `N` visual rows keeps `max(N, int(T * N * (1 - q)))` rows; `0` keeps every row. Any other value fails the load before its LOAD claim and installation. A value below `0.5` keeps more rows, so a video's prompt has more tokens than the coordinator estimates for it, since that estimate assumes `0.5`. Not forwarded to LaunchAgents. |
| `DARKBLOOM_MTP_VERIFICATION_MODE` | `rectangular`, `serial`, `serial_target`, `automatic` | `automatic` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift` | MTP verification strategy (benchmark session). |
| `DARKBLOOM_MTP_ACCEPTANCE` | `exact`, `typical`, `typical:<delta>` (finite positive delta) | `exact` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift`; `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift` (`benchmarkOverride`) | MTP draft acceptance rule (benchmark session only). An unrecognized value uses `exact`. Serving reads no environment variable for this rule; it reads `[backend] mtp_acceptance` and `mtp_acceptance_by_model` in [`provider.toml`](../provider/cli-reference.md#providertoml-keys-read-by-the-cli). |
| `DARKBLOOM_STRICT_TOOL_GRAMMAR` | unset: the default builds; `on`, `1`, `true`, `yes`: every Qwen 3.5-family build (`qwen3_5`, `qwen3_5_moe`); an off word (`off`, `0`, `false`, `no`, `none`, `disabled`) disables; otherwise a comma list of `model_type`s or model-id parts (trimmed, case-insensitive) that replaces the default builds | on for `qwen3_5_moe` (Qwen 3.6, Qwen 3.5 35B) and `qwen3.8-27b` (Qwen 3.8 27B); Qwen 3.5 9B only when set | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift` (`setting`) | Qwen 3.5-family `auto` requests that declare a `strict` function sample every call's function, parameters and values under the declared schemas on one Mac; a request whose schemas fall outside the grammar, or a cluster pair, is served unconstrained. While a constrained answer decodes, no answer on that Mac drafts with MTP. See [strict tool-call grammar](../architecture/inference.md#strict-tool-call-grammar). Forwarded to the LaunchAgent. |
| `DARKBLOOM_CONSTRAINT_SPANS` | trimmed, case-insensitive `1`, `true`, `on`, `yes`; other values disable | off | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envFreeSpanSpeculation`) | Opts eligible constrained rows into MTP only while the provider proves an ordinary free-text span. Existing sampler, model and ownership eligibility still apply. Does not enable MTP or admit new strict-tool requests. Read at engine construction. Applies to admitted Qwen strict-auto reasoning/content and JSON reasoning; JSON values and trailing whitespace remain protected. Forwarded by the LaunchAgent. Native completion-tracked engines remain ineligible. |
| `DARKBLOOM_STRICT_TOOL_GRAMMAR` | unset: the default builds; `on`, `1`, `true`, `yes`: every Qwen 3.5-family build (`qwen3_5`, `qwen3_5_moe`); an off word (`off`, `0`, `false`, `no`, `none`, `disabled`) disables; otherwise a comma list of `model_type`s or model-id parts (trimmed, case-insensitive) that replaces the default builds | on for `qwen3_5_moe` (Qwen 3.6, Qwen 3.5 35B) and `qwen3.8-27b` (Qwen 3.8 27B); Qwen 3.5 9B only when set | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift` (`setting`) | Qwen 3.5-family `auto` requests that declare a `strict` function sample every call's function, parameters and values under the declared schemas on one Mac; a request whose schemas fall outside the grammar, or a cluster pair, is served unconstrained. With `DARKBLOOM_CONSTRAINT_SPANS` off, constrained decoding retains its existing drafting restriction. The opt-in only relaxes eligible free spans. See [strict tool-call grammar](../architecture/inference.md#strict-tool-call-grammar). Forwarded to the LaunchAgent. |
| `DARKBLOOM_STRICT_TOOL_GRAMMAR_ALL_TOOLS` | `on`, `1`, `true`, `yes` enable (trimmed, case-insensitive) | off | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift` (`allTools`) | Also constrains the calls of requests that declare no `strict` function. Forwarded to the LaunchAgent. |
| `DARKBLOOM_PREFILL_DEADLINE_MODE` | exactly `off` disables; any other value enforces | `enforce` | `provider-swift/Sources/ProviderCore/Inference/Engine/PrefillDeadlineMode.swift` (`PrefillDeadlineMode.resolve`) | Prefill-deadline admission on the provider. Read only when `[backend] prefill_deadline_mode` is absent from `provider.toml`; that key takes precedence. |
| `DARKBLOOM_TTFT_ADMISSION_FIXES` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineAdmissionFixes`) | Deadline-admission estimator corrections: per-batch decode charging, anchored isolated-prefill rate, newest-observation freshness, a probe that re-measures stale isolated-prefill evidence after three refusals it explains. Off restores the previous estimators and turns that probe off too. Forwarded to the launchd provider job. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ struct JSONAnswerBoundary: Hashable {
/// once the value is complete. Per-request and host-only: as in
/// `FlintNativeProtocolConstraint`, interning collapses free text to bounded
/// framing states, and it never forces a value or repairs a truncated one.
final class JSONAnswerConstraint: CBv2TokenConstraint, @unchecked Sendable {
final class JSONAnswerConstraint: CBv2FreeSpanTokenConstraint, @unchecked Sendable {
let mode = CBv2TokenConstraintMode.auto
let maxTokens: Int
let initialState = 0
Expand Down Expand Up @@ -145,6 +145,31 @@ final class JSONAnswerConstraint: CBv2TokenConstraint, @unchecked Sendable {
/// step ahead and redraw it when the confirmed token changes the state.
var allowsChainedDecode: Bool { true }

func isFreeSpan(state: Int) -> Bool {
lock.lock(); defer { lock.unlock() }
return !resourceExhausted && states.indices.contains(state) && isFree(states[state])
}

/// Preview never interns a state. Even a token that returns to reasoning
/// is protected if any byte enters a marker prefix along the way.
func isFreeSpanContinuation(state: Int, tokenID: Int) -> Bool {
lock.lock(); defer { lock.unlock() }
guard !resourceExhausted, states.indices.contains(state), isFree(states[state]),
vocabulary.pieces.indices.contains(tokenID),
!vocabulary.stopTokenIDs.contains(tokenID), !vocabulary.pieces[tokenID].isEmpty else {
return false
}
var next = states[state]
for byte in vocabulary.pieces[tokenID] {
guard next.consume(byte, profile: profile, grammar: format.grammar), isFree(next) else { return false }
}
return next == states[state]
}

private func isFree(_ boundary: JSONAnswerBoundary) -> Bool {
profile.family == "Qwen" && boundary.phase == .reasoning && boundary.window.isEmpty
}

func nextState(state: Int, tokenID: Int) -> Int? {
lock.lock(); defer { lock.unlock() }
guard !resourceExhausted, states.indices.contains(state), vocabulary.pieces.indices.contains(tokenID) else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,15 @@ struct QwenStrictToolBoundary: Hashable {
}
}

/// Draft only ordinary text, never a partial marker or a call opening.
var isFreeSpan: Bool {
guard window.isEmpty else { return false }
switch step {
case .reasoning, .content: return true
default: return false
}
}

/// Free spans whose bytes can only be refused by completing a marker:
/// reasoning, text, text values (every marker ends in `>`).
var isOpaqueSpan: Bool {
Expand Down Expand Up @@ -296,7 +305,7 @@ struct QwenStrictToolBoundary: Hashable {
/// Should the interned states ever run out, the constraint releases the rest
/// of the answer to free sampling (as before the grammar) instead of failing
/// it.
final class QwenStrictToolConstraint: CBv2TokenConstraint, @unchecked Sendable {
final class QwenStrictToolConstraint: CBv2FreeSpanTokenConstraint, @unchecked Sendable {
let mode = CBv2TokenConstraintMode.auto
let maxTokens: Int
let initialState = 0
Expand Down Expand Up @@ -404,6 +413,29 @@ final class QwenStrictToolConstraint: CBv2TokenConstraint, @unchecked Sendable {
/// `nextState` interns only host-confirmed tokens.
var allowsChainedDecode: Bool { true }

func isFreeSpan(state: Int) -> Bool {
lock.lock(); defer { lock.unlock() }
return states.indices.contains(state) && states[state].isFreeSpan
}

/// Preview a copy: discarded proposals must not intern states or release
/// the grammar. A token touching a marker is protected even when its final
/// bytes return to the same free state.
func isFreeSpanContinuation(state: Int, tokenID: Int) -> Bool {
lock.lock(); defer { lock.unlock() }
guard states.indices.contains(state), states[state].isFreeSpan,
vocabulary.pieces.indices.contains(tokenID),
!vocabulary.stopTokenIDs.contains(tokenID) else { return false }
let piece = vocabulary.pieces[tokenID]
guard !piece.isEmpty else { return false }
let boundary = states[state]
var next = boundary
for byte in piece {
guard next.consume(byte, schema: schema, markers: markers), next.isFreeSpan else { return false }
}
return next == boundary
}

func nextState(state: Int, tokenID: Int) -> Int? {
lock.lock(); defer { lock.unlock() }
guard vocabulary.pieces.indices.contains(tokenID) else { return nil }
Expand Down
3 changes: 3 additions & 0 deletions provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,8 @@ public enum LaunchAgent: Sendable {
/// rectangular cap override is the operator's lever to REDUCE speculative
/// verification work short of disabling MTP entirely; it must survive
/// install/restart like the kill switches.
/// `DARKBLOOM_CONSTRAINT_SPANS`: opt-in drafting through free Qwen
/// reasoning/text spans; the SDK snapshots it when constructing an engine.
/// `DARKBLOOM_KV_BACKEND_GUARD`: the crash-loop guard's record-path
/// override (`KVBackendGuardStore.pathEnvKey`). The guard has one writer
/// (the launchd watchdog — same key in `WatchdogAgent.passthroughEnvKeys`)
Expand Down Expand Up @@ -504,6 +506,7 @@ public enum LaunchAgent: Sendable {
"DARKBLOOM_CBV2_KV_QUANTIZATION",
"DARKBLOOM_CBV2_CHECKPOINT_QUANTIZATION",
"DARKBLOOM_CBV2_MTP", "DARKBLOOM_MTP_MAX_RECTANGULAR_TOKENS",
"DARKBLOOM_CONSTRAINT_SPANS",
"DARKBLOOM_KV_BACKEND_GUARD",
"DARKBLOOM_MLX_CACHE_LIMIT_GB", "DARKBLOOM_MLX_MEMORY_RESERVE_GB",
"DARKBLOOM_R2_CDN_URL",
Expand Down
Loading
Loading