Skip to content
Draft
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/qwen35-default-penalty-keeps-mtp-and-cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Qwen 3.5/3.6 speculate and cache again

- From 0.10.5 a request to the catalog `Qwen3.5-9B`, `qwen3.5-35b-a3b` or `qwen3.6-35b-a3b-vl-mtp-mxfp8` build that omitted `presence_penalty` got the model card's 1.5. The engine drafts no row with a penalty, and these builds' MTP heads keep the prompt history, so such a row also stages no resident or SSD prefix checkpoint. The coordinator adds only these builds' registry `temperature`, `top_p` and `top_k`, so every request whose client sent no penalty of its own ran without MTP and donated no checkpoint: on the two 35B builds OpenRouter's cached share of prompt tokens fell from 27–42% on 10-30 to 0% from 10-31, and production had no cache holders for them.
- Omitted fields now take the cards' `temperature` 1.0, `top_p` 0.95 and `top_k` 20 only, which still replace the greedy decoding that looped to `max_tokens` (#1530). A request's own `presence_penalty` still applies.
28 changes: 19 additions & 9 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -2603,7 +2603,7 @@ disabled for this hybrid model.
| `top_p` | `topP` | artifact default, else `1.0` |
| `top_k` | `topK` | artifact default, else `0` |
| `repetition_penalty` | `repetitionPenalty` | artifact default, else `1.0` |
| `frequency_penalty` / `presence_penalty` | `frequencyPenalty` / `presencePenalty` | `0`; `presence_penalty` takes a model-card default (catalog Qwen 3.5/3.6) |
| `frequency_penalty` / `presence_penalty` | `frequencyPenalty` / `presencePenalty` | `0` |
| `seed` | `seed`; also keys a stable engine request id | nil |
| `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` |
| `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` |
Expand All @@ -2627,14 +2627,7 @@ recommends). The exact `prism-ml/Ternary-Bonsai-2-9B-mlx-2bit` and
`EigenLabs/Ternary-Bonsai-2-9B-MLX-2bit` identities also require `model_type == prism_hadamard_qwen35` and honors its pinned artifact
defaults (`temperature 1.0`, `top_p 0.95`, `top_k 20`, `do_sample true`). Its
qualification requests explicitly supply `presence_penalty: 1.5`; that value
is absent from the artifact and is not injected as a default. The catalog
`Qwen3.5-9B`, `qwen3.5-35b-a3b` and `qwen3.6-35b-a3b-vl-mtp-mxfp8` builds
(`EngineV2SamplingDefaults.qwen35CardModelTypes`, each bound to its `model_type`)
ship no `generation_config.json`; omitted knobs take their model cards'
thinking-mode values
(`EngineV2SamplingDefaults.qwen35CardDefaults`: `temperature 1.0`, `top_p 0.95`,
`top_k 20`, `presence_penalty 1.5`). Greedy decoding with no presence penalty
made them repeat themselves until `max_tokens` (#1530). This request
is absent from the artifact and is not injected as a default. This request
policy enables native channels, nested reasoning and forced-media framing.
These exact 9B identities separately default to paged attention and encrypted SSD
prefix caching. Explicit operator selections, kill switches, native capability
Expand Down Expand Up @@ -2663,6 +2656,23 @@ head's artifact contract and unchanged base precision are documented in
F16 and affine 4-bit/group-64 heads, preserving the original path for rollback.
Actual model, cache and speed qualification
remain separate from this automatic intent and validated loading path.

The catalog `Qwen3.5-9B`, `qwen3.5-35b-a3b` and `qwen3.6-35b-a3b-vl-mtp-mxfp8`
builds (`EngineV2SamplingDefaults.qwen35CardModelTypes`, each bound to its
`model_type`) take their model cards' thinking-mode sampling values for omitted
knobs (`EngineV2SamplingDefaults.qwen35CardDefaults`: `temperature 1.0`,
`top_p 0.95`, `top_k 20`). The 9B ships no `generation_config.json`; the 35B
builds' files declare the same three values; none of these builds is admitted
to artifact defaults, so no file is read for them. Greedy decoding made them
repeat themselves until `max_tokens` (#1530). The cards' `presence_penalty 1.5`
is not a default: these builds' MTP heads keep the prompt history, and the
engine neither drafts nor checkpoints a row with a penalty
([prefix caching](prefix-cache.md#invariants)). A default penalty would turn
off MTP and the resident and SSD prefix cache for every request that omits it,
coordinator requests included: the coordinator adds only the registry's
`temperature`, `top_p` and `top_k`, and no penalty unless the registry sets
one. A request's own `presence_penalty` still applies.

Other model identities keep the legacy defaults in the table byte-for-byte. `do_sample: false` or an absent/unreadable file is legacy. The
sampler is not part of prompt or cache identity, so prefix-cache and SSD
checkpoint identity do not change.
Expand Down
14 changes: 13 additions & 1 deletion docs/architecture/prefix-cache.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# KV cache layouts and prefix caching

> Last updated: 2026-11-07
> Last updated: 2026-11-09

How the provider lays out a request's KV cache, how it decides whether a
previously computed prefix can be reused, and where reusable state lives:
Expand Down Expand Up @@ -958,6 +958,17 @@ rules applied to these signals.
geometry; a matching longer token branch cannot supply an absent shorter
checkpoint — `HybridPrefixCache.swift` (`lookup`),
`HybridPrefixCacheContract.swift` (`CBv2RecurrentCheckpointGeometry`).
9. On a slot whose MTP head keeps the prompt history (for example the
embedded Qwen 3.5/3.6 heads), only a row that can speculate stages a
resident or SSD checkpoint. A row with a token constraint, logprobs,
`logit_bias`, a repetition, frequency or presence penalty, or a `stop` string
(`EngineLoopV2.mtpBasicEligible`) observes no assistant history, so it
donates nothing, though it can still restore. Provider sampling defaults
therefore set no penalty on these builds —
`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift`
(`mtpTakeHistoryState`),
`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointCapture.swift`,
`EngineV2SamplingDefaults.swift`.

## Failure modes

Expand All @@ -969,6 +980,7 @@ rules applied to these signals.
| `pending` / `scan_pending`, `error` / `scan_failed` | Startup disk scan not finished or failed | `SSDPrefixCache.swift` |
| SSD repeat served cold | Prefix shorter than one block; staging reservation refused; donation below the effective-token floor; TTL expiry; box-wide LRU eviction | `SSDPrefixCache.swift` (`donate`), `SSDBlockIndex.swift` |
| Recurrent repeat served cold | No actual checkpoint, incompatible geometry/identity, scope mismatch, SSD stage refusal/eviction, or opt-in memory bank eviction | `HybridPrefixCache.swift`, `EngineLoopV2+HybridPrefix.swift`, `PrefixCachePolicy+Hybrid.swift` |
| A Qwen MTP model gets no coordinator holders although its slots are cache-ready | Its requests cannot speculate (a penalty, `stop` string, logprobs, `logit_bias` or token constraint), so they stage no checkpoint ([invariant 9](#invariants)) | `EngineLoopV2+MTPExecution.swift` (`mtpTakeHistoryState`), `CompleteCheckpointCapture.swift`, `EngineV2SamplingDefaults.swift` |
| Local memory hit gives no coordinator routing preference | Paged resident publication is not implemented; recurrent slot missing verified identity; or holder evidence expired/invalidated | `ResidentPrefixCacheEvidence.swift`, [coordinator/registry/cache_routing_hints.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/registry/cache_routing_hints.go) |
| Load refused with `pagedUnavailable` | Explicit `paged` and preflight/capacity/pool construction failed | `EngineV2Factory+BackendPreparation.swift` |
| Every slot contiguous despite `paged` config | `DARKBLOOM_CBV2_PAGED_KV` set to a negative value, or `supportsPagedKV == false` | `EngineV2KVBackendPolicy.swift`, `EngineV2Factory+BackendPreparation.swift` |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ enum EngineV2Translation {
minP: 0,
repetitionPenalty: request.repetition_penalty ?? defaults.repetitionPenalty ?? 1.0,
frequencyPenalty: request.frequency_penalty ?? 0,
presencePenalty: request.presence_penalty ?? defaults.presencePenalty ?? 0,
presencePenalty: request.presence_penalty ?? 0,
seed: request.seed,
logitBias: logitBias,
topLogprobs: topLogprobs(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,28 @@
// Rules:
// * Applied ONLY to fields the request omits. Explicit request values
// always win (`temperature: 0` still means greedy).
// * `seed`, `logit_bias`, the frequency penalty and `max_tokens` are
// untouched; only a model-card default sets the presence penalty.
// * `seed`, `logit_bias`, the frequency/presence penalties and `max_tokens`
// are untouched.
// * Gated per model family with explicit admission, like
// `ToolChoiceEnforcementPolicy.nativeStructuredTarget`: the admitted Nemotron
// and owned Bonsai 9B listings, native Flint and the exact GLM-5.3-Flash
// identities (catalog `glm-5.3-flash` and the local qualification download)
// honor their artifact defaults.
// The catalog Qwen 3.5/3.6 builds ship no `generation_config.json`; they
// take their model cards' thinking-mode values (`qwen35CardDefaults`),
// whose presence penalty stops greedy decoding looping to `max_tokens`.
// The catalog Qwen 3.5/3.6 builds take their model cards' thinking-mode
// sampling values (`qwen35CardDefaults`) instead of the greedy decoding
// that looped to `max_tokens`. The 9B ships no `generation_config.json`;
// the 35B builds' files declare the same three values; none of these
// builds is admitted here, so no file is read for them.
// Every other model keeps the legacy defaults byte-for-byte.
// * `do_sample: false` in the file means greedy (legacy), matching HF
// semantics; an absent or unreadable file is legacy.
// * Resolved once at slot construction (like the stop-token set). The
// sampler is not part of prompt or cache identity, so prefix-cache and
// SSD checkpoint identity are unchanged.
// SSD checkpoint identity are unchanged. It still decides whether a row
// speculates: the engine drafts no row with a repetition, frequency or
// presence penalty (`EngineLoopV2.mtpBasicEligible`), and on a slot whose
// MTP head keeps the prompt history such a row captures no resident or SSD
// checkpoint either.

import Foundation
import MLXLMCommon
Expand All @@ -44,17 +50,15 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable {
public var topP: Float?
public var topK: Int?
public var repetitionPenalty: Float?
public var presencePenalty: Float?

public init(
temperature: Float? = nil, topP: Float? = nil, topK: Int? = nil,
repetitionPenalty: Float? = nil, presencePenalty: Float? = nil
repetitionPenalty: Float? = nil
) {
self.temperature = temperature
self.topP = topP
self.topK = topK
self.repetitionPenalty = repetitionPenalty
self.presencePenalty = presencePenalty
}

/// Legacy behavior: every omitted knob collapses to the contract's no-op
Expand All @@ -64,9 +68,12 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable {
public static let legacy = EngineV2SamplingDefaults()

/// The model cards' thinking-mode values (the template default), shared by
/// these exact catalog builds and their `model_type`.
static let qwen35CardDefaults = EngineV2SamplingDefaults(
temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5)
/// these exact catalog builds and their `model_type`, without the cards'
/// `presence_penalty` 1.5: these builds' MTP heads keep the prompt
/// history, so a default penalty would turn off MTP and the resident and
/// SSD prefix cache for every request that omits it. A request's own
/// penalty still applies.
static let qwen35CardDefaults = EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20)
static let qwen35CardModelTypes = [
"Qwen3.5-9B": "qwen3_5",
"qwen3.5-35b-a3b": "qwen3_5_moe",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,10 @@ struct EngineV2SamplingDefaultsTests {
#expect(!EngineV2SamplingDefaults.honorsArtifactDefaults(modelId: "flint", modelType: "unknown"))
}

/// The catalog Qwen 3.5/3.6 builds have no generation_config.json: omitted
/// knobs take the model cards' thinking-mode values, explicit ones win.
/// The catalog Qwen 3.5/3.6 builds' omitted knobs take the model cards'
/// thinking-mode values without reading a file (the 9B ships no
/// generation_config.json; the 35B builds' files declare the same three
/// values); explicit ones win.
@Test func qwen35CatalogBuildsUseTheirModelCardDefaults() throws {
for (id, type) in EngineV2SamplingDefaults.qwen35CardModelTypes {
#expect(EngineV2SamplingDefaults.resolve(modelId: id, modelType: type, modelDirectory: nil)
Expand All @@ -93,7 +95,7 @@ struct EngineV2SamplingDefaultsTests {
modelId: "Qwen3.5-9B", modelType: "qwen3_5", modelDirectory: nil)
let omitted = EngineV2Translation.samplingParams(from: try request(bareRequest), defaults: defaults)
#expect(omitted.temperature == 1 && omitted.topP == 0.95 && omitted.topK == 20)
#expect(omitted.presencePenalty == 1.5 && omitted.repetitionPenalty == 1)
#expect(omitted.presencePenalty == 0 && omitted.repetitionPenalty == 1)
let explicit = EngineV2Translation.samplingParams(
from: try request(#"{"model":"m","messages":[],"temperature":0,"presence_penalty":0}"#),
defaults: defaults)
Expand All @@ -103,6 +105,33 @@ struct EngineV2SamplingDefaultsTests {
}
}

/// These builds' embedded MTP heads keep the prompt history (`mtp_mode`
/// `auto` for `qwen3_5`/`qwen3_5_moe`), so the engine captures their
/// resident and SSD checkpoints only from rows that can speculate, and it
/// never speculates a row with a repetition, frequency or presence penalty
/// (`EngineLoopV2.mtpBasicEligible`, `mtpTakeHistoryState`). A default
/// penalty turns off MTP and the prefix cache for every request that omits
/// it, coordinator bodies included: the coordinator adds only the
/// registry's temperature, top_p and top_k, and no penalty unless the
/// registry sets one.
@Test func qwen35CardDefaultsLeaveDefaultRequestsSpeculativeAndCacheable() throws {
let coordinatorBody =
#"{"model":"m","messages":[{"role":"user","content":"hi"}],"temperature":1,"top_p":0.95,"top_k":20}"#
for (id, type) in EngineV2SamplingDefaults.qwen35CardModelTypes {
#expect(MTPMode.auto.enablesMTP(forModelType: type, embeddedArtifactDeclared: true, modelID: id))
let defaults = EngineV2SamplingDefaults.resolve(modelId: id, modelType: type, modelDirectory: nil)
for body in [bareRequest, coordinatorBody] {
let sampling = EngineV2Translation.samplingParams(from: try request(body), defaults: defaults)
#expect(sampling.temperature == 1 && sampling.topP == 0.95 && sampling.topK == 20, "\(id)")
#expect(sampling.presencePenalty == 0, "\(id): \(body)")
#expect(sampling.frequencyPenalty == 0 && sampling.repetitionPenalty == 1, "\(id)")
}
let explicit = EngineV2Translation.samplingParams(
from: try request(#"{"model":"m","messages":[],"presence_penalty":1.5}"#), defaults: defaults)
#expect(explicit.presencePenalty == 1.5, "\(id)")
}
}

/// The exact locally qualified GLM artifact declares temperature 1.0 and
/// top_p 0.95 without `do_sample`; other GLM IDs or types stay legacy.
@Test func gateAdmitsOnlyTheQualifiedGLMArtifact() throws {
Expand Down
Loading