diff --git a/changelog.d/inkling-mtp-max-draft.md b/changelog.d/inkling-mtp-max-draft.md new file mode 100644 index 0000000000..b17dd3f956 --- /dev/null +++ b/changelog.d/inkling-mtp-max-draft.md @@ -0,0 +1,4 @@ +### Inkling 2 Mini's draft cap can be set per Mac + +- `DARKBLOOM_INKLING_MTP_MAX_DRAFT` sets the most drafts one Inkling 2 Mini MTP round may propose: a whole number from 1 to 7, with values outside that range clamped. Unset, it stays at 7, the drafter's whole block, as before. +- The adaptive depth policy still picks each round's depth at or below the cap, and every draft is verified exactly, so tokens are the same at any cap. Only how much each round tries changes. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 7d273bb0fb..41e4a0d36f 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3501,6 +3501,11 @@ the catalog `gemma-4-26b-qat-4bit`, which drafted every answer of OpenRouter's on a single Mac. Qwen 3.8 pairs never read this rule and were already exact. Exact keeps the model's output distribution; its tokens are not bit-identical to MTP off, since verify windows round differently. +Inkling 2 Mini replaces the generic depth with its drafter's own profile +(`Inkling2DSparkDrafter.defaultMTPConfig`: up to 7 drafts, adaptive), and +`DARKBLOOM_INKLING_MTP_MAX_DRAFT` (1 to 7) lowers that cap; the acceptance +setting still applies (`Inkling2MTPProfilePolicy` in +`provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift`). Under typical acceptance a draft is kept when the sampler-filtered target row gives it probability above `min(1, 0.2 * exp(-H))`, `H` the row's entropy in nats; the first rejected position and the bonus position still commit the keyed diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index dd2e6f6d37..0cc53b3899 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -639,6 +639,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY` | trimmed, case-insensitive `0`, `false`, `no`, `off` drop the default; any other value keeps it | on: the model card's 1.5 | `provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift` (`qwen35NineBKeepsCardPenalty`) | The catalog `Qwen3.5-9B`'s `presence_penalty` for a request that omits one (0.10.13; 0.10.12 had none, and its answers with `max_tokens` ≥ 8,192 ran to the limit about three times as often: 5.5 % against 1.7 %). `0` restores 0.10.12's no-penalty default. A request's own value, the coordinator's registry default included, always wins: while the registry sets `presence_penalty` for `Qwen3.5-9B`, routed requests carry it and `0` affects only local requests, so rolling routed traffic back also needs the registry value removed or set to `0`. `darkbloom start` passes it to the launchd job. | | `DARKBLOOM_TTFT_SHAPE_WARMUP` | trimmed, case-insensitive `0`, `false`, `no`, `off` disable; `always` skips the probe | unset: probe-gated warmup | `provider-swift/Sources/ProviderCore/Inference/Performance/ModelCalibrationPolicy.swift` (`shapeWarmupMode`) | Excluded load-time [shape warmup](../architecture/inference.md#model-startup-calibration) for ordinary `EngineV2` slots: a 128-token shader-cache probe runs twice and only a cold cache runs the shape cells, within 20 seconds per engine. Trains no rate or counter. Forwarded to the LaunchAgent. | | `DARKBLOOM_INKLING2_DEPTH_WARMUP` | trimmed, case-insensitive `0`, `false`, `no`, `off` disable | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Inkling2DepthWarmup.swift` (`enabled`) | Inkling 2 Mini only: after its shape warm-up, every draft depth 0 to 7 runs once per load on a private engine with its own scratch paged pool (the `Inkling 2 depth warmup` log line reports cells and time); off skips it and keeps the shape cells. `DARKBLOOM_TTFT_SHAPE_WARMUP=0` skips both. See the [Inkling 2 Mini reference](inkling2-mini-support.md#prompt-contract). Read when a load warms. | +| `DARKBLOOM_INKLING_MTP_MAX_DRAFT` | a whole number, clamped to 1 to 7 (surrounding whitespace ignored); other values keep the default and log a warning | `7` | `provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift` (`maxDraftTokens`) | Inkling 2 Mini only: the most drafts one DSpark round may propose. The adaptive depth policy still picks each round's depth at or below it, down to plain decode, and the verify envelope follows the cap (8 rows × (cap + 1)). Every draft is verified exactly, so tokens are unchanged; only how much a round tries changes. The load warm-up still runs depths 0 to 7. Read when the model loads. Forwarded to the LaunchAgent. | | `DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL` | integer layers | projected from `provider.toml` (`18`) | `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift` | Gemma-4 prefill chunk-eval layers; the provider sets it for the engine, `scripts/install.sh` sets `18` for the smoke test. | | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | | `DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK` | `0` skips | on | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VLMTextExtraction.swift` | VLM text-extraction parity check. | diff --git a/docs/reference/inkling2-mini-support.md b/docs/reference/inkling2-mini-support.md index 4dfa3742bb..d932761a74 100644 --- a/docs/reference/inkling2-mini-support.md +++ b/docs/reference/inkling2-mini-support.md @@ -17,7 +17,7 @@ Reference for the provider's side of Thinking Machines' Inkling 2 Mini (`inkling | Prefill geometry | 2,048-token prompt chunks and no solo stripe: with MLX's own prefill products (the SDK default) the engine keeps a fixed chunk grid of the scheduler's chunk and captures a prefix checkpoint only where every prompt range was exactly one grid chunk, so a solo stripe (an operator `DARKBLOOM_CBV2_SOLO_PREFILL_STRIPE` included) is not used for this model; boundaries fall at 2,048, 4,096, 6,144, ... `DARKBLOOM_CBV2_PREFILL_CHUNK` still sets the chunk, and so the grid. The step budget stays the SDK's 2,048 tokens unless `DARKBLOOM_CBV2_STEP_TOKENS` sets it (the grid gives a step's first prompt row its whole chunk past the budget), so one step carries at most one 2,048-token chunk beside its decode rows, as the solo stripe did; paged window rings and step bounds take max(chunk, stripe) = 2,048 as before | `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Configuration.swift` (`prefillGeometry`, `inkling2PrefillChunkTokens`) | | Image input | Images in user and tool-result messages. Each image's tower rows replace its run of token 200054 as causal tokens at scalar positions, no position state; only this model's cache bank admits causal media; content parts keep their message order into the template; video and media for a checkpoint without the tower are refused before any decode; media stays out of durable prefix checkpoints (engine rule) | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` (`buildInkling2Submission`, `validateInkling2Media`); `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Production.swift` | | Prefix cache | On by policy for served identities (the global switch still wins). Complete checkpoints use the SDK's historical recurrent layout, which carries all 48 cache slots: the 8 full-attention slots' K/V for every prompt position, the 40 sliding slots' last 1,024 positions, and every slot's convolution and recurrent state; with the DSpark drafter's rounds on, the drafter's own history too (`native-paged-historical-recurrent-mtp-v1`, otherwise `native-paged-historical-recurrent-v1`). Rows are stored exactly as served: the layout takes no lossy checkpoint profile, so the fleet's default profile leaves them native (the identity records `native`). Checkpoints sit on whole 2,048-token prefill chunks; a follow-up restores the deepest one below its prompt and recomputes the rest. The store, its encryption, cache identity (weights, prompt contract, build, numerics, drafter configuration) and tenant scoping (`cacheSalt`) are the ones every complete-checkpoint model uses; media requests are not captured (engine rule) | `provider-swift/Sources/ProviderCore/Inference/PrefixCache/PrefixCachePolicy+Activation.swift` (`isEnabled`); `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory+CompletePrefixCache.swift` (`completeCheckpointStorage`); `provider-swift/Sources/ProviderCore/Inference/PrefixCache/CompleteCheckpointStorageIdentity.swift` (`historicalRecurrent`) | -| Drafter | `mtp_config` on the native target declares the DSpark drafter in `mtp.safetensors` beside the target, outside its index. Its header is read with the inline bound; every tensor range must lie in the file; the header digest pins its tensor selection and is revalidated before load. Served on by default: the drafter loads bound to the text model (also when the VLM wrapper serves), with its own engine profile (up to 7 drafts, up to 8 speculating rows, adaptive depth down to plain decode); image rows run target-only | `provider-swift/Sources/ProviderCore/SpecDec/SpecDecStore.swift` (`declaresInkling2DSparkMTP`, `inspectInlineArtifact`, `revalidateForLoad`); `provider-swift/Sources/ProviderCore/Inference/MTP/EngineV2MTPAssistant.swift`; `EngineV2SlotFactory.swift` (`Inkling2DSparkDrafter.defaultMTPConfig()`) | +| Drafter | `mtp_config` on the native target declares the DSpark drafter in `mtp.safetensors` beside the target, outside its index. Its header is read with the inline bound; every tensor range must lie in the file; the header digest pins its tensor selection and is revalidated before load. Served on by default: the drafter loads bound to the text model (also when the VLM wrapper serves), with its own engine profile (up to 7 drafts, up to 8 speculating rows, adaptive depth down to plain decode; `DARKBLOOM_INKLING_MTP_MAX_DRAFT` lowers the draft cap, see the [configuration reference](configuration.md)); image rows run target-only | `provider-swift/Sources/ProviderCore/SpecDec/SpecDecStore.swift` (`declaresInkling2DSparkMTP`, `inspectInlineArtifact`, `revalidateForLoad`); `provider-swift/Sources/ProviderCore/Inference/MTP/EngineV2MTPAssistant.swift`; `EngineV2SlotFactory.swift` (`Inkling2DSparkDrafter.defaultMTPConfig()`); `provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift` | ## Cache layout diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift index 36388c319f..62d2ce7636 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift @@ -313,8 +313,17 @@ enum EngineV2SlotFactory { if assistantHandle?.drafter is Inkling2DSparkDrafter { // The drafter's own engine profile: up to 7 drafts, up to 8 // speculating rows, adaptive depth down to plain decode. The - // operator's acceptance setting still applies. - mtpConfig = Inkling2DSparkDrafter.defaultMTPConfig() + // operator's acceptance setting still applies, and + // DARKBLOOM_INKLING_MTP_MAX_DRAFT may lower the cap. + let maxDraft = Inkling2MTPProfilePolicy.maxDraftTokens(environment: environment) + if let unrecognized = maxDraft.unrecognized { + logWarning( + "engine_v2: unrecognized \(Inkling2MTPProfilePolicy.maxDraftKey) value " + + "\"\(unrecognized)\" for \(modelId) — using \(maxDraft.tokens)") + } else if maxDraft.tokens != Inkling2MTPProfilePolicy.defaultMaxDraftTokens { + logInfo("engine_v2: \(modelId) MTP max draft tokens \(maxDraft.tokens)") + } + mtpConfig = Inkling2MTPProfilePolicy.engineConfig(maxDraft: maxDraft) mtpConfig.acceptance = mtpAcceptance.acceptance } // Per-build SDK switches this release turns on where they were measured; diff --git a/provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift b/provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift new file mode 100644 index 0000000000..efbbbf4e50 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift @@ -0,0 +1,42 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLLM +import MLXLMCommon + +/// Operator overrides of Inkling 2's DSpark engine profile +/// (`Inkling2DSparkDrafter.defaultMTPConfig`). Tokens are unaffected: every +/// draft is verified exactly, so a cap changes only how much one round tries. +public enum Inkling2MTPProfilePolicy { + /// `DARKBLOOM_INKLING_MTP_MAX_DRAFT`: the most drafts one round may + /// propose. The adaptive depth policy still picks each round's depth at + /// or below it, down to plain decode. + public static let maxDraftKey = "DARKBLOOM_INKLING_MTP_MAX_DRAFT" + /// The drafter's whole block: the shipped cap. + public static let defaultMaxDraftTokens = 7 + + public struct MaxDraft: Equatable, Sendable { + public let tokens: Int + /// The raw value when it was not a whole number (the default applies). + public let unrecognized: String? + } + + /// Unset or blank: 7. A whole number is clamped to 1...7. Anything else + /// keeps 7 and is reported. + public static func maxDraftTokens( + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> MaxDraft { + guard let raw = environment[maxDraftKey]?.trimmingCharacters(in: .whitespacesAndNewlines), + !raw.isEmpty + else { return MaxDraft(tokens: defaultMaxDraftTokens, unrecognized: nil) } + guard let value = Int(raw) else { + return MaxDraft(tokens: defaultMaxDraftTokens, unrecognized: raw) + } + return MaxDraft(tokens: min(max(value, 1), defaultMaxDraftTokens), unrecognized: nil) + } + + /// Inkling's engine profile with the operator's cap. + public static func engineConfig(maxDraft: MaxDraft) -> CBv2MTPConfig { + Inkling2DSparkDrafter.defaultMTPConfig(maxDraftTokens: maxDraft.tokens) + } +} diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift index 7d1b52a563..b1ba489911 100644 --- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift @@ -508,6 +508,8 @@ public enum LaunchAgent: Sendable { /// `DARKBLOOM_INKLING_UNDECLARED_CALL_TEXT`: an Inkling 2 call frame in the /// answer to an `auto` request that declares no tools is text by default; /// exact `0` restores its refusal. + /// `DARKBLOOM_INKLING_MTP_MAX_DRAFT`: Inkling 2's most drafts per MTP round + /// (1 to 7, default 7); tokens are unaffected. /// `DARKBLOOM_GRAMMAR_ONLY_TOOL_PARSING` (SDK-read, `GrammarOnlyToolParsing`): /// the GLM, Gemma and MiMo parsers return calls that break only their /// schema; `0`, `off`, `false` or `no` restores their refusals. @@ -629,6 +631,7 @@ public enum LaunchAgent: Sendable { // with `stop` strings speculate on the builds that opt in; `0`, `false`, `no` // or `off` keeps them target-only. MTPStopStringRows.environmentKey, + Inkling2MTPProfilePolicy.maxDraftKey, // SDK-read (`EngineLoopV2.nativeSegmentReleaseEnvironmentKey`): idle seconds // before an issued GLM pool returns its free segments; `0` is the rollback. "DARKBLOOM_NATIVE_SEGMENT_RELEASE", diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPMaxDraftTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPMaxDraftTests.swift new file mode 100644 index 0000000000..dabe84c7c2 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPMaxDraftTests.swift @@ -0,0 +1,58 @@ +import MLXLLM +import MLXLMCommon +import Testing +@testable import ProviderCore + +/// `DARKBLOOM_INKLING_MTP_MAX_DRAFT` caps Inkling 2's drafts per MTP round +/// (`Inkling2MTPProfilePolicy`): unset keeps the drafter's whole block (7), a +/// whole number is clamped to 1...7, anything else keeps 7 and is reported. +@Suite("Inkling 2 MTP max draft override") +struct Inkling2MTPMaxDraftTests { + private let key = Inkling2MTPProfilePolicy.maxDraftKey + + @Test func unsetOrBlankKeepsTheShippedProfile() { + #expect(key == "DARKBLOOM_INKLING_MTP_MAX_DRAFT") + for environment in [[:], [key: ""], [key: " "]] { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: environment) + #expect(cap == .init(tokens: 7, unrecognized: nil)) + let config = Inkling2MTPProfilePolicy.engineConfig(maxDraft: cap) + let shipped = Inkling2DSparkDrafter.defaultMTPConfig() + #expect(config.maxDraftTokens == shipped.maxDraftTokens) + #expect(config.maxAutomaticRectangularTokens == shipped.maxAutomaticRectangularTokens) + #expect(config.fixedDraftTokens == nil) + #expect(config.costCurveDepthSelection) + } + } + + @Test(arguments: [("4", 4), ("3", 3), ("2", 2), (" 5 ", 5), ("7", 7), ("1", 1)]) + func aWholeNumberSetsTheCap(raw: String, tokens: Int) { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: [key: raw]) + #expect(cap == .init(tokens: tokens, unrecognized: nil)) + let config = Inkling2MTPProfilePolicy.engineConfig(maxDraft: cap) + #expect(config.enabled) + #expect(config.maxDraftTokens == tokens) + // Still adaptive below the cap, with the verify envelope of that depth. + #expect(config.fixedDraftTokens == nil) + #expect(config.maxAutomaticRectangularTokens == 8 * (tokens + 1)) + #expect(config.maxSpeculativeBatch == 8) + } + + @Test(arguments: [("0", 1), ("-3", 1), ("8", 7), ("64", 7)]) + func outOfRangeValuesAreClamped(raw: String, tokens: Int) { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: [key: raw]) + #expect(cap == .init(tokens: tokens, unrecognized: nil)) + #expect(Inkling2MTPProfilePolicy.engineConfig(maxDraft: cap).maxDraftTokens == tokens) + } + + @Test(arguments: ["four", "4.5", "3x", "on"]) + func otherValuesKeepSevenAndAreReported(raw: String) { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: [key: raw]) + #expect(cap == .init(tokens: 7, unrecognized: raw)) + } + + @Test func theOverrideReachesABackgroundProvider() { + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "3"])[key] == "3") + #expect(LaunchAgent.passthroughEnvironment(from: [:])[key] == nil) + } +}