From 6dc0fffe88cb66c5be93dafff7c864cf068907ac Mon Sep 17 00:00:00 2001 From: anupsv <6407789+anupsv@users.noreply.github.com> Date: Mon, 15 Jun 2026 21:36:07 -0700 Subject: [PATCH 1/3] Add post-load measured-headroom guard (close the estimate-vs-measured gap) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the follow-up deferred from the cap-rework review: the model-LOAD gate admits on an ESTIMATE (estimatedMemoryGb = on-disk weight bytes × 1.2), while the runtime KV budget uses MEASURED live MLX usage. If the estimate under-counts real residency, a model could load yet have its requests rejected by the KV gate — a "loaded but unserveable" model the coordinator keeps routing to. After a model is resident, both load paths now measure the true live KV headroom under the 90% cap and reject if it's below the minimum serveable KV: - BatchScheduler gains `measuredLiveKVHeadroomBytes` (liveKVHeadroomBytes from real MLX active+cache, with NO 1024-token floor so it reports a true zero) and `hasServeableKVHeadroom()` (>= UnifiedMemoryCap.minimumLoadKVBytes, 1 GiB). - ProviderLoop.ensureModelLoaded and StandaloneServer's lazy-load, right after loadModel returns and BEFORE registering the slot, unload + MLX.Memory .clearCache() + throw a clear "insufficient KV headroom … — unloaded" error (ProviderLoop records it for `doctor`; both mirror evictUntilAvailable so the coordinator reroutes). The check runs inside the `isLoadingAny` critical section, so the MLX measurement reflects this load with no concurrent race. This makes the cap invariant hold on MEASURED residency end-to-end, not just the estimate. Test: postLoadGuardRejectsWhenMeasuredHeadroomBelowMinimum pins the guard's boundary (an over-estimate-residency model → headroom < min → reject; a model with real room → admit). 59 tests green across UnifiedMemoryCap + BatchSchedulerBudget + StandaloneServer suites. --- .../Inference/BatchScheduler+Telemetry.swift | 24 +++++++++++++++++ .../Sources/ProviderCore/ProviderLoop.swift | 23 ++++++++++++++++ .../Server/StandaloneServer.swift | 18 +++++++++++++ .../UnifiedMemoryCapTests.swift | 26 +++++++++++++++++++ 4 files changed, 91 insertions(+) diff --git a/provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift b/provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift index 8c4f17faaf..bd7c2882d0 100644 --- a/provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift +++ b/provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift @@ -53,6 +53,30 @@ extension BatchScheduler { return max(1024, min(staticBudget, liveBudget)) } + /// MEASURED live KV headroom in bytes right now — `liveKVHeadroomBytes` + /// computed from actual MLX usage (`active + cache`, reflecting this model's + /// just-loaded weights plus any co-resident model). Unlike ``tokenBudgetMax`` + /// this applies NO 1024-token floor, so it reports a true zero when the cap is + /// already exhausted. Used by the post-load guard to reject a model that + /// loaded but has no room to serve (the load gate admits on an ESTIMATE, so a + /// model whose real residency exceeds the estimate can land here with no KV). + var measuredLiveKVHeadroomBytes: UInt64 { + let mlxUsed = UInt64(max(0, MLX.GPU.activeMemory)) + UInt64(max(0, MLX.GPU.cacheMemory)) + return UnifiedMemoryCap.liveKVHeadroomBytes( + mlxUsedBytes: mlxUsed, + systemAvailableBytes: SystemMemory.availableBytes() ?? .max) + } + + /// Post-load guard: true iff this freshly-loaded model has at least the + /// minimum serveable KV headroom under the cap. When false, the caller must + /// unload + clearCache + reject — keeping the model resident would just + /// reject every request at the KV-reservation gate (a "loaded but + /// unserveable" model). Catches the case where measured residency exceeds the + /// load gate's `estimatedMemoryGb` estimate. + func hasServeableKVHeadroom() -> Bool { + measuredLiveKVHeadroomBytes >= UnifiedMemoryCap.minimumLoadKVBytes + } + /// Sum of `(promptTokens + maxTokens)` across active bridges. This /// is the value the P1 cumulative-budget gate in `submit()` checks /// against `tokenBudgetMax`. diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 99f0842285..14b639d624 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -2694,6 +2694,29 @@ public actor ProviderLoop { throw CancellationError() } + // Post-load measured-headroom guard: the load gate admitted on an + // ESTIMATE (estimatedMemoryGb = on-disk × 1.2). Now that the weights + // are actually resident, check the MEASURED live KV headroom under the + // cap — if the real footprint exceeded the estimate there may be no + // room to serve, and keeping the model would just reject every request + // at the KV gate. Unload + reclaim + reject so the coordinator + // reroutes, instead of advertising a dead model. Safe to measure here: + // we're inside the `isLoadingAny` critical section, so MLX usage + // reflects this load and no concurrent load/unload can race it. + if !(await scheduler.hasServeableKVHeadroom()) { + let headroomGb = String( + format: "%.1f", + Double(await scheduler.measuredLiveKVHeadroomBytes) / (1024.0 * 1024.0 * 1024.0)) + let minGb = String( + format: "%.1f", Double(UnifiedMemoryCap.minimumLoadKVBytes) / (1024.0 * 1024.0 * 1024.0)) + await scheduler.unloadModel() + MLX.Memory.clearCache() + let message = "Model '\(modelId)' loaded but has insufficient KV headroom " + + "under the memory cap (\(headroomGb) GB free, need \(minGb) GB to serve) — unloaded" + recordModelLoadError(model: modelId, message: message) + throw InferenceError.modelLoadFailed(message) + } + let tokenizer: TokenizerHandle = await container.perform { ctx in TokenizerHandle(ctx.tokenizer) } diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift index 898fe38df5..cac4d92126 100644 --- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift +++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift @@ -552,6 +552,24 @@ public actor StandaloneServer { MLX.Memory.clearCache() throw CancellationError() } + // Post-load measured-headroom guard (mirrors ProviderLoop): the load + // gate admitted on an estimate; now that weights are resident, reject + // a model with no serveable KV headroom under the cap rather than keep + // a "loaded but every request rejected" model. Serialized by + // isLoadingAny, so the MLX measurement reflects this load. + if let cached = schedulers[modelId], !(await cached.scheduler.hasServeableKVHeadroom()) { + let headroomGb = String( + format: "%.1f", + Double(await cached.scheduler.measuredLiveKVHeadroomBytes) / (1024.0 * 1024.0 * 1024.0)) + let minGb = String( + format: "%.1f", Double(UnifiedMemoryCap.minimumLoadKVBytes) / (1024.0 * 1024.0 * 1024.0)) + schedulers.removeValue(forKey: modelId) + await cached.scheduler.unloadModel() + MLX.Memory.clearCache() + throw StandaloneServerError.capacityUnavailable( + "Model '\(modelId)' loaded but has insufficient KV headroom under the memory cap " + + "(\(headroomGb) GB free, need \(minGb) GB to serve) — unloaded") + } standaloneLogger.info("Lazy-loaded model: \(modelId)") modelsLoading.remove(modelId) diff --git a/provider-swift/Tests/ProviderCoreTests/UnifiedMemoryCapTests.swift b/provider-swift/Tests/ProviderCoreTests/UnifiedMemoryCapTests.swift index f2b790f86c..c8157eb2c9 100644 --- a/provider-swift/Tests/ProviderCoreTests/UnifiedMemoryCapTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/UnifiedMemoryCapTests.swift @@ -283,6 +283,32 @@ private let gib: UInt64 = 1024 * 1024 * 1024 "a model that passes the load gate must have at least minimum serveable KV") } +// MARK: - Post-load guard decision (measured headroom vs minimum serveable KV) + +@Test func postLoadGuardRejectsWhenMeasuredHeadroomBelowMinimum() { + // The post-load guard (BatchScheduler.hasServeableKVHeadroom) is exactly + // `measuredLiveKVHeadroomBytes >= minimumLoadKVBytes`, where the measured + // headroom is liveKVHeadroomBytes(real MLX usage). Pin that boundary here + // (the BatchScheduler accessor reads real MLX globals, not injectable). + let phys = 64 * gib // cap 57.6 + let activation = 3 * gib + // Estimate said the model fit, but MEASURED residency turned out larger: + // 55.5 GiB actually resident → headroom = 57.6 − 55.5 − 3 = clamped to 0. + let measuredOverHeadroom = UnifiedMemoryCap.liveKVHeadroomBytes( + physicalBytes: phys, mlxUsedBytes: UInt64(55.5 * Double(gib)), + systemAvailableBytes: .max, activationReserveBytes: activation) + #expect(measuredOverHeadroom < UnifiedMemoryCap.minimumLoadKVBytes, + "an over-estimate-residency model must be rejected by the post-load guard") + + // A model whose real residency leaves room keeps serveable KV → admitted. + // 50 GiB resident → headroom = 57.6 − 50 − 3 = 4.6 GiB ≥ 1 GiB min. + let measuredOkHeadroom = UnifiedMemoryCap.liveKVHeadroomBytes( + physicalBytes: phys, mlxUsedBytes: 50 * gib, + systemAvailableBytes: .max, activationReserveBytes: activation) + #expect(measuredOkHeadroom >= UnifiedMemoryCap.minimumLoadKVBytes, + "a model with real serveable KV must pass the post-load guard") +} + @Test func kvBudgetAndAdmitSaturateOnMaxOperands() { // .max weights must clamp the KV budget to 0, not underflow/trap. #expect(UnifiedMemoryCap.kvBudgetBytes( From 55296b1f86f6101b0e25e8af4acd16c967b61375 Mon Sep 17 00:00:00 2001 From: anupsv <6407789+anupsv@users.noreply.github.com> Date: Mon, 15 Jun 2026 21:40:36 -0700 Subject: [PATCH 2/3] fix(provider): bound Gemma batching memory envelope --- coordinator/api/billing_integration_test.go | 2 +- coordinator/api/consumer.go | 43 ++++++------ coordinator/api/consumer_test.go | 25 +++++++ coordinator/registry/scheduler.go | 56 +++++++++++++-- coordinator/registry/scheduler_test.go | 24 +++++++ .../Inference/BatchScheduler.swift | 70 +++++++++++++++---- .../MultiModelBatchSchedulerEngine.swift | 3 + .../Sources/ProviderCore/ProviderLoop.swift | 8 ++- .../Server/StandaloneServer.swift | 6 +- .../BatchSchedulerBudgetTests.swift | 41 +++++++++++ 10 files changed, 231 insertions(+), 47 deletions(-) diff --git a/coordinator/api/billing_integration_test.go b/coordinator/api/billing_integration_test.go index 2cfb071741..364f7df8fa 100644 --- a/coordinator/api/billing_integration_test.go +++ b/coordinator/api/billing_integration_test.go @@ -435,7 +435,7 @@ func TestIntegration_ReservationRefundedOnCompletion(t *testing.T) { defer conn.Close(websocket.StatusNormalClosure, "") // Short generation — completion_tokens (10) is far below the reservation - // based on default max_tokens=8192. + // based on the implicit default max_tokens bound. usage := protocol.UsageInfo{PromptTokens: 5, CompletionTokens: 10} providerDone := serveOneInference(ctx, t, conn, pubKey, usage) diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go index 0eb78587d4..c247b3b547 100644 --- a/coordinator/api/consumer.go +++ b/coordinator/api/consumer.go @@ -999,14 +999,21 @@ func bodyForProvider(rawBody []byte, requiresVision bool, provider *registry.Pro return rawBody } -// defaultMaxOutputTokens is the ceiling injected into requests that don't set -// max_tokens. It bounds the worst-case cost of a single inference so the +// defaultMaxOutputTokens is the generation bound injected into requests that +// don't set max_tokens. It bounds the worst-case cost of a single inference so the // pre-flight balance reservation covers the entire generation; without this // cap a consumer could stream output exceeding their reservation and the // post-inference charge would fail silently (see GitHub issue #33). Consumers // who need longer generations must set max_tokens explicitly and carry the // balance to cover it. -const defaultMaxOutputTokens = 8192 +const defaultMaxOutputTokens = 1024 + +func implicitMaxTokensBound(modelMaxOutputLength int) int { + if modelMaxOutputLength > 0 && modelMaxOutputLength < defaultMaxOutputTokens { + return modelMaxOutputLength + } + return defaultMaxOutputTokens +} // explicitMaxTokens returns the consumer-specified max output tokens from any // of the recognized field names, or 0 if none were set. @@ -1176,11 +1183,10 @@ func (s *Server) reserveAdditionalForProvider(pr *registry.PendingRequest, provi // ensureMaxTokensBound injects a max-tokens bound into parsed when the // consumer didn't specify any max-tokens field, so the outgoing request to // the provider is bounded by the amount we reserve upfront. The bound is -// the model's max_output_length from the registry (or defaultMaxOutputTokens -// as fallback). The injected field name depends on the API flavor: Responses -// API uses max_output_tokens, everything else uses max_tokens. Returns true -// when an injection occurred, so the caller can re-marshal the outgoing body -// if needed. +// the platform default clamped by the model's max_output_length when lower. +// The injected field name depends on the API flavor: Responses API uses +// max_output_tokens, everything else uses max_tokens. Returns true when an +// injection occurred, so the caller can re-marshal the outgoing body if needed. func ensureMaxTokensBound(parsed map[string]any, isResponsesAPI bool, bound int) bool { if n := explicitMaxTokens(parsed); n > 0 { // Normalize alias fields the provider engine doesn't read: a chat @@ -1532,7 +1538,7 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { // Inject model-specific defaults from the registry: reasoning_parser // and max_tokens bound. Single DB lookup (cached for platform prices). - maxOutputBound := defaultMaxOutputTokens + maxOutputBound := implicitMaxTokensBound(0) if rec, err := s.store.GetModelRegistryRecord(model); err == nil { // Reasoning parser from runtime_parameters. if _, hasRP := parsed["reasoning_parser"]; !hasRP && rec.RuntimeParameters != nil { @@ -1541,18 +1547,15 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { rawBody, _ = marshalForwardBody(parsed) } } - // Use the registry's max_output_length as the default max_tokens - // bound instead of the hardcoded 8192. This lets models like - // GPT-OSS 20B (32K output) generate longer responses when the - // consumer omits max_tokens. - if rec.MaxOutputLength > 0 { - maxOutputBound = rec.MaxOutputLength - } + // max_output_length is an advertised maximum, not the implicit default. + // Omitted max_tokens stays on the safer platform default; models with a + // lower published max still clamp the injected bound to their maximum. + maxOutputBound = implicitMaxTokensBound(rec.MaxOutputLength) } // Bound the generation so the pre-flight reservation covers it. If the - // consumer didn't set max_tokens, inject the model's max_output_length - // (or defaultMaxOutputTokens as fallback). Without this bound the + // consumer didn't set max_tokens, inject the platform default clamped by + // the model's max_output_length when lower. Without this bound the // provider could return more tokens than we reserved for, and the // silent post-inference charge failure would hand the consumer free // inference (GitHub issue #33). @@ -4100,9 +4103,9 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request, // Completions and Anthropic messages both use the max_tokens field (never // max_output_tokens, which is Responses API only). Inject a default if // unset so the pre-flight reservation bounds the generation. - genericMaxOutput := defaultMaxOutputTokens + genericMaxOutput := implicitMaxTokensBound(0) if rec, err := s.store.GetModelRegistryRecord(model); err == nil && rec.MaxOutputLength > 0 { - genericMaxOutput = rec.MaxOutputLength + genericMaxOutput = implicitMaxTokensBound(rec.MaxOutputLength) } ensureMaxTokensBound(parsed, false, genericMaxOutput) diff --git a/coordinator/api/consumer_test.go b/coordinator/api/consumer_test.go index fe789d9844..c0f8d95aad 100644 --- a/coordinator/api/consumer_test.go +++ b/coordinator/api/consumer_test.go @@ -1032,6 +1032,31 @@ func TestResponsesRequestToChatCompletions(t *testing.T) { } } +func TestImplicitMaxTokensBoundUsesSafeDefaultBelowModelMaximum(t *testing.T) { + if got := implicitMaxTokensBound(8192); got != defaultMaxOutputTokens { + t.Fatalf("implicitMaxTokensBound(8192) = %d, want %d", got, defaultMaxOutputTokens) + } +} + +func TestImplicitMaxTokensBoundClampsToLowerModelMaximum(t *testing.T) { + if got := implicitMaxTokensBound(256); got != 256 { + t.Fatalf("implicitMaxTokensBound(256) = %d, want 256", got) + } +} + +func TestEnsureMaxTokensBoundInjectsImplicitDefault(t *testing.T) { + parsed := map[string]any{ + "model": "gemma-4-26b", + "messages": []any{map[string]any{"role": "user", "content": "hello"}}, + } + if !ensureMaxTokensBound(parsed, false, implicitMaxTokensBound(8192)) { + t.Fatal("ensureMaxTokensBound did not report injection") + } + if got := parsed["max_tokens"]; got != defaultMaxOutputTokens { + t.Fatalf("max_tokens = %v, want %d", got, defaultMaxOutputTokens) + } +} + func TestResponsesInputToolTranscriptToChatMessages(t *testing.T) { input := []any{ map[string]any{ diff --git a/coordinator/registry/scheduler.go b/coordinator/registry/scheduler.go index c77c139d2d..841e30d3d8 100644 --- a/coordinator/registry/scheduler.go +++ b/coordinator/registry/scheduler.go @@ -79,6 +79,7 @@ type routingSnapshot struct { prefillTPS float64 systemMetrics protocol.SystemMetrics gpuMemoryActiveGB float64 + gpuMemoryCacheGB float64 totalMemoryGB float64 modelSizeGB float64 // catalog-reported weight footprint (0 = unknown, gate disabled) minRAMGb int // catalog authoritative min RAM (GB) to run the model (0 = unknown) @@ -133,6 +134,14 @@ const ( // gemma-4-26b min_ram_gb=36 vs 28*2.x rejecting the whole 64 GB tier). const modelMemoryHeadroomFactor = 2.0 +const ( + providerMemoryCapFraction = 0.90 + providerMinimumReserveGB = 2.0 + providerModelMemoryOverheadFactor = 1.2 + providerActivationReserveGB = 3.0 + providerMinimumLoadKVGB = 1.0 +) + // modelFitsHardware reports whether a model can run on a node with the given // total unified memory (GB). It prefers the catalog's authoritative min_ram_gb // (the operator-published requirement) and only falls back to a heuristic @@ -153,6 +162,28 @@ func modelFitsHardware(minRAMGb int, modelSizeGB, totalMemoryGB float64) bool { return true } +func providerHardMemoryCapGB(totalMemoryGB float64) float64 { + if totalMemoryGB <= 0 { + return 0 + } + byFraction := totalMemoryGB * providerMemoryCapFraction + byFloor := 0.0 + if totalMemoryGB > providerMinimumReserveGB { + byFloor = totalMemoryGB - providerMinimumReserveGB + } + if byFraction < byFloor { + return byFraction + } + return byFloor +} + +func providerEstimatedModelLoadGB(modelSizeGB float64) float64 { + if modelSizeGB <= 0 { + return 0 + } + return modelSizeGB * providerModelMemoryOverheadFactor +} + // costBreakdown decomposes the routing cost so callers can log or // expose individual contributions. The numeric values match the terms // added in buildCandidate; total should equal costMs (modulo float @@ -760,6 +791,7 @@ func (r *Registry) snapshotProviderLocked(p *Provider, model string, traits Requ if p.BackendCapacity != nil { snap.gpuMemoryActiveGB = p.BackendCapacity.GPUMemoryActiveGB + snap.gpuMemoryCacheGB = p.BackendCapacity.GPUMemoryCacheGB if p.BackendCapacity.TotalMemoryGB > 0 { snap.totalMemoryGB = p.BackendCapacity.TotalMemoryGB } @@ -805,7 +837,8 @@ func freeMemoryAdmits(snap routingSnapshot, reqPromptTokens, reqMaxTokens int) b if snap.modelSizeGB <= 0 || snap.totalMemoryGB <= 0 { return true } - required := snap.modelSizeGB + modelLoadGB := providerEstimatedModelLoadGB(snap.modelSizeGB) + required := modelLoadGB if snap.modelLoaded { required = 0 } @@ -818,7 +851,6 @@ func freeMemoryAdmits(snap routingSnapshot, reqPromptTokens, reqMaxTokens int) b tokens = maxTokensForCalc } kvCacheGB := float64(tokens*kvCacheBytesPerToken) / float64(bytesPerGB) - required += kvCacheGB // When the model is available on disk but not currently loaded, the // provider will evict idle models to make room (LRU eviction). Check @@ -831,12 +863,23 @@ func freeMemoryAdmits(snap routingSnapshot, reqPromptTokens, reqMaxTokens int) b // through to the standard free-memory check which requires room // alongside active models. if snap.availableOnDisk && !snap.modelLoaded && snap.totalPending == 0 { - const osReserveGB = 4.0 - return snap.modelSizeGB+kvCacheGB+osReserveGB <= snap.totalMemoryGB + requiredKVGB := kvCacheGB + if requiredKVGB < providerMinimumLoadKVGB { + requiredKVGB = providerMinimumLoadKVGB + } + required := modelLoadGB + providerActivationReserveGB + requiredKVGB + return required <= providerHardMemoryCapGB(snap.totalMemoryGB) } - free := snap.totalMemoryGB - snap.gpuMemoryActiveGB - return free >= required + freeUnderCap := providerHardMemoryCapGB(snap.totalMemoryGB) - snap.gpuMemoryActiveGB - snap.gpuMemoryCacheGB + if freeUnderCap < 0 { + freeUnderCap = 0 + } + required += kvCacheGB + providerActivationReserveGB + if !snap.modelLoaded { + required += providerMinimumLoadKVGB + } + return freeUnderCap >= required } func pendingTokenBudget(pr *PendingRequest) int { @@ -1255,6 +1298,7 @@ func (r *Registry) quickCapacityCheck(model string, estimatedPromptTokens, reque } if snap.hasBackendCapacity { snap.gpuMemoryActiveGB = p.BackendCapacity.GPUMemoryActiveGB + snap.gpuMemoryCacheGB = p.BackendCapacity.GPUMemoryCacheGB if p.BackendCapacity.TotalMemoryGB > 0 { snap.totalMemoryGB = p.BackendCapacity.TotalMemoryGB } diff --git a/coordinator/registry/scheduler_test.go b/coordinator/registry/scheduler_test.go index a116a2b936..4a8d60a577 100644 --- a/coordinator/registry/scheduler_test.go +++ b/coordinator/registry/scheduler_test.go @@ -1423,6 +1423,30 @@ func TestFreeMemoryAdmitsFallsBackWithoutBudget(t *testing.T) { } } +func TestFreeMemoryAdmitsColdLoadMirrorsProviderMemoryEnvelope(t *testing.T) { + // 26 GB of raw weights looks like it fits on a 36 GB laptop under the old + // raw-size + 4 GB reserve check (30 <= 36). The provider actually loads with + // scanner overhead (1.2x), a 90% hard cap, activation reserve, and minimum KV + // headroom: 31.2 + 3 + 1 > 32.4, so the coordinator must not route it cold. + publicGemmaOnLaptop := routingSnapshot{ + modelSizeGB: 26, + totalMemoryGB: 36, + availableOnDisk: true, + modelLoaded: false, + totalPending: 0, + } + if freeMemoryAdmits(publicGemmaOnLaptop, 100, 256) { + t.Fatal("should reject cold load that only fits under raw-size accounting") + } + + // The QAT build's smaller raw footprint still fits the same envelope. + qatGemmaOnLaptop := publicGemmaOnLaptop + qatGemmaOnLaptop.modelSizeGB = 15 + if !freeMemoryAdmits(qatGemmaOnLaptop, 100, 256) { + t.Fatal("should admit smaller QAT build under provider-equivalent accounting") + } +} + func TestSlotHeadroomWithExhaustedTokenBudgetRejectsCapacity(t *testing.T) { reg := New(testLogger()) model := "budget-headroom-model" diff --git a/provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift b/provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift index d5b52e4078..af0f685677 100644 --- a/provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift +++ b/provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift @@ -1463,6 +1463,32 @@ public actor BatchScheduler { return n // 0 ⇒ disabled } + static func makeSamplingParams( + maxTokens: Int, + temperature: Float, + topP: Float?, + topK: Int?, + repetitionPenalty: Float?, + presencePenalty: Float?, + frequencyPenalty: Float?, + seed: UInt64? + ) -> SamplingParams { + let requestedRepetitionPenalty = repetitionPenalty ?? 1.0 + let safeRepetitionPenalty = + requestedRepetitionPenalty <= 0 ? Float(1.0) : requestedRepetitionPenalty + var sp = SamplingParams( + maxTokens: maxTokens, + temperature: temperature, + repetitionPenalty: safeRepetitionPenalty, + presencePenalty: presencePenalty ?? 0.0, + frequencyPenalty: frequencyPenalty ?? 0.0 + ) + if let topP { sp.topP = topP } + if let topK { sp.topK = topK } + if let seed { sp.seed = seed } + return sp + } + /// Set the post-load budgets driven by architecture + physical /// memory. Pulled out of `loadModel` so the lifecycle reads as a /// short sequence; the arithmetic itself is unchanged. @@ -1488,11 +1514,12 @@ public actor BatchScheduler { // Derive context-aware limits from config.json. self.maxContextLength = snapshot.architecture.maxContextLength ?? 0 if maxContextLength > 0 { - // Raise the default max output tokens so consumers that omit - // `max_tokens` get a reasonable budget for the model's class. - // Cap at 8192 so we don't over-reserve with very-long-context - // models (e.g. 131K Qwen). - self.defaultMaxTokens = min(maxContextLength, 8192) + // Do not auto-raise omitted `max_tokens` after model load. Runaway + // loops then run to an unexpectedly large cap and over-reserve KV. + // Only clamp downward for unusually short-context models. + self.defaultMaxTokens = min(initDefaultMaxTokens, maxContextLength) + } else { + self.defaultMaxTokens = initDefaultMaxTokens } self.dynamicMaxConcurrentRequests = min(4, maxConcurrentRequests) @@ -1518,6 +1545,9 @@ public actor BatchScheduler { temperature: Float = 0.0, topP: Float? = nil, topK: Int? = nil, + repetitionPenalty: Float? = nil, + presencePenalty: Float? = nil, + frequencyPenalty: Float? = nil, seed: UInt64? = nil, requestId: String? = nil, cacheScope: String = "" @@ -1575,10 +1605,16 @@ public actor BatchScheduler { await refreshPendingSummaryCache() } - var sp = SamplingParams(maxTokens: maxTokens, temperature: temperature) - if let topP { sp.topP = topP } - if let topK { sp.topK = topK } - if let seed { sp.seed = seed } + let sp = Self.makeSamplingParams( + maxTokens: maxTokens, + temperature: temperature, + topP: topP, + topK: topK, + repetitionPenalty: repetitionPenalty, + presencePenalty: presencePenalty, + frequencyPenalty: frequencyPenalty, + seed: seed + ) let req = Request( requestId: id, @@ -1752,13 +1788,17 @@ public actor BatchScheduler { await refreshPendingSummaryCache() } - // Greedy (temperature == 0) hits the engine's vectorized argmax - // fast path automatically; just pass the requested value through. let temperature = request.temperature ?? 0.0 - var sp = SamplingParams(maxTokens: maxTokens, temperature: temperature) - if let topP = request.top_p { sp.topP = topP } - if let topK = request.top_k { sp.topK = topK } - if let seed = request.seed { sp.seed = seed } + let sp = Self.makeSamplingParams( + maxTokens: maxTokens, + temperature: temperature, + topP: request.top_p, + topK: request.top_k, + repetitionPenalty: request.repetition_penalty, + presencePenalty: request.presence_penalty, + frequencyPenalty: request.frequency_penalty, + seed: request.seed + ) let req = Request( requestId: id, diff --git a/provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift index 73dfdefb34..c8ca2e5004 100644 --- a/provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift @@ -296,6 +296,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { temperature: temperature, topP: request.topP, topK: request.topK, + repetitionPenalty: request.repetitionPenalty, + presencePenalty: request.presencePenalty, + frequencyPenalty: request.frequencyPenalty, requestId: requestId, cacheScope: cacheScope ) diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 14b639d624..1246956358 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -466,9 +466,13 @@ public actor ProviderLoop { // MARK: - Model Slot - private static let schedulerMaxConcurrent = 24 + // Production fan-in must match the MLX/Gemma memory envelope. The upstream + // scheduler's `maxNumSeqs` uses this value directly, so keeping it at the old + // fleet-wide 24 lets real batches grow far beyond the 4-way budget reported + // in heartbeats. + private static let schedulerMaxConcurrent = 4 private static let schedulerPendingTimeout: Duration = .seconds(120) - private static let schedulerDefaultMaxTokens = 4096 + private static let schedulerDefaultMaxTokens = 1024 /// Infer the reasoning parser format from the model's `model_type` /// (read from config.json at scan time). Used to auto-select the diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift index cac4d92126..0b2ea7c8ec 100644 --- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift +++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift @@ -117,11 +117,12 @@ public actor StandaloneServer { MLXMemoryGuard.configureOnce() } - static let schedulerMaxConcurrent = 24 + // Keep local serving on the same memory-safe envelope as provider mode. + static let schedulerMaxConcurrent = 4 static let schedulerPendingTimeout: Duration = .seconds(120) /// Internal access so the +HTTP extension can pass the same /// default through to ``MultiModelBatchSchedulerEngine``. - static let schedulerDefaultMaxTokens = 4096 + static let schedulerDefaultMaxTokens = 1024 /// Map a scheduler-side admission error message to an HTTP status. Used /// by tests and by any custom error-mapping middleware. Retained here @@ -597,4 +598,3 @@ public actor StandaloneServer { } } } - diff --git a/provider-swift/Tests/ProviderCoreTests/BatchSchedulerBudgetTests.swift b/provider-swift/Tests/ProviderCoreTests/BatchSchedulerBudgetTests.swift index 0e8180bcc0..179feae643 100644 --- a/provider-swift/Tests/ProviderCoreTests/BatchSchedulerBudgetTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/BatchSchedulerBudgetTests.swift @@ -44,6 +44,47 @@ struct BatchSchedulerBudgetTests { // MARK: - P1: cumulative active-bridge gate + @Test("sampling params preserve OpenAI repetition penalties") + func samplingParamsPreservePenalties() { + let params = BatchScheduler.makeSamplingParams( + maxTokens: 128, + temperature: 0.2, + topP: 0.9, + topK: 40, + repetitionPenalty: 1.15, + presencePenalty: 0.3, + frequencyPenalty: 0.4, + seed: 42 + ) + + #expect(params.maxTokens == 128) + #expect(params.temperature == 0.2) + #expect(params.topP == 0.9) + #expect(params.topK == 40) + #expect(params.repetitionPenalty == 1.15) + #expect(params.presencePenalty == 0.3) + #expect(params.frequencyPenalty == 0.4) + #expect(params.seed == 42) + } + + @Test("sampling params coerce non-positive repetition penalty to disabled") + func samplingParamsCoerceInvalidRepetitionPenalty() { + let params = BatchScheduler.makeSamplingParams( + maxTokens: 128, + temperature: 0.0, + topP: nil, + topK: nil, + repetitionPenalty: 0, + presencePenalty: nil, + frequencyPenalty: nil, + seed: nil + ) + + #expect(params.repetitionPenalty == 1.0) + #expect(params.presencePenalty == 0.0) + #expect(params.frequencyPenalty == 0.0) + } + /// Pre-fix: planner validated per-request limits + queue size only, /// so a burst of large requests each individually within budget /// could overcommit KV memory once they all reached the engine. From 279897b402c740da60d3f1e0fa9e941231f73787 Mon Sep 17 00:00:00 2001 From: anupsv <6407789+anupsv@users.noreply.github.com> Date: Mon, 15 Jun 2026 21:47:56 -0700 Subject: [PATCH 3/3] fix(provider): avoid Gemma batch decode mask divergence --- coordinator/api/server.go | 2 +- libs/mlx-swift-lm | 2 +- provider-swift/Sources/ProviderCore/ProviderCore.swift | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/coordinator/api/server.go b/coordinator/api/server.go index e9da06158f..27c5fd1a76 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -143,7 +143,7 @@ func keyLimitResetFromContext(ctx context.Context) string { // 0.6.0 is the APNs code-identity / VLM-routing / graceful-update release. // Keep this fallback in sync with ProviderCore.version so dev/in-memory // coordinators advertise the same floor as the Swift binary they expect. -var LatestProviderVersion = "0.6.10" +var LatestProviderVersion = "0.6.11" // minProviderVersionForDesiredModels is the first provider version whose Swift // runtime understands the desired_models message. The coordinator must NOT send diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 404afee142..9f771d1973 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 404afee1425bef8f2650d4b3f9ac79035d486f24 +Subproject commit 9f771d197327ccfa9177edaeb545070e00f6a843 diff --git a/provider-swift/Sources/ProviderCore/ProviderCore.swift b/provider-swift/Sources/ProviderCore/ProviderCore.swift index 277b0cc389..c7b2fce468 100644 --- a/provider-swift/Sources/ProviderCore/ProviderCore.swift +++ b/provider-swift/Sources/ProviderCore/ProviderCore.swift @@ -34,5 +34,8 @@ public enum ProviderCore { // 0.6.10 ships the resource-count-safe MLX allocator pins, bounded model // weight hashing, attestation reconnect stability, alias-aware catalog UX, // and coordinator-side TTFT 429 admission for overloaded OpenRouter traffic. - public static let version = "0.6.10" + // 0.6.11 keeps unpadded single-token continuous-batch decode on the same + // unmasked attention path as regular KVCache, avoiding 4-bit Gemma 4 + // repetition from explicit all-true batch masks. + public static let version = "0.6.11" }