Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
7891de7
test(provider): Gemma 4 JSON answers are grammar-constrained (red)
jonathan308 Nov 13, 2026
ab972c2
feat(provider): Gemma 4 JSON answers are grammar-constrained after th…
jonathan308 Nov 13, 2026
2a888f6
fix(provider): Gemma JSON answers share masks across indentation; rev…
jonathan308 Nov 13, 2026
8239bbc
test(provider): the Gemma fixture keeps the prompt's words whole; the…
jonathan308 Nov 13, 2026
db19ace
refactor(provider): Gemma JSON answers, the refactor pass
jonathan308 Nov 13, 2026
12cda52
test(provider): Gemma JSON masks equal their transitions; exact real-…
jonathan308 Nov 13, 2026
2baa9b5
test(provider): the mask oracle's array position sits inside the JSON…
jonathan308 Nov 13, 2026
ecfa075
feat(provider): Gemma JSON answers enforce Pydantic- and zod-style sc…
jonathan308 Nov 13, 2026
0829cad
fix(provider): the schema rewrite resolves only plain definition name…
jonathan308 Nov 13, 2026
e6bfd86
fix(provider): the schema rewrite stays shallow and reads only draft-…
jonathan308 Nov 13, 2026
3810f18
refactor(provider): the schema rewrite's refactor pass (no behavior c…
jonathan308 Nov 13, 2026
2354404
fix(provider): the schema rewrite pays for what it copies
jonathan308 Nov 13, 2026
347dc46
fix(provider): the schema rewrite pays for the bytes it hashes
jonathan308 Nov 13, 2026
941157b
fix(provider): the schema rewrite compares only short keys
jonathan308 Nov 13, 2026
3502545
fix(provider): the schema rewrite bounds what the compiler reads per …
jonathan308 Nov 13, 2026
cab7aed
refactor(provider): the schema rewrite's hardening, refactor pass (do…
jonathan308 Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/gemma-json-answer-grammar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Gemma 4 JSON answers follow the requested format

