Repository navigation
perf(cbv2): retain free paged KV segments and grow new ones from host-zeroed pages - #328
Merged
Merged
Conversation
Format-only (`swift format`, repository `.swift-format`). The Lint workflow formats every Swift file a pull request touches; two expressions added by #316 were not formatted on main, and the next commit edits this file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…out a stream fence Row release used to retire every fully free 64 MiB segment, so each admission re-allocated, zero-filled, evaluated and stream-synchronized new ones. A pool configured with retainedFreeSegmentBytes now parks those evaluated backings outside the committed set (grant, floor and ledger coverage released exactly as before) and reinstalls one of the same size class, covered by the same admission, at the next growth without allocating, filling or fencing. Retained backing is dropped on a refused admission or allocation and after the engine idles. hostZeroedSegments wraps zero-fill-on-demand host pages as the segment buffer without a copy, so growth schedules no stream work, takes no MLX eval lock and waits on no completion fence. It sits beside #316's hostMaterialized import path: cbv2HostZeros copies into a fresh allocator buffer for an evaluator that skips available arrays, while the pool's growth evaluator takes the eval lock unconditionally, so a wrapped segment returns before evaluation. Both options default off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Retained free segments are live allocator memory outside every grant, so neither a cache flush nor another engine's refused charge could reclaim them. CBv2RetainedKVSegments.requestRelease() advances a process epoch; each pool drops its retained backing at its engine's next step (pools stay engine-queue confined). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Retained free segments are allocator-active memory outside every grant. Pools mirror their parked bytes into CBv2RetainedKVSegments.retainedBytes (parking, reinstall, release and group teardown), so provider load admission can count that backing as reclaimable and wait for engines to drop it after a release request before evicting a resident model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Gajesh2007
added a commit
to Layr-Labs/d-inference
that referenced
this pull request
Oct 22, 2026
Layr-Labs/mlx-swift-lm#328 squash-merged as 07b48961 ("perf(cbv2): retain free paged KV segments and grow new ones from host-zeroed pages (#328)"). Move the gitlink from the PR branch head 4cb9a532 to that commit on SDK main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007
added a commit
to Layr-Labs/d-inference
that referenced
this pull request
Oct 22, 2026
…nts warm (#1545) * Keep busy engines' MLX buffer pool and paged KV segments warm The proactive MLX cache sweep ran synchronize + clearCache under the eval lock every capacity tick whenever the pool exceeded 2 GiB, between busy engines' steps, and every flush reported device activity. It now waits for five seconds of whole-Mac idleness and flushes without reporting activity; busy engines flush only when the pool crowds out admission headroom. A refused engine-owned KV charge signals the shortfall-gated reclaim that request reservations already use. DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0 restores the old sweep. Segmented paged pools retain up to min(2 GiB, grant / 8) of free segments across requests and allocate new ones from zero-fill-on-demand host pages. DARKBLOOM_TTFT_SEGMENT_RETENTION=0 restores release-time trimming and device fills; DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0 keeps retention with device fills. Pins libs/mlx-swift-lm to the paired SDK branch (segment retention, the release request and the retained-bytes gauge) on the SDK commit master pins; libs/mlx-swift and libs/mlx stay at master's commits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Reclaim retained KV segments on memory pressure Shortfall reclaims (request and engine-owned refusals), pressure-window sweeps and macOS memory-pressure events now also ask every engine to drop its retained free KV segments, which no cache flush reaches. A shortfall the MLX cache cannot cover still releases them. Adds the idle-sweep tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop the MLX buffer pool before evicting a model for a cold load Busy engines now keep the reusable MLX pool up to its cache limit, and the load gate counts that pool as used. Both load paths (ProviderLoop's evictUntilAvailable, StandaloneServer's headroom gate) now flush the pool and resample once before unloading a resident model for room, so a pool-inflated box does not evict a model it could keep. Follows DARKBLOOM_TTFT_IDLE_CACHE_SWEEP (=0 keeps evict-first). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Release retained KV segments before a cold load evicts or refuses Retained free paged segments are allocator-active memory, so load admission treated them as used. Count them as reclaimable (the process-wide retained-bytes gauge comes from the paired SDK change), and in the ProviderLoop and standalone load paths and the fast pre-accept self-heal request their release and wait briefly for engines to drop them before the pool flush and resample, ahead of evicting a resident model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Test that the standalone headroom gate releases retained KV segments StandaloneServer.ensureMemoryHeadroomForLoad releases retained free KV segments and drops the MLX buffer pool once before it evicts or refuses. Cover the refusing path: a gate that may not evict still waits for the engine to drop its parked segment backing, then refuses without unloading or shutting down the resident model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: idle-gated cache sweep and retained paged KV segments Describe the busy-engine cache sweep window, retained free segments and host-zeroed growth in the inference architecture, the load gate's release of retained segments before eviction in the memory model, and the standalone load headroom path in direct mode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): forward the serving-stall rollbacks to launchd launchd does not inherit the installing shell, so a DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0, DARKBLOOM_TTFT_SEGMENT_RETENTION=0 or DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0 export reached only a foreground provider: the background provider job kept the idle-gated sweep and the retained, host-zeroed KV segments, and restarts and watchdog recovery reuse its saved plist. Name the three keys and add them to LaunchAgent.inferencePassthroughEnvKeys, so darkbloom start persists them into the provider plist. The watchdog plist stays without them: it never runs inference. The changelog now says what the old segment growth waited for: queued GPU work drained under the process-wide MLX eval lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Stop waiting for retained KV segments once a load is cancelled releaseRetainedKVSegments polled with `try? Task.sleep(for:)`. In a cancelled load the sleep threw at once and the loop swallowed it, so the task spun until its 250 ms deadline. The loop also used the generic sleep overload that TaskSleep.swift tells ProviderCore to avoid in release builds. Sleep through taskSleep and return on cancellation; the release request stays posted for the engines' next steps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(provider): name the reclaimer flush; describe the windowed sweep flushIfDue took its flush as a parameter named clearCache, which shadowed the stored clearCache, so `clearCache()` inside it silently meant the argument (the idle or the device flush). Name it `flush`. The sweep's entry point (proactiveReclaimSweep) and its ProviderLoop driver still said the sweep returns freed buffers instead of letting them accumulate. Busy engines now keep the pool, up to the cache limit, while admission headroom is healthy. Say so, and why engine-owned refusals now signal a reclaim. No behavior change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(provider): pin segment-retention wiring and release-before-eviction order No test read the segmented factory's retention settings. The min(2 GiB, grant / 8) cap, the 30 s idle release that the docs quote and the DARKBLOOM_TTFT_SEGMENT_HOST_ZEROS rollback were unchecked. Build backends from the factory under each environment and read their pool configuration. retainedSegmentsReleaseBeforeEviction checked the parked bytes only after evictUntilAvailable returned. The final nothing-evictable refusal also releases them, so the test passed even without the release before the eviction. Record the parked bytes when the resident model shuts down; makeInertStubBridge gains an optional onShutdown hook for that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: match the serving-stall wording to the code - inference.md: admission no longer waits for queued GPU work (it never stalled the queue itself). The eval lock is the process-wide part, not the stream synchronize. Host pages are wrapped only for segments that are a whole number of VM pages. The sweep flushes between busy engines' steps when the pool crowds out headroom, which "never ... unless" contradicted. - hardware-support.md: shortfall reclaims and pressure sweeps ask engines to drop retained segments even when they do not flush. - configuration.md: cold loads release retained segments before evicting or refusing; the page-granular condition for host pages. - changelog: the sweep still flushes busy engines under headroom pressure; cold loads also release retained segments before refusing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Re-pin libs/mlx-swift-lm to the merged SDK change (#328) Layr-Labs/mlx-swift-lm#328 squash-merged as 07b48961 ("perf(cbv2): retain free paged KV segments and grow new ones from host-zeroed pages (#328)"). Move the gitlink from the PR branch head 4cb9a532 to that commit on SDK main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): signal a shortfall reclaim on refused native MiMo media charges MiMoV26ManagedMediaReservation charges the process ledger directly, so its refusals never reached recordReservationRefusal or the engine-owner callback. With busy engines keeping MLX's buffer pool and retained KV segments, a media reservation a release or flush would fit could keep failing until the Mac idled. Each insufficientCapacity refusal (initial charge, decode working bytes, native plan adoption, recheck) now signals the same shortfall-gated reclaim. The ledger snapshot omits the media path's extra system reserve, which can shrink headroom by at most its own size, so the signalled shortfall is an upper bound: retained segments are always asked back, and the cache is flushed only when it certainly covers the refusal. GlobalKVCacheBudget.directChargeRefusalSignal builds the signal for both direct-charge owners and is nil under the existing kill switch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): keep engine-refusal reclaim signals on while segments are retained signalsEngineRefusals followed only the idle-sweep kill switch, so with DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0 and segment retention still on, a refused engine-owned growth no longer asked other pools to drop their retained segments, which no cache flush reaches. One predicate, busyEnginesKeepReclaimableMemory (idle sweep or retention on), now drives both the refusal signal and the load gates' one-time release-and-flush pass. The production budget takes its environment as a defaulted parameter so the wiring is tested directly rather than through the test initializer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): release retained KV segments in the Nemotron Super load gate Managed Super loads bypass evictUntilAvailable, so their gate neither released retained free KV segments nor dropped the buffer pool busy engines now keep before evicting an idle model or refusing, and its pre-accept counted retained segments as used. Super loads could evict needlessly, refuse a load that fits, or be fast-rejected. evictUntilNemotronSuperFits now runs the ordinary gate's one-time release-and-flush pass before its first eviction and before refusing with nothing idle; reclaimableMemoryBytes counts retained segments, so the reachable room both gates plan with includes them, and nemotronSuperLoadIsCertainToFail counts them in its nothing-evictable branch. The release-then-flush step is one helper, releaseReclaimableMemoryForLoad, on ProviderLoop and StandaloneServer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): reclaim retained KV segments before skipping a startup preload A startup preload candidate whose shortfall the previous model's retained segments (or the kept buffer pool) covered was skipped and left cold until its first request, because the preloader compared free memory without the release the load gates run. StartupPreloader takes a reclaimBeforeSkip hook: on a short sample it releases what a load reclaims without evicting, then resolves the live requirement (Super's tracks its claim room) and samples free memory again before skipping. ProviderLoop and StandaloneServer wire it to releaseReclaimableMemoryForLoad. Preload still never evicts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): make the idle cache flush atomic with request admission The idle sweep rechecked WholeMacServiceBudget.isIdle and then synchronized and cleared, so a request admitted in between started on a pool being emptied. When the recheck bailed out, flushIfDue still stamped lastReclaimAt and recorded a reclaim, suppressing a real shortfall reclaim for the rate-limit interval. The idle flush now fences outside the budget, then clears inside WholeMacServiceBudget.performIfIdle, which runs its body under the same lock as admission and device-activity starts: a request admitted first cancels the clear, and one arriving during it is admitted afterwards. An idle Mac has no charged GPU work, so the clear does not wait on evals while holding the lock. Flush callbacks report whether they ran, and only a flush that ran records a reclaim and starts the next window. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(provider): describe exactly which load paths release retained KV segments The changelog, configuration reference and hardware-support page said cold loads release retained segments before evicting or refusing. Name the paths that do (the provider, standalone and managed Nemotron Super load gates, and the startup-preload check), state that the post-load headroom guard measures without releasing them (that backing was already counted as used when the gate admitted the load), and document the idle flush's atomicity with admission and the direct-charge refusal signal (native MiMo media included, on while retention is on). inference.md now cites repo paths and symbols instead of bare file names. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(provider): tidy the serving-stalls review follow-ups Behavior-preserving cleanup from the independent refactor pass: - busyEnginesKeepReclaimableMemory's comment now names every direct charge that signals a reclaim (directChargeRefusalSignal), not only engine-owned growth, since native MiMo media reservations use it too. - idleOperationHoldsOffAdmission records the idle operation and the admission as ordered events instead of reusing a pool-size field as a flag, so the assertion states the ordering it checks. - Rewrap two over-long lines in hardware-support.md and inference.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): report the exact ledger deficit for refused direct charges A refused native MiMo media charge added its extra OS reserve to the reclaim shortfall unconditionally, but ProcessMemoryLedger narrows only the OS-available side with that reserve, never the cap. When the cap bound (the usual case on large Macs) the shortfall overshot by the whole reserve, so KVPoolReclaimer skipped a buffer-cache flush that would have let the retry fit. A refused engine-owned paged charge in commitment debt had the opposite error: it ignored the debt and under-reported. ProcessMemoryLedger.capacityShortfall now computes, under the ledger lock, outstanding + growth - headroom with the same min(cap, system - extra) - reserve arithmetic admission uses, and both owners report it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): count usage inside the reserve in the refusal shortfall ProcessMemoryLedger.capacityShortfall subtracted the admission headroom, which floors at zero once active plus cache memory reaches the activation reserve below the cap, or OS-available memory falls below the reserves. That is where refusals cluster, and there it reported only the outstanding commitment plus growth. KVPoolReclaimer then flushed the buffer cache whenever the cache covered that figure, even when the flush could not admit the retry, stalling busy engines for nothing. The shortfall is now the larger of the cap-side and OS-side deficits, neither floored: exactly what usage must fall by for the charge to fit. It is unchanged wherever headroom is positive. The MiMo reservation's onRefusal doc no longer calls the signal an upper bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(provider): count retained KV segments as eviction credit only until released ProviderLoop.reclaimableMemoryBytes added the live retained-segment gauge (CBv2RetainedKVSegments.retainedBytes) to every eviction and pre-accept feasibility check. A busy engine drops its segments only at its next step, which can outlast the 250 ms wait in releaseRetainedKVSegments, and it can park more meanwhile. After the one-time release the gates still counted those bytes, so evictUntilAvailable and evictUntilNemotronSuperFits could pass their feasibility check, evict an idle model, and then refuse the load anyway ("all loaded models are actively serving"). Pre-accept could also admit on the same bytes. Retained segments now count only to decide whether that release could make room. After the release, eviction credit is the idle models' weights and the buffer cache, and the memory sample shows what the release returned. The ordinary pre-accept and the managed Super pre-accept (nemotronSuperLoadIsCertainToFail, now async) run the same release-and-resample when nothing is idle or when only retained segments could close the gap. They decide on the room that remains and re-check the request's verdicts after the suspension. Segments are still released before any eviction or refusal. Regression tests use a RetainingEngineStub that does not step within the wait, with the unreleased bytes as the margin. They cover the ordinary gate and pre-accept and the Super gate and pre-accept. A Super pre-accept whose engine does step is still admitted. Docs and the changelog fragment describe the narrower credit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(provider): note which refusals skip the retained-segment release The load gates refuse at once, without releasing retained KV segments, when not even those segments and every idle model's weights could make room. Pre-accept also releases when nothing is idle, not only when the segments alone could close the gap. State both in the hardware-support memory notes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Place standalone load-headroom sentence apart from sibling PRs' edits Move the ensureMemoryHeadroomForLoad sentence ahead of the preload_models precedence sentence so it no longer edits the line next to the shape-warmup rewrite of the standalone self-test sentence. Pure move with rewrapping; the sentence text is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Nov 20, 2026
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Paged admission on a segmented pool allocated, zero-filled, evaluated and stream-synchronized every new 64 MiB KV segment, because row release dropped every fully free segment. The fill's
evalandStream.synchronize()both run under the process-wide MLX eval lock. Every admission therefore waited for the engine's queued GPU work, and other engines' evals waited behind it. This PR adds two pool options, both off by default (the provider turns them on), and a process-wide release request with a gauge.PagedKVPoolConfig.retainedFreeSegmentBytes: release parks free segment backings up to this many bytes. Parked backing leaves the committed set exactly like a trim (grant, floor and ledger coverage are released), and the next growth of the same size class reinstalls it without allocating, filling or fencing.PagedKVPoolConfig.hostZeroedSegments: a new segment wraps zero-fill-on-demand anonymous pages as its Metal buffer, without a copy (MLXArray.cbv2ZeroFilledPages). Growth schedules no stream work, takes no eval lock and waits on no fence.CBv2RetainedKVSegments: a process-wide release request (an epoch that each pool honors at its engine's next step, so pools stay engine-queue confined) and a retained-bytes gauge. The provider uses both to reclaim parked backing on memory pressure and before a cold load evicts a model.Parked backing is also dropped on a refused admission or allocation, and after
retainedFreeSegmentIdleSeconds(30 s) of engine idleness.51c1ec63style(paged): format PagedKVSegments.swiftmain, and the Lint job formats every file a PR touchesd95ab76eRetain free paged KV segments across requests; allocate new ones without a stream fenceEngineLoopV2, testsa50ec95aDrop retained KV segments on a process-wide release requestCBv2RetainedKVSegments.requestRelease(), the step hook inEngineLoopV24cb9a532Gauge retained paged KV segment bytes process-wideCBv2RetainedKVSegments.retainedBytes(park, reinstall, release, group teardown)The paired provider PR is Layr-Labs/d-inference branch
ttft/serving-stalls. It enables the options and pins this branch.Before
flowchart TB subgraph SB["Behavior: paged admission on a segmented pool"] direction LR rb["Row released"]:::input --> tb["Every fully free 64 MiB<br/>segment is dropped"]:::slow ab["Next admission"]:::input --> zb["Each new segment:<br/>device zero fill"]:::slow zb --> eb["eval under the<br/>MLX eval lock"]:::slow eb --> fb["Stream synchronize under<br/>the eval lock: waits for<br/>queued GPU work"]:::slow fb --> gb["Growth per admission<br/>Gemma: p50 7.1 ms, max 12.7 ms"]:::slow end subgraph CB["Code flow"] direction LR pb["PagedKVPool<br/>trimFreeSegments"]:::code --> kb["PagedKVGroup.trimSegments<br/>drops the backing"]:::code qb["PagedKVPool+Segments<br/>growth"]:::code --> hb["PagedKVGroup<br/>prepareGrowth"]:::code hb --> sb["PagedKVSegment.init<br/>zeros, evaluate, fence"]:::code end SB ~~~ CB style SB fill:#f8fafc,stroke:#64748b,color:#0f172a style CB fill:#f8fafc,stroke:#64748b,color:#0f172a classDef input fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a classDef code fill:#e0e7ff,stroke:#4338ca,color:#1e1b4b classDef slow fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d linkStyle default stroke:#64748b,stroke-width:1.5px linkStyle 8 stroke:none,stroke-width:0pxAfter
flowchart TB subgraph SA["Behavior: paged admission on a segmented pool"] direction LR ra["Row released"]:::input --> ta["Free segments parked up to<br/>retainedFreeSegmentBytes:<br/>no grant, floor or ledger charge"]:::new aa["Next admission"]:::input --> qa{"Parked backing of<br/>the same size class?"}:::decide qa -- "yes" --> ia["Reinstall under the new range:<br/>no allocation, fill or fence"]:::new qa -- "no" --> ha{"hostZeroedSegments and<br/>a page-granular size?"}:::decide ha -- "yes" --> wa["Wrap zero-fill-on-demand pages<br/>without a copy: no eval,<br/>no fence, no eval lock"]:::new ha -- "no" --> da["Device zero fill, eval, fence<br/>(unchanged path)"]:::stock ia --> ga["Growth per admission<br/>Gemma: p50 0.16 ms, max 0.26 ms"]:::new wa --> ga end subgraph RA["Code flow: parked backing is released"] direction LR xa["Refused admission<br/>or allocation"]:::release --> la["releaseRetainedSegments"]:::release ya["Engine idle for 30 s<br/>(EngineLoopV2 idle hook)"]:::release --> la za["CBv2RetainedKVSegments<br/>.requestRelease(): an epoch<br/>honored at the next step"]:::release --> la la --> ma["Process-wide gauge<br/>CBv2RetainedKVSegments<br/>.retainedBytes"]:::state end SA ~~~ RA style SA fill:#f8fafc,stroke:#64748b,color:#0f172a style RA fill:#f8fafc,stroke:#64748b,color:#0f172a classDef input fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a classDef new fill:#dcfce7,stroke:#15803d,color:#14532d classDef decide fill:#fef3c7,stroke:#b45309,color:#78350f classDef stock fill:#e5e7eb,stroke:#4b5563,color:#111827 classDef release fill:#ffedd5,stroke:#c2410c,color:#7c2d12 classDef state fill:#ede9fe,stroke:#6d28d9,color:#3b0764 linkStyle default stroke:#64748b,stroke-width:1.5px linkStyle 12 stroke:none,stroke-width:0pxLegend: blue marks inputs, indigo unchanged code, red the per-admission stall, amber decisions, green new behavior, grey the unchanged fallback, orange the release paths for parked backing, and purple the process-wide gauge. Growth figures are from the Gemma 4 runs in the evidence table.
Reconciliation with #316 (
cbv2HostZeros)#316 added
hostMaterializedtoPagedKVSegment.initfor checkpoint imports. That path copies host zeros into a fresh allocator buffer (cbv2HostZeros) and relies on an evaluator that skips available arrays (evaluateUnavailable). Pool growth cannot reuse it unchanged:slabEval) evaluates unconditionally and takes the eval lock. A host-copied array would still wait for the lock.cbv2HostZeroscopies the whole segment, and briefly commits a second host buffer of the same size outside MLX's allocator.This branch therefore leaves #316's lines unchanged and adds
hostZeroedas an early return before evaluation.cbv2ZeroFilledPagesmaps anonymous pages and hands them to MLX'smake_bufferwithout a copy. MLX counts the exact length as active memory. When Metal refuses the wrap, MLX itself falls back to a copied allocation. When the size is not page-granular, the helper returns nil and growth takes the device fill plus fence, as before; pool growth never passeshostMaterialized. Checkpoint staging is unchanged: it keeps #316'shostMaterializedcopy and never passeshostZeroed. A checkpoint import's suffix growth (prepareImport) now goes through the same growth helper, so it can reinstall parked backing of the same size class, but it never wraps host pages.Evidence (M5 Ultra, 80-core GPU)
All numbers were measured by the implementer on pre-rebase builds that carried a measurement-only trace commit, which this branch drops. Each provider run had 5 decode streams, plus a cold arrival every 2 s (2,048, 512 or 4,096 prompt tokens) for 70 s; the first 10 s are excluded. "off" sets
DARKBLOOM_TTFT_SEGMENT_RETENTION=0 DARKBLOOM_TTFT_IDLE_CACHE_SWEEP=0; "on" is the default. The provider PR has the end-to-end tables.scratchpad/stalls/hold-q1.logscratchpad/stalls/hold-q4.logscratchpad/stalls/hold-q2.logscratchpad/stalls/h3-q1.log,h3-q2.logThe benchmark is
scratchpad/stalls/growth-bench-1.log, a Gemma-4-like geometry. In the configuration this PR enables, the first 2,048-token KV write into the grown backing was unchanged: p50 36.73 ms before and 36.52 ms after (idle). Host zeros without retention made that write slower, p50 43.55 ms idle, because fresh pages fault on first touch. The provider always pairs host zeros with retention. Row release behind co-resident work fell from p50 29.43 ms to 3.12 ms, because a pool that keeps its backing skips the empty-pool retirement synchronize.scratchpadis/private/tmp/claude-501/-Users-gaj-Documents-Builds-Darkbloom/8eacbef9-e1dd-444e-98a8-972bc1d30258/scratchpadon the M5 Ultra.Validation
Run on M5 Ultra in a fresh PR clone. Toolchain: Apple Swift 6.4 (Command Line Tools), XCTest from Xcode 27.1, and
libs/mlx-swift81f58d79(nested MLX71271f08).swift build --build-tests(debug, clean build directory)../../scripts/stage-test-metallib.sh "$(swift build --show-bin-path)"mlx.metallibSHA-256fb1ba8f9…c85c, from nested MLX71271f08swift test --skip-build --no-parallel --filter 'CBv2PagedSegmentRetentionTests|CBv2CheckpointAdmissionTransferTests|CBv2PagedGrantTests|CBv2PagedPoolGuardTests|CBv2PagedSegmentDispatchCacheExecutionTests|CBv2PagedSegmentDispatchCacheTests|CBv2PagedSegmentTests|CBv2PagedSlabCommitmentTests|PagedCompleteCheckpointCodecTests'(one exclusive GPU ticket)swift format format --configuration .swift-formaton the 6 changed files: swift-format 604.0.0 (Homebrew) and the Swift 6.4 Command Line Tools formatterpython3 scripts/check_forkdiff.pyTests/MLXLMTests/CBv2*glob. The merge-base check needs upstreammainand was skippedLogs:
scratchpad/pr/stalls-work/logs/build-sdk-tests-1.logandsdk-gpu-tests-1.log.Not run here: the
CBv2CompleteCheckpointTestsXCTest suite, which exercises #316's import path. The Command Line Tools runner runs only Swift Testing. Also not run: the full SDK suite.Compatibility
PagedKVPoolConfigfields, each with a defaulted initializer argument, and theCBv2RetainedKVSegmentsenum. Existing callers keep the old behavior.PagedKVSegment.init(internal) gainshostZeroed: Bool = falsenext tohostMaterialized.reinstalledStaleSegmentsDecodeLikeFreshStoragecovers this.Rollback
Leave the options at their defaults (off). In the provider,
DARKBLOOM_TTFT_SEGMENT_RETENTION=0turns off both retention and host zeros, andDARKBLOOM_TTFT_SEGMENT_HOST_ZEROS=0turns off host zeros only.Limitations
retainedFreeSegmentBytesof allocator memory while its engine serves, and for 30 s after it idles. The provider cap ismin(2 GiB, grant / 8).main(Stage provider checkpoint imports without the MLX eval lock #316 and the Nemotron Super commits). The retention and growth code is the same as in the measured build, apart from the Stage provider checkpoint imports without the MLX eval lock #316 reconciliation described above.Landing order
Land this PR first. The provider PR then re-pins
libs/mlx-swift-lmfrom this branch head to the merged commit onmain.Refactor pass
The independent refactor pass required by d-inference
AGENTS.mdreviewed this branch (six files, eight tests) and this description. It changed no code, so the provider PR's pin stays at4cb9a532.trimSegments(willRetire:)still serves native pool retirement. Refused admissions and failed allocations drop parked backing. The gauge stays exact through reinstall, release and group teardown.mainlacks. All 8 pass in the run above.EngineLoopV2step-hook comment names only memory pressure as a release trigger. AnyrequestRelease()triggers it, including refused charges and cold loads.retainedSegmentsTouchedNanosis documented as "parked or reinstalled", but any trim refreshes it.cbv2ZeroFilledPagesleaks its anonymous mapping. Only address space is lost, because the pages were never touched.🤖 Generated with Claude Code