Repository navigation
fix(provider): load models for one-request fit, not full-concurrency headroom #273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
e54fbf7
fix(provider): load models for one-request fit, not full-concurrency …
Gajesh2007 61fc6b4
fix(provider): apply the same one-request load gate to StandaloneServ…
Gajesh2007 13a4719
fix(provider): make the looser load gate OOM-safe (system-free clamp …
Gajesh2007 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
provider-swift/Sources/ProviderCore/Inference/ModelLoadAdmission.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
|
||
| /// 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
37
provider-swift/Sources/ProviderCore/Inference/SystemMemory.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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
inferenceAcceptedhas already been sent, butBatchScheduler/GlobalKVCacheBudget.reserve()can still reject the real prompt+max-token budget withtoken_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 👍 / 👎.