- A Gemma 4 26B request with a JSON `response_format` (`json_object`, or `json_schema` within the provider's supported subset) is now sampled under a grammar: after the model's thought, if any, the answer is exactly one JSON value of the requested format, with no code fences, surrounding prose or trailing text. Schemas as Pydantic, OpenAI's strict mode or zod write them (`$defs`/`$ref`, optional fields as `anyOf` with null, `$schema`) are enforced as written; a `json_schema` the grammar still does not cover is held to a JSON object when its root is an object. The thought is unchanged.
- Requests the grammar does not cover (tools, a `tool_choice` other than `auto` without tools, `stop` sequences, images, other schemas) and cluster pairs are answered as before; an answer cut at `max_tokens` still ends as `length`, never as an error. `DARKBLOOM_GEMMA_JSON_ANSWERS=off` turns the grammar off on a Mac.
85 changes: 84 additions & 1 deletion docs/architecture/inference.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Provider inference engine

> Last updated: 2026-11-12
> Last updated: 2026-11-13

How a chat-completion request is served inside the `darkbloom` provider
process: one in-process engine (`mlx-swift-lm`
Expand Down Expand Up @@ -3390,6 +3390,89 @@ spliced across a boundary the reasoning parser later hides. Required and named
(`provider-swift/Sources/ProviderCore/Inference/Tools/GemmaNoToolTokenConstraint.swift`,
`provider-swift/Sources/ProviderCore/Inference/Tools/GemmaTokenVocabulary.swift`).

### Constrained Gemma 4 JSON answers

Gemma 4 answers to a JSON `response_format` are sampled under the same JSON
grammar as constrained Qwen answers (below), with three differences: Gemma's
vocabulary, its thought framing, and best-effort semantics.
`ToolConstraintFactory.make` asks `GemmaJSONAnswerPolicy` first: a text request
on `gemma4` or `gemma4_text` with a JSON `response_format`, no `tools`, no
`tool_choice` (or a tool-free `auto`), no client `stop`, the `gemma4` reasoning
parser and the pinned chat template (`TokenizerHandle.toolConstraintContractVerified`)
gets a `GemmaJSONAnswerConstraint`. The prompt is unchanged.

**Vocabulary.** Gemma's tokenizer is SentencePiece BPE with byte fallback, not
byte-level BPE. `GemmaAnswerPieces` gives every id the bytes its decoder writes:
U+2581 becomes a space, a `<0x80>`…`<0xFF>` token is that byte, other pieces are
their UTF-8 (the provider's tokenizer runs no clean-up for Gemma). The 24 added
tokens and the `<unusedN>` slots have no piece, and neither do the ASCII
byte-fallback tokens: a byte-fallback run is decoded as a whole, so what one byte
becomes depends on its neighbours (a run that is not UTF-8 reads as U+FFFD),
while every ASCII character JSON needs has a piece of its own. Non-ASCII bytes
occur only inside strings, where U+FFFD is still a character.
Before constraining, `GemmaAnswerPieces.vocabulary` checks `<|channel>` 100,
`<channel|>` 101, `<turn|>` 106 and `<eos>` 1 by id, spelling, encoding and
decoding, that the tokenizer has exactly 262,144 ids, and that `<turn|>` and
`<eos>` are engine stop tokens. The
vocabulary is built on the first such request per loaded tokenizer and stop set
and cached (two entries).

**Phases.** The rendered prompt's tail selects the first phase
(`GemmaJSONAnswerPolicy.initialPhase`). Thinking off renders an empty, closed
thought (`<|turn>model\n<|channel>thought\n<channel|>`), so output starts in the
answer. Thinking on ends at `<|turn>model\n`, so a thought may open with
`<|channel>`, or the answer may start at once (whitespace before either stays
content, so an answer can read `"\n{...}"`, still one JSON value). The thought
is free text: no EOS or added token other than the two thought markers, and the
first `<channel|>`, as its token or spelled from ordinary pieces (the stream's
Gemma parser reads text), ends it. The answer is one JSON value of the request's
grammar (`JSONAnswerFormat`, `FlintJSONGrammar`);
no Gemma control spelling can complete in it, strings included. `<turn|>` or
`<eos>` is allowed once the value is complete, and a value that delimits itself
(an object, array, string or literal) is followed by the terminator only, never
by text a client would have to strip. JSON whitespace outside strings runs at
most 64 bytes (`GemmaJSONAnswerBoundary.maximumWhitespaceRun`), so a model that
keeps reaching for a refused spelling (a code fence) cannot fill its budget with
blank lines. States that differ only in a run
no piece can push past that cap share one mask key (`maskEquivalent`), so
indentation does not multiply mask builds; a request keeps at most two broad
allowed sets (about 2 MB each) and the sampler its per-key device masks.

**Best effort.** Unlike constrained Qwen answers, nothing is validated after
generation (`MultiModelBatchSchedulerEngine` checks only `JSONAnswerConstraint`
answers): a budget that ends first stays `length` with the partial value, as
before. A request whose interned states reach the cap
(`GemmaJSONAnswerConstraint.defaultMaximumStates`, 16,384) continues
unconstrained instead of failing. A `json_schema` in the shapes common clients
generate is first rewritten into the shared subset where the result admits
exactly the same instances (`ResponseSchemaRewrite`: `$ref`s to plainly named
entries of the root's `$defs`/`definitions` inlined, a one-branch `allOf`
unwrapped, `anyOf` of one schema and `{"type": "null"}` made nullable, with only
annotations beside them; `$comment` on every node it rewrites, the root's `$id`
and a draft-06 to 2020-12 `$schema` dropped; at most 16 levels, 8 references or
compositions in a row and a bounded amount of copying and hashing,
`maximumWork`).
One still outside it (`pattern`, `format`, a recursive `$ref`, a wider `anyOf`,
an older `$schema`, a nullable enum of 128 values, …) whose root is
`"type": "object"` is held to a JSON object; any other
unsupported schema, an unpinned template or tokenizer, another
prompt end or a nonpositive budget keeps prompt-only steering with one
content-free line (category `json-answer`). An engine that runs no token
constraint (a cluster pair or a native-tracked engine) would refuse one, so
`EngineV2Bridge.admittedConstraint` submits the request there unconstrained.
`DARKBLOOM_GEMMA_JSON_ANSWERS=off` restores prompt-only answers everywhere.

**Speculative decoding.** A constrained row never drafts
(`EngineLoopV2.mtpBasicEligible`), and Gemma's target is not recurrent, so a
step that holds one runs target-only for every row in it, as for a `stop`,
penalty or logprob row (see the Qwen notes below). Rows in steps without one
are unchanged.

Sources: `provider-swift/Sources/ProviderCore/Inference/Tools/GemmaJSONAnswerPolicy.swift`,
`provider-swift/Sources/ProviderCore/Inference/Tools/ResponseSchemaRewrite.swift`,
`provider-swift/Sources/ProviderCore/Inference/GemmaJSONAnswerConstraint.swift`,
`provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift`.

### Constrained Qwen JSON answers

The format instruction alone leaves some Qwen answers outside the requested
Expand Down
3 changes: 2 additions & 1 deletion docs/reference/configuration.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Configuration reference

> Last updated: 2026-11-12
> Last updated: 2026-11-13

Provider CLI and native-runtime environment variables, compiled defaults and reading symbols. Secrets are named, never valued. Unless specified otherwise, values are read at process start.

Expand Down Expand Up @@ -541,6 +541,7 @@ and rollback are defined in the [provider configuration reference](../provider/c
| `DARKBLOOM_GLM_DECODE_STEPS_BETWEEN_CHUNKS` | integer `0`…`64` (surrounding spaces ignored; blank is unset) | `8` (`glm5NextDefaultDecodeStepsBetweenChunks`) | `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Configuration.swift` (`glm5NextDecodeStepsBetweenChunks`) | Decode-only steps after each GLM prompt chunk while other requests decode; a step without decode rows is never held. `0` is the rollback to a chunk in every step. Any other value refuses the GLM load. First-token deadline admission charges the held steps ([deadlines](../architecture/inference.md#deadlines)). Forwarded to the launchd provider job. |
| `DARKBLOOM_TTFT_FUSED_CAUSAL_PREFILL` | exact `0` disables | on | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/AttentionV1.swift` (`CBv2AttentionV1.fusedCausalPrefillEnabled`, `usesFusedCausalPrefill`) | Full-attention prompt chunks whose head geometry MLX serves with a fused kernel take one `.causal` SDPA call on either KV backend, except live packed paged KV ([eligible chunks](../architecture/inference.md#scheduler-and-loop-configuration)); `0` returns them to 128-query blocks. Read once per process; not forwarded to LaunchAgents. |
| `DARKBLOOM_CBV2_LEGACY_REQUEST_TIMEOUT` | affirmative | off | `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Configuration.swift` | Restores the legacy per-request timeout. |
| `DARKBLOOM_GEMMA_JSON_ANSWERS` | `off`, `0`, `false`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Tools/GemmaJSONAnswerPolicy.swift` (`GemmaJSONAnswerPolicy.enabled`) | Gemma 4 answers to a JSON `response_format` are sampled under the request's JSON grammar after a free thought ([constrained Gemma 4 JSON answers](../architecture/inference.md#constrained-gemma-4-json-answers)); off restores prompt-only answers. Read once at launch. Forwarded by LaunchAgent. |
| `DARKBLOOM_CBV2_MTP` | negative disables | unset (beta flag decides) | `provider-swift/Sources/ProviderCore/SpecDec/SpecDecArtifactFunnel.swift`; `provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift` | Kill switch for MTP speculation; beats the `provider.toml` beta flag. See [`../provider/beta-features.md`](../provider/beta-features.md). |
| `DARKBLOOM_MTP_MAX_RECTANGULAR_TOKENS` | integer | policy default | `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift` | Tighten-only cap on rectangular MTP verification tokens. |
| `DARKBLOOM_TTFT_QWEN_MTP_CHAINED` | `0`, `false`, `no`, `off` disable | on | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envOrdinaryDecodeHistory`) | While no Qwen inline-MTP row can speculate (more decode rows than its speculative batch of one), steps in which every MTP-eligible row is decoding run as ordinary chainable decode with no policy top-two; finalize feeds the assistant history and carry. Off restores hidden-returning seed steps. Not forwarded to LaunchAgents. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ extension EngineV2Bridge {
/// (`GenerationLoopGuardPolicy`); nil leaves it unguarded.
loopGuard: GenerationLoopGuard? = nil
) async throws -> AsyncStream<GenerationEvent> {
let tokenConstraint = Self.admittedConstraint(tokenConstraint, servesDistributedPair: servesDistributedPair,
tracksNativeShutdown: tracksNativeShutdown)
if let clusterStillImages {
guard mimoClusterImages == nil, multimodal == nil,
let binding = try clusterGLMImageIngress() else { throw DistributedEngineError.refused(.mediaUnsupported) }
Expand Down
Loading
Loading