From e54fbf72bd176068cab180db0b20eb410cc5b1da Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Wed, 3 Jun 2026 16:28:23 -0700 Subject: [PATCH 1/3] fix(provider): load models for one-request fit, not full-concurrency headroom MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is the foundational fix for ~half the fleet sitting idle. A small/mid machine could not LOAD a model it was perfectly capable of serving, because the load gate was doubly conservative: requiredGb = estimatedMemoryGb * 2.0 (full-concurrency KV headroom) availableMemoryGb = free * 0.7 (runtime KV safety, double-counted) => effectively demanded free >= weights * 2.86 Measured effect: gpt-oss-20b "needed" 40.5 GB and gemma-4-26b 93.7 GB to load — ~3.35x the weights — so every 24/32/36/48 GB box (and most 64 GB boxes) served ZERO requests despite advertising the models. The runtime is ALREADY safe and dynamic: GlobalKVCacheBudget.reserve() strictly rejects any request whose KV won't fit real free memory, and the live token budget scales concurrency with a floor of one request. So the 2x/0.7 belonged nowhere near the LOAD decision. Fix (ModelLoadAdmission, pure + unit-tested): - Load gate now requires only WEIGHTS + one-request headroom (estimatedMemoryGb + loadHeadroomGb, default 2 GB). - availableMemoryGb drops the 0.7 discount — loading weights is a known one-time allocation; the 0.7 runtime safety stays where it belongs (per-request KV). - Concurrency beyond one request is grown dynamically by the existing budget, so a 24 GB box serves 1-2 and a 128 GB box serves many. Cannot OOM: a load that fits one request is admitted; everything past that is gated per request. Impact (measured against the live fleet): gpt-oss-20b now loads on 24/32/36/48 GB boxes; gemma-4-26b now loads on the 48/64 GB tiers (18x 64 GB machines that served nothing before). gemma-8bit correctly still rejected on 32 GB (weights + OS ≈ whole box). Tests: ModelLoadAdmissionTests (gpt-oss-on-24GB admit, gemma-on-64GB admit, gemma-on-32GB reject, resident-model no-room, free-memory math, regression guard proving the old gate rejected gpt-oss-on-24GB). swift build + swift test green. --- .../Inference/ModelLoadAdmission.swift | 73 +++++++++++++++++++ .../Sources/ProviderCore/ProviderLoop.swift | 45 ++++++++---- .../ModelLoadAdmissionTests.swift | 68 +++++++++++++++++ 3 files changed, 170 insertions(+), 16 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift diff --git a/provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift b/provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift new file mode 100644 index 0000000000..7fad391cc4 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift @@ -0,0 +1,73 @@ +import Foundation + +/// Pure memory arithmetic for deciding whether a model can be LOADED on this +/// machine. Kept separate from the runtime per-request KV admission +/// (`GlobalKVCacheBudget`) and unit-testable on any platform. +/// +/// The foundational fix: loading a model is a one-time, known allocation (the +/// weights). The previous gate demanded `weights × 2.0` of headroom AND then +/// only counted `free × 0.7` as usable — together requiring `free ≥ weights × +/// 2.86`. That baked full-concurrency KV headroom into the LOAD decision and +/// left every small/mid machine unable to load a model it could actually serve. +/// +/// Correct model: load whenever the weights plus enough headroom for ONE +/// request physically fit alongside the OS reserve. Concurrency BEYOND one +/// request is then sized dynamically at runtime by the live token budget + +/// `GlobalKVCacheBudget`, which strictly rejects any request whose KV won't fit +/// real free memory (so this looser load gate cannot cause an OOM — the worst +/// case is a loaded model that serves a single request at a time). +public enum ModelLoadAdmission { + /// Default headroom (GB) reserved above the weights for one request's KV + /// cache + activations at load time. Small on purpose: it only needs to + /// cover a single in-flight request; the runtime budget grows concurrency + /// from whatever is left. Tunable via provider config. + public static let defaultLoadHeadroomGb: Double = 2.0 + + /// Physical memory (GB) available to load a model: total minus the OS + /// reserve and whatever MLX already has resident (active + cache). NOTE: + /// deliberately NO 0.7 safety discount — weights are a known allocation, and + /// the 0.7 runtime safety is already applied per-request by + /// GlobalKVCacheBudget. Discounting here too is the double-count that kept + /// capable machines idle. + public static func freeForLoadGb( + totalBytes: UInt64, + gpuActiveBytes: UInt64, + gpuCacheBytes: UInt64, + reserveBytes: UInt64 + ) -> Double { + let used = saturatingAdd(gpuActiveBytes, gpuCacheBytes, reserveBytes) + let usable = totalBytes > used ? totalBytes - used : 0 + return Double(usable) / bytesPerGb + } + + /// Memory (GB) required to load a model and serve at least one request: + /// the (overhead-padded) weight footprint plus one-request headroom. + public static func requiredToLoadGb(weightsGb: Double, headroomGb: Double = defaultLoadHeadroomGb) -> Double { + max(0, weightsGb) + max(0, headroomGb) + } + + /// Whether a model with the given weight footprint can be loaded now. + public static func canLoad( + weightsGb: Double, + headroomGb: Double, + totalBytes: UInt64, + gpuActiveBytes: UInt64, + gpuCacheBytes: UInt64, + reserveBytes: UInt64 + ) -> Bool { + let free = freeForLoadGb(totalBytes: totalBytes, gpuActiveBytes: gpuActiveBytes, gpuCacheBytes: gpuCacheBytes, reserveBytes: reserveBytes) + return requiredToLoadGb(weightsGb: weightsGb, headroomGb: headroomGb) <= free + } + + private static let bytesPerGb = 1024.0 * 1024.0 * 1024.0 + + private static func saturatingAdd(_ values: UInt64...) -> UInt64 { + var total: UInt64 = 0 + for v in values { + let (sum, overflow) = total.addingReportingOverflow(v) + if overflow { return UInt64.max } + total = sum + } + return total + } +} diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index bf5b260889..d4aa5cff89 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -1436,14 +1436,18 @@ public actor ProviderLoop { try Task.checkCancellation() if isShuttingDown { throw CancellationError() } - // Budget enough headroom to warm the model. Per-request KV safety is - // enforced later by BatchScheduler's live token budget, so this load - // gate should not assume the engine's full adaptive slot ceiling is - // simultaneously filled with maximum-context requests. A 2x (rather - // than 3x) multiple keeps a safety margin for KV-cache growth while - // still letting models load on boxes where other models are actively - // serving — the previous 3x rejected loads that would have fit. - let requiredGb = modelInfo.estimatedMemoryGb * 2.0 + // Load gate: require room for the WEIGHTS plus headroom for ONE + // request, not a full-concurrency multiple. Concurrency beyond one + // request is sized dynamically at runtime by the live token budget + + // GlobalKVCacheBudget (which strictly rejects any request whose KV + // won't fit real free memory, so this looser gate cannot OOM — worst + // case a box serves one request at a time). The old `× 2.0` here, + // combined with the `× 0.7` discount in availableMemoryGb, demanded + // free ≥ weights × 2.86 and left every small/mid machine unable to + // load a model it could actually serve. + let requiredGb = ModelLoadAdmission.requiredToLoadGb( + weightsGb: modelInfo.estimatedMemoryGb, + headroomGb: Self.loadHeadroomGb) try await evictUntilAvailable(requiredGb: requiredGb) try Task.checkCancellation() if isShuttingDown { throw CancellationError() } @@ -1544,16 +1548,23 @@ public actor ProviderLoop { } } + /// Physical memory (GB) available to LOAD a model. No 0.7 KV-safety discount + /// here — weights are a known one-time allocation, and the 0.7 runtime + /// safety is already enforced per request by GlobalKVCacheBudget. Applying it + /// twice was the double-count that kept capable machines from ever loading a + /// model they could serve. private func availableMemoryGb() -> Double { - let total = ProcessInfo.processInfo.physicalMemory - let active = UInt64(MLX.GPU.activeMemory) - let cache = UInt64(MLX.GPU.cacheMemory) - let reserve = Self.memoryReserveBytes(forGiB: loopConfig.config.provider.memoryReserveGB) - let used = Self.saturatingAdd(active, cache, reserve) - let usable = total > used ? total - used : 0 - return Double(usable) * 0.7 / (1024.0 * 1024.0 * 1024.0) + ModelLoadAdmission.freeForLoadGb( + totalBytes: ProcessInfo.processInfo.physicalMemory, + gpuActiveBytes: UInt64(max(0, MLX.GPU.activeMemory)), + gpuCacheBytes: UInt64(max(0, MLX.GPU.cacheMemory)), + reserveBytes: Self.memoryReserveBytes(forGiB: loopConfig.config.provider.memoryReserveGB)) } + /// Headroom (GB) reserved above the weights at load time for ONE request. + /// Concurrency beyond that is grown dynamically by the runtime token budget. + static let loadHeadroomGb = ModelLoadAdmission.defaultLoadHeadroomGb + private static func saturatingAdd(_ values: UInt64...) -> UInt64 { var total: UInt64 = 0 for value in values { @@ -1608,7 +1619,9 @@ public actor ProviderLoop { guard let modelInfo = loopConfig.models.first(where: { $0.id == modelId }) else { return false } - let requiredGb = modelInfo.estimatedMemoryGb * 2.0 + let requiredGb = ModelLoadAdmission.requiredToLoadGb( + weightsGb: modelInfo.estimatedMemoryGb, + headroomGb: Self.loadHeadroomGb) // An idle slot (loaded, no in-flight work, not already unloading) can be // evicted to make room, so its presence means we must NOT pre-reject. diff --git a/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift b/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift new file mode 100644 index 0000000000..43665bfe47 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift @@ -0,0 +1,68 @@ +import Foundation +import Testing +@testable import ProviderCore + +private let gib: UInt64 = 1024 * 1024 * 1024 + +@Test func freeForLoadHasNoSafetyDiscount() { + // 32 GB box, 4 GB reserve, nothing loaded → 28 GB free (NOT 28*0.7). + let free = ModelLoadAdmission.freeForLoadGb( + totalBytes: 32 * gib, gpuActiveBytes: 0, gpuCacheBytes: 0, reserveBytes: 4 * gib) + #expect(abs(free - 28.0) < 0.001) +} + +@Test func freeForLoadSubtractsResidentAndReserve() { + // 64 GB, 30 GB already resident (active), 2 GB cache, 4 GB reserve → 28 GB. + let free = ModelLoadAdmission.freeForLoadGb( + totalBytes: 64 * gib, gpuActiveBytes: 30 * gib, gpuCacheBytes: 2 * gib, reserveBytes: 4 * gib) + #expect(abs(free - 28.0) < 0.001) +} + +@Test func requiredToLoadIsWeightsPlusHeadroom() { + #expect(abs(ModelLoadAdmission.requiredToLoadGb(weightsGb: 13.5, headroomGb: 2.0) - 15.5) < 0.001) + // Negative inputs are floored at 0. + #expect(ModelLoadAdmission.requiredToLoadGb(weightsGb: -5, headroomGb: -1) == 0) +} + +// The headline fix: gpt-oss-20b (~13.5 GB weights) MUST load on a 24 GB box. +// Old gate: weights×2.0=27 vs free×0.7=(24-4)*0.7=14 → 27>14 → REJECTED. +// New gate: 13.5+2=15.5 vs free=20 → ADMITTED. +@Test func gptOssLoadsOn24GB() { + let ok = ModelLoadAdmission.canLoad( + weightsGb: 13.5, headroomGb: 2.0, + totalBytes: 24 * gib, gpuActiveBytes: 0, gpuCacheBytes: 0, reserveBytes: 4 * gib) + #expect(ok, "gpt-oss must load on a 24 GB box now") + + // And the OLD doubly-discounted gate would have rejected it — prove the gap. + let oldFreeUsable = ((24.0 - 4.0)) * 0.7 // 14.0 + let oldRequired = 13.5 * 2.0 // 27.0 + #expect(oldRequired > oldFreeUsable, "regression guard: old gate rejected this") +} + +// gemma-4-26b (~31 GB weights, 8-bit) genuinely does NOT fit a 32 GB box +// (weights + OS already ≈ the whole box) — must be rejected, not OOM'd. +@Test func gemma8bitRejectedOn32GB() { + let ok = ModelLoadAdmission.canLoad( + weightsGb: 31.3, headroomGb: 2.0, + totalBytes: 32 * gib, gpuActiveBytes: 0, gpuCacheBytes: 0, reserveBytes: 4 * gib) + #expect(!ok, "gemma-8bit can't fit 32 GB; must be rejected") +} + +// …but the 64 GB tier (18 machines in the fleet) MUST now serve gemma. +// Old gate needed free ≥ 31.3*2/0.7 ≈ 89 GB → rejected every box < ~96 GB. +@Test func gemmaLoadsOn64GB() { + let ok = ModelLoadAdmission.canLoad( + weightsGb: 31.3, headroomGb: 2.0, + totalBytes: 64 * gib, gpuActiveBytes: 0, gpuCacheBytes: 0, reserveBytes: 4 * gib) + #expect(ok, "gemma must load on a 64 GB box now (was rejected before)") +} + +@Test func cannotLoadWhenAnotherModelIsResident() { + // 64 GB box already holding gemma (31 GB resident) can't also cold-load it + // again / a second big model — eviction path handles that, gate says no room. + let ok = ModelLoadAdmission.canLoad( + weightsGb: 31.3, headroomGb: 2.0, + totalBytes: 64 * gib, gpuActiveBytes: 31 * gib, gpuCacheBytes: 0, reserveBytes: 4 * gib) + // free = 64-31-4 = 29; required = 33.3 → false + #expect(!ok) +} From 61fc6b4a8c44941d8e5a385a55f6d965c2249ce2 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Wed, 3 Jun 2026 16:34:58 -0700 Subject: [PATCH 2/3] fix(provider): apply the same one-request load gate to StandaloneServer (--local) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review parity follow-up: the --local standalone path still sized loads at estimatedMemoryGb × 2.0. Route it through the shared ModelLoadAdmission helper so the dev/local path matches the production ProviderLoop gate (weights + one-request headroom). Removes the now-unused modelLoadMemoryMultiplier. --- .../Sources/ProviderCore/Server/StandaloneServer.swift | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift index 5e99f0292d..71402e2b37 100644 --- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift +++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift @@ -99,11 +99,6 @@ public actor StandaloneServer { /// Internal access so the +HTTP extension can pass the same /// default through to ``MultiModelBatchSchedulerEngine``. static let schedulerDefaultMaxTokens = 4096 - /// Free-memory headroom required to admit a model load, as a multiple of - /// the model's estimated weight footprint. 2x leaves room for KV-cache - /// growth without blocking loads when other models are actively serving on - /// the same machine (3x was too conservative and rejected loads that fit). - static let modelLoadMemoryMultiplier = 2.0 /// Map a scheduler-side admission error message to an HTTP status. Used /// by tests and by any custom error-mapping middleware. Retained here @@ -496,7 +491,9 @@ public actor StandaloneServer { try Task.checkCancellation() try await evictIfNeededForLoad() try await ensureMemoryHeadroomForLoad( - requiredGb: modelInfo.estimatedMemoryGb * Self.modelLoadMemoryMultiplier + requiredGb: ModelLoadAdmission.requiredToLoadGb( + weightsGb: modelInfo.estimatedMemoryGb, + headroomGb: ModelLoadAdmission.defaultLoadHeadroomGb) ) try Task.checkCancellation() let container = try await LLMModelFactory.shared.loadContainer( From 13a4719adac64a69917a35c08d2e6f44a0934714 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Wed, 3 Jun 2026 18:10:40 -0700 Subject: [PATCH 3/3] fix(provider): make the looser load gate OOM-safe (system-free clamp + in-flight KV) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The one-request load gate let small/mid machines finally load models they can serve, but two holes could still drive a box into OOM: 1. System-free clamp. Free memory was computed as total − MLX.active − MLX.cache, which over-reports whenever the OS or other processes hold RAM. availableMemoryGb now also reads real OS-available memory (SystemMemory.availableBytes, via vm_statistics64) and takes the smaller of the two views, so the gate can never count memory that is already gone. 2. In-flight KV reservations. A concurrent preload/cold-load could place a new model's weights into memory already promised to a mid-decode request (those bytes may not yet appear in MLX.active/cache). The gate now subtracts GlobalKVCacheBudget.outstandingReservedBytes() before admitting a load. ModelLoadAdmission.freeForLoadGb/canLoad gain systemAvailableBytes (default .max) and outstandingReservationBytes (default 0), so the pure arithmetic stays unit-testable. ProviderLoop.availableMemoryGb / fastAdmissionReject and StandaloneServer.availableMemoryGb become async to query the KV actor; StandaloneServer drops its duplicated vm_statistics helper for the shared SystemMemory. The headline win is preserved: an idle box with low OS usage and no reservations still loads gpt-oss on 24 GB. Adds tests for the system clamp, reservation subtraction, and a guard that the idle-box gpt-oss-on-24GB case still passes under both clamps. --- .../Inference/GlobalKVCacheBudget.swift | 12 ++++ .../Inference/ModelLoadAdmission.swift | 47 ++++++++++--- .../ProviderCore/Inference/SystemMemory.swift | 37 ++++++++++ .../Sources/ProviderCore/ProviderLoop.swift | 51 ++++++++++---- .../Server/StandaloneServer.swift | 49 ++++---------- .../ModelLoadAdmissionTests.swift | 67 +++++++++++++++++++ 6 files changed, 205 insertions(+), 58 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Inference/SystemMemory.swift diff --git a/provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift b/provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift index a6b342674e..b6727c20a9 100644 --- a/provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift +++ b/provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift @@ -47,6 +47,18 @@ public actor GlobalKVCacheBudget { reservations.removeValue(forKey: requestID) } + /// Total KV bytes currently promised to in-flight requests. The model-load + /// gate subtracts this so a new model's weights can't be loaded into memory + /// already reserved for a request that is mid-decode (those bytes may not + /// yet show up in MLX.active/cache, so the load gate would otherwise treat + /// promised memory as free and risk an OOM). + public func outstandingReservedBytes() -> UInt64 { + reservations.values.reduce(UInt64(0)) { partial, value in + let (sum, overflow) = partial.addingReportingOverflow(value) + return overflow ? UInt64.max : sum + } + } + private func availableReservationBytes() -> UInt64 { let (total, active, cache) = memorySnapshot() let usedBeforeReservations = Self.saturatingAdd(active, cache, reserveBytes) diff --git a/provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift b/provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift index 7fad391cc4..08a29b465c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift @@ -23,20 +23,37 @@ public enum ModelLoadAdmission { /// from whatever is left. Tunable via provider config. public static let defaultLoadHeadroomGb: Double = 2.0 - /// Physical memory (GB) available to load a model: total minus the OS - /// reserve and whatever MLX already has resident (active + cache). NOTE: - /// deliberately NO 0.7 safety discount — weights are a known allocation, and - /// the 0.7 runtime safety is already applied per-request by - /// GlobalKVCacheBudget. Discounting here too is the double-count that kept - /// capable machines idle. + /// Physical memory (GB) available to load a model: the real free memory + /// (clamped to what the OS actually reports available, not just total minus + /// MLX's resident set) minus the OS reserve and any KV already promised to + /// in-flight requests. NOTE: deliberately NO 0.7 safety discount — weights + /// are a known allocation, and the 0.7 runtime safety is already applied + /// per-request by GlobalKVCacheBudget. Discounting here too is the + /// double-count that kept capable machines idle. + /// - Parameters: + /// - systemAvailableBytes: real OS-reported available memory (free + + /// reclaimable). Pass `.max` when unavailable to fall back to the + /// MLX-only view. The result is clamped to this so the gate can never + /// count memory the OS or other processes have already taken — the fix + /// for the OOM hole where `total − MLX.active − MLX.cache` over-reports. + /// - outstandingReservationBytes: KV bytes already promised to in-flight + /// requests (`GlobalKVCacheBudget`). Subtracted so a concurrent load + /// can't claim memory a mid-decode request is counting on. public static func freeForLoadGb( totalBytes: UInt64, + systemAvailableBytes: UInt64 = .max, gpuActiveBytes: UInt64, gpuCacheBytes: UInt64, - reserveBytes: UInt64 + reserveBytes: UInt64, + outstandingReservationBytes: UInt64 = 0 ) -> Double { - let used = saturatingAdd(gpuActiveBytes, gpuCacheBytes, reserveBytes) - let usable = totalBytes > used ? totalBytes - used : 0 + let mlxUsed = saturatingAdd(gpuActiveBytes, gpuCacheBytes) + let mlxFree = totalBytes > mlxUsed ? totalBytes - mlxUsed : 0 + // The OS view and the MLX view can each be the tighter bound; take the + // smaller so we never over-count free memory. + let realFree = min(mlxFree, systemAvailableBytes) + let committed = saturatingAdd(reserveBytes, outstandingReservationBytes) + let usable = realFree > committed ? realFree - committed : 0 return Double(usable) / bytesPerGb } @@ -51,11 +68,19 @@ public enum ModelLoadAdmission { weightsGb: Double, headroomGb: Double, totalBytes: UInt64, + systemAvailableBytes: UInt64 = .max, gpuActiveBytes: UInt64, gpuCacheBytes: UInt64, - reserveBytes: UInt64 + reserveBytes: UInt64, + outstandingReservationBytes: UInt64 = 0 ) -> Bool { - let free = freeForLoadGb(totalBytes: totalBytes, gpuActiveBytes: gpuActiveBytes, gpuCacheBytes: gpuCacheBytes, reserveBytes: reserveBytes) + let free = freeForLoadGb( + totalBytes: totalBytes, + systemAvailableBytes: systemAvailableBytes, + gpuActiveBytes: gpuActiveBytes, + gpuCacheBytes: gpuCacheBytes, + reserveBytes: reserveBytes, + outstandingReservationBytes: outstandingReservationBytes) return requiredToLoadGb(weightsGb: weightsGb, headroomGb: headroomGb) <= free } diff --git a/provider-swift/Sources/ProviderCore/Inference/SystemMemory.swift b/provider-swift/Sources/ProviderCore/Inference/SystemMemory.swift new file mode 100644 index 0000000000..9f65a91ab8 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/SystemMemory.swift @@ -0,0 +1,37 @@ +import Foundation + +/// Real, OS-reported available physical memory — what's actually free right now +/// accounting for macOS and every other process, not just what MLX is holding. +/// +/// The model-load gate needs this: `total − MLX.active − MLX.cache` over-reports +/// free memory whenever the OS or other processes have consumed RAM, which on a +/// tight 24–64 GB box can let a load slip in that then drives the machine into +/// memory pressure / OOM before the per-request KV budget can intervene. +public enum SystemMemory { + /// Available physical memory in bytes (free + inactive pages), or nil if the + /// host statistics call fails. Inactive pages are reclaimable, so they count + /// as available — matching how the OS reports "available". + /// + /// NOTE: `speculative_count` is deliberately NOT added: on macOS speculative + /// pages are already counted inside `free_count` (the `vm_stat` tool prints + /// "Pages free" as `free_count − speculative_count`). Adding speculative + /// again over-reports available memory and would undercut the load gate's + /// OOM-safety clamp. + public static func availableBytes() -> UInt64? { + var stats = vm_statistics64() + var count = mach_msg_type_number_t(MemoryLayout.size / MemoryLayout.size) + let result = withUnsafeMutablePointer(to: &stats) { ptr in + ptr.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { intPtr in + host_statistics64(mach_host_self(), HOST_VM_INFO64, intPtr, &count) + } + } + guard result == KERN_SUCCESS else { return nil } + var pages: UInt64 = 0 + for v in [UInt64(stats.free_count), UInt64(stats.inactive_count)] { + let (sum, overflow) = pages.addingReportingOverflow(v) + pages = overflow ? UInt64.max : sum + } + let (bytes, overflow) = pages.multipliedReportingOverflow(by: UInt64(getpagesize())) + return overflow ? UInt64.max : bytes + } +} diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index d4aa5cff89..4628ca241a 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -610,7 +610,7 @@ public actor ProviderLoop { // deliberately conservative: when in doubt it admits and lets the // post-accept load path below make the final call. let modelId = chatRequest.model - if fastAdmissionReject(modelId: modelId) { + if await fastAdmissionReject(modelId: modelId) { logger.warning("[\(requestId)] Pre-accept reject for '\(modelId)': insufficient capacity to load") send.send(.inferenceError( requestId: requestId, @@ -1441,10 +1441,12 @@ public actor ProviderLoop { // request is sized dynamically at runtime by the live token budget + // GlobalKVCacheBudget (which strictly rejects any request whose KV // won't fit real free memory, so this looser gate cannot OOM — worst - // case a box serves one request at a time). The old `× 2.0` here, - // combined with the `× 0.7` discount in availableMemoryGb, demanded - // free ≥ weights × 2.86 and left every small/mid machine unable to - // load a model it could actually serve. + // case a box serves one request at a time). The old gate demanded + // free ≥ weights × 2.86 (a `× 2.0` here on top of a `× 0.7` discount + // in availableMemoryGb) and left every small/mid machine unable to + // load a model it could actually serve. `availableMemoryGb` now + // clamps to real OS-available memory and subtracts in-flight KV + // reservations, so dropping the multiplier here is still OOM-safe. let requiredGb = ModelLoadAdmission.requiredToLoadGb( weightsGb: modelInfo.estimatedMemoryGb, headroomGb: Self.loadHeadroomGb) @@ -1553,12 +1555,24 @@ public actor ProviderLoop { /// safety is already enforced per request by GlobalKVCacheBudget. Applying it /// twice was the double-count that kept capable machines from ever loading a /// model they could serve. - private func availableMemoryGb() -> Double { - ModelLoadAdmission.freeForLoadGb( + /// + /// Two OOM-safety clamps make the looser gate sound: + /// 1. The free figure is clamped to what the OS actually reports available + /// (`SystemMemory.availableBytes`), not just `total − MLX.active − + /// MLX.cache`, which over-reports whenever the OS/other processes hold + /// RAM. + /// 2. KV already promised to in-flight requests + /// (`kvBudget.outstandingReservedBytes`) is subtracted, so a concurrent + /// load can't consume memory a mid-decode request is counting on. + private func availableMemoryGb() async -> Double { + let outstanding = await kvBudget.outstandingReservedBytes() + return ModelLoadAdmission.freeForLoadGb( totalBytes: ProcessInfo.processInfo.physicalMemory, + systemAvailableBytes: SystemMemory.availableBytes() ?? .max, gpuActiveBytes: UInt64(max(0, MLX.GPU.activeMemory)), gpuCacheBytes: UInt64(max(0, MLX.GPU.cacheMemory)), - reserveBytes: Self.memoryReserveBytes(forGiB: loopConfig.config.provider.memoryReserveGB)) + reserveBytes: Self.memoryReserveBytes(forGiB: loopConfig.config.provider.memoryReserveGB), + outstandingReservationBytes: outstanding) } /// Headroom (GB) reserved above the weights at load time for ONE request. @@ -1580,14 +1594,14 @@ public actor ProviderLoop { /// eviction since `await unloadModel` is a suspension point. /// Throws if the memory target cannot be met after exhausting evictable models. private func evictUntilAvailable(requiredGb: Double) async throws { - while availableMemoryGb() < requiredGb { + while await availableMemoryGb() < requiredGb { let modelsWithInflight = Set(requestToModel.values) let candidate = modelSlots .filter { !modelsWithInflight.contains($0.key) && !modelsUnloading.contains($0.key) } .min(by: { $0.value.lastInferenceAt < $1.value.lastInferenceAt }) guard let (modelId, _) = candidate else { - let available = String(format: "%.1f", availableMemoryGb()) + let available = String(format: "%.1f", await availableMemoryGb()) let required = String(format: "%.1f", requiredGb) throw InferenceError.modelLoadFailed( "Insufficient memory (\(available) GB free, need \(required) GB) and all loaded models are actively serving" @@ -1608,7 +1622,7 @@ public actor ProviderLoop { /// ``evictUntilAvailable`` WITHOUT loading anything and is deliberately /// conservative: anything that *could* succeed (including via eviction of /// an idle model) is admitted and left for the post-accept load path. - private func fastAdmissionReject(modelId: String) -> Bool { + private func fastAdmissionReject(modelId: String) async -> Bool { // Already resident — definitely serviceable. if modelSlots[modelId] != nil { return false @@ -1623,6 +1637,19 @@ public actor ProviderLoop { weightsGb: modelInfo.estimatedMemoryGb, headroomGb: Self.loadHeadroomGb) + // Sample live memory FIRST — this is the only suspension point in the + // method (it awaits the KV-budget actor). Reading all the actor-local + // slot/in-flight state AFTER the await means the decision below is made + // atomically with respect to this actor: nothing can mutate slots + // between the reads and the verdict, so there is no TOCTOU window. + let available = await availableMemoryGb() + + // Re-check residency after the suspension: the model may have been + // loaded by a concurrent request while we were awaiting memory. + if modelSlots[modelId] != nil { + return false + } + // An idle slot (loaded, no in-flight work, not already unloading) can be // evicted to make room, so its presence means we must NOT pre-reject. let modelsWithInflight = Set(requestToModel.values) @@ -1632,7 +1659,7 @@ public actor ProviderLoop { // Mirrors evictUntilAvailable's terminal failure: not enough free // memory and nothing idle to free. - if availableMemoryGb() < requiredGb && !hasEvictable { + if available < requiredGb && !hasEvictable { return true } diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift index 71402e2b37..d458cca2d4 100644 --- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift +++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift @@ -278,7 +278,7 @@ public actor StandaloneServer { private func ensureMemoryHeadroomForLoad(requiredGb: Double) async throws { guard requiredGb.isFinite, requiredGb > 0 else { return } - while availableMemoryGb() < requiredGb { + while await availableMemoryGb() < requiredGb { guard await evictLRUIdleScheduler() else { throw StandaloneServerError.capacityUnavailable( String(format: "Insufficient memory headroom to load model (needs %.1f GB available)", requiredGb) @@ -287,40 +287,19 @@ public actor StandaloneServer { } } - private nonisolated func availableMemoryGb() -> Double { - let mlxUsedBytes = Self.saturatingAdd(UInt64(max(0, MLX.GPU.activeMemory)), UInt64(max(0, MLX.GPU.cacheMemory))) - let totalBytes = ProcessInfo.processInfo.physicalMemory - let mlxHeadroomBytes = totalBytes > mlxUsedBytes ? totalBytes - mlxUsedBytes : 0 - let availableBytes = min(Self.systemAvailableMemoryBytes() ?? mlxHeadroomBytes, mlxHeadroomBytes) - return Double(availableBytes) / (1024.0 * 1024.0 * 1024.0) - } - - private nonisolated static func systemAvailableMemoryBytes() -> UInt64? { - var stats = vm_statistics64() - var count = mach_msg_type_number_t(MemoryLayout.size / MemoryLayout.size) - let result = withUnsafeMutablePointer(to: &stats) { ptr in - ptr.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { intPtr in - host_statistics64(mach_host_self(), HOST_VM_INFO64, intPtr, &count) - } - } - guard result == KERN_SUCCESS else { return nil } - let availablePages = Self.saturatingAdd( - UInt64(stats.free_count), - UInt64(stats.inactive_count), - UInt64(stats.speculative_count) - ) - let (bytes, overflow) = availablePages.multipliedReportingOverflow(by: UInt64(getpagesize())) - return overflow ? UInt64.max : bytes - } - - private nonisolated static func saturatingAdd(_ values: UInt64...) -> UInt64 { - var total: UInt64 = 0 - for value in values { - let (sum, overflow) = total.addingReportingOverflow(value) - if overflow { return UInt64.max } - total = sum - } - return total + /// Free memory (GB) for loading a model, via the shared OOM-safe arithmetic: + /// clamped to real OS-available memory (`SystemMemory`) and minus any KV + /// already promised to in-flight requests (`kvBudget`). See + /// `ModelLoadAdmission` for the rationale. + private func availableMemoryGb() async -> Double { + let outstanding = await kvBudget.outstandingReservedBytes() + return ModelLoadAdmission.freeForLoadGb( + totalBytes: ProcessInfo.processInfo.physicalMemory, + systemAvailableBytes: SystemMemory.availableBytes() ?? .max, + gpuActiveBytes: UInt64(max(0, MLX.GPU.activeMemory)), + gpuCacheBytes: UInt64(max(0, MLX.GPU.cacheMemory)), + reserveBytes: 0, + outstandingReservationBytes: outstanding) } /// Touch the cached scheduler's last-used timestamp on access. diff --git a/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift b/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift index 43665bfe47..f18ed1678e 100644 --- a/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift @@ -66,3 +66,70 @@ private let gib: UInt64 = 1024 * 1024 * 1024 // free = 64-31-4 = 29; required = 33.3 → false #expect(!ok) } + +// OOM-safety #1: the free figure is clamped to what the OS actually reports +// available, NOT just total − MLX.active − MLX.cache. MLX may be holding almost +// nothing while another process (or the OS) has eaten most of RAM. +@Test func freeIsClampedToRealSystemAvailable() { + // 64 GB box, MLX holding nothing → MLX view says ~60 GB free, but the OS + // reports only 10 GB actually available. We must take the OS figure. + let free = ModelLoadAdmission.freeForLoadGb( + totalBytes: 64 * gib, + systemAvailableBytes: 10 * gib, + gpuActiveBytes: 0, gpuCacheBytes: 0, + reserveBytes: 4 * gib) + // realFree = min(64, 10) = 10; minus 4 reserve → 6 + #expect(abs(free - 6.0) < 0.001) +} + +@Test func systemClampBlocksLoadThatMlxViewWouldAllow() { + // gpt-oss (13.5 GB) on a 64 GB box looks fine to the MLX view, but if the OS + // only has 12 GB free right now the load must be rejected, not OOM'd. + let ok = ModelLoadAdmission.canLoad( + weightsGb: 13.5, headroomGb: 2.0, + totalBytes: 64 * gib, + systemAvailableBytes: 12 * gib, + gpuActiveBytes: 0, gpuCacheBytes: 0, + reserveBytes: 4 * gib) + // realFree = min(64,12)=12; minus 4 → 8 usable; required 15.5 → reject + #expect(!ok, "must reject when the OS, not MLX, is the binding constraint") +} + +// OOM-safety #2: KV already promised to in-flight requests is subtracted, so a +// concurrent cold-load can't claim memory a mid-decode request is counting on. +@Test func outstandingReservationsReduceFree() { + // 32 GB box, 4 GB reserve, 6 GB of KV promised to in-flight requests. + let free = ModelLoadAdmission.freeForLoadGb( + totalBytes: 32 * gib, + gpuActiveBytes: 0, gpuCacheBytes: 0, + reserveBytes: 4 * gib, + outstandingReservationBytes: 6 * gib) + // 32 - 4 reserve - 6 reserved → 22 + #expect(abs(free - 22.0) < 0.001) +} + +@Test func outstandingReservationsCanBlockASecondLoad() { + // 24 GB box serving gpt-oss: weights resident (13.5 GB ≈ active) plus 6 GB of + // promised KV. A second cold-load of another ~13.5 GB model must be rejected. + let ok = ModelLoadAdmission.canLoad( + weightsGb: 13.5, headroomGb: 2.0, + totalBytes: 24 * gib, + gpuActiveBytes: 13 * gib, gpuCacheBytes: 0, + reserveBytes: 4 * gib, + outstandingReservationBytes: 6 * gib) + // realFree (MLX) = 24-13 = 11; minus 4 reserve minus 6 reserved → 1; need 15.5 + #expect(!ok, "promised KV must block a competing cold-load") +} + +// The headline win MUST survive the new clamps: an idle box with low OS usage +// and no reservations still loads gpt-oss on 24 GB. +@Test func idleBoxStillLoadsGptOssWithClamps() { + let ok = ModelLoadAdmission.canLoad( + weightsGb: 13.5, headroomGb: 2.0, + totalBytes: 24 * gib, + systemAvailableBytes: 21 * gib, // OS reports plenty free + gpuActiveBytes: 0, gpuCacheBytes: 0, + reserveBytes: 4 * gib, + outstandingReservationBytes: 0) + #expect(ok, "the core fix must still hold under the OOM-safety clamps") +}