Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Size load headroom from the actual request

This fixed 2 GB headroom does not prove that even the first accepted request fits: long prompts or models whose scheduler raises the default output budget toward 8192 tokens can require more than 2 GB of KV. On a tight cold load that now passes with only this margin, the model is loaded and inferenceAccepted has already been sent, but BatchScheduler/GlobalKVCacheBudget.reserve() can still reject the real prompt+max-token budget with token_budget_exhausted; use the decoded request budget or a conservative model-specific KV estimate for the load gate instead of a constant.

Useful? React with 👍 / 👎.


/// 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,
outstandingReservationBytes: UInt64 = 0
) -> Double {
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
}

/// 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,
systemAvailableBytes: UInt64 = .max,
gpuActiveBytes: UInt64,
gpuCacheBytes: UInt64,
reserveBytes: UInt64,
outstandingReservationBytes: UInt64 = 0
) -> Bool {
let free = freeForLoadGb(
totalBytes: totalBytes,
systemAvailableBytes: systemAvailableBytes,
gpuActiveBytes: gpuActiveBytes,
gpuCacheBytes: gpuCacheBytes,
reserveBytes: reserveBytes,
outstandingReservationBytes: outstandingReservationBytes)
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
}
}
37 changes: 37 additions & 0 deletions provider-swift/Sources/ProviderCore/Inference/SystemMemory.swift
Original file line number Diff line number Diff line change
@@ -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<vm_statistics64>.size / MemoryLayout<integer_t>.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
}
}
84 changes: 62 additions & 22 deletions provider-swift/Sources/ProviderCore/ProviderLoop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1436,14 +1436,20 @@ 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 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)
try await evictUntilAvailable(requiredGb: requiredGb)
try Task.checkCancellation()
if isShuttingDown { throw CancellationError() }
Expand Down Expand Up @@ -1544,16 +1550,35 @@ public actor ProviderLoop {
}
}

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)
/// 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.
///
/// 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),
outstandingReservationBytes: outstanding)
}

/// 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 {
Expand All @@ -1569,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"
Expand All @@ -1597,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
Expand All @@ -1608,7 +1633,22 @@ 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)

// 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.
Expand All @@ -1619,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
}

Expand Down
Loading
Loading