Repository navigation
perf: plan CUDA server memory at startup with per-layer KV slabs - #3680
Merged
Merged
Conversation
Add per-layer paged KV geometry (LanguageModel::paged_layer_geometry, implemented for Gemma 4), per-layer slab sizes in the paged pool, a geometry-aware block budget, and a CUDA-only startup memory plan in the model worker: profile one prefill, read total and free device memory (MemAvailable on unified-memory devices), size the KV budget from --gpu-memory-utilization, refuse to serve when the slabs do not fit, and bound the MLX buffer cache and allocator limit.
The buffer cache holds freed activations that the next forward reuses, so the plan reserved the same bytes twice when it added the activation peak and the derived cache limit. It now reserves the larger of the two. The profile peak also excludes the KV and logits the profile forward leaves alive, which the plan already counts per layer.
On Gemma 4 31B NVFP4 on GB10 (--parallel 32 --ctx-size 32768, 2 interleaved rounds) a fixed 8 GiB cache limit had the best TPOT at c=8 and c=32 in both rounds. The uncapped 1.25 x activation peak (14 GiB there) came within 3% at c=8 but trailed by 6% at c=32, so the issue's rule takes the best measured bound.
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
A CUDA
mlxcel-servernow plans its memory at startup, after the weights load and before the scheduler starts.--parallelsequences at the per-slot context do not fit, it refuses to serve and names the numbers and the knobs.--gpu-memory-utilization(envMLXCEL_GPU_MEMORY_UTILIZATION, default 0.90) sets the share of the device the plan sizes against. Part of epic #3671.Changes
LanguageModel::paged_layer_geometry()returns aPagedLayerGeometryper layer (full, sliding with window, or no storage; KV heads; head dim; in the pool or not). Gemma 4 text, VL and unified implement it. Since fix(cuda): default paged sliding-window KV off on CUDA #3676 the Gemma 4 sliding layers use dense ring caches on CUDA, so they are reported as outside the pool, and the plan reserves theirwindowtokens per sequence outside the pool budget.PagedBlockPoolkeeps one slab size per layer (set_layer_slab_blocks). A full layer getsceil(per_slot_ctx / block) * parallelblocks and a pooled sliding layer(ceil(window / block) + 2) * parallel, both plus the rows the prompt cache may pin. A layer that outgrows its planned slab logs a one-timepaged KV planning miss.utilization * total - (weights + max(activation peak, cache limit) + v2 workspace), further bounded by free memory with the same margin. On a unified-memory CUDA device (GB10, Thor, Orin) the free figure is the larger of the driver value andMemAvailable, because the driver leaves out reclaimable page cache. That cache includes the checkpoint just read.MLXCEL_CACHE_LIMITis set, the bound is1.25 * activation peakkept within 2 to 8 GiB, and the allocator limit is the planned total.--kv-cache-budget, the dense backend andMLXCEL_PAGED_SLAB_BLOCKSkeep the previous behavior. Pinned values in a test cover this.Paged KV slabs: ...andKV capacity: N full-attention tokens (M sequences at X tokens per slot), sliding layers sized for B sequences. The KV capacity is net of prompt-cache rows.docs/CONTINUOUS_BATCHING.md(Startup memory plan on CUDA) anddocs/environment-variables.md.Two corrections came from the GB10 runs. The first version added the activation peak and the cache limit, which counts freed activations twice: the cache holds what the next forward reuses. With that version the 262144 run refused to start (47.00 GiB KV need, 34.29 GiB available). The profile peak also now excludes the profile's own KV and logits, which the plan already counts per layer.
K == V shared slab: not applicable
The issue proposed one slab for K==V layers. In Gemma 4 only the raw projection is shared. K then gets
k_norm(weighted RMSNorm) and partial RoPE (0.25 on full layers), while V getsv_norm(RMSNormNoScale) and no RoPE, so the cached K and V differ. A shared slab would corrupt attention, so it is not implemented.shared_kvstays in the geometry type for byte accounting only, and no model sets it. This also affects the "write once for K==V" note in #3665.Metal and ROCm unchanged
startup_memory_plan_appliesreturns true only forGpuBackendKind::Cuda. A test walksGpuBackendKind::ALL, and the worker checks the gate before any plan code runs. The CLI is untouched.Validation on GB10 (sm_121, 128 GB unified)
The host was shared with other sessions' cargo builds and tests throughout, with load average 15 to 25 and available memory between 74 and 111 GiB per arm. The timing numbers below are indicative only. Deltas inside the round-to-round spread are not claimed in either direction, and the merge gate is correctness plus the 262144 acceptance run.
Acceptance:
--parallel 32 --ctx-size 262144,models/gemma-4-31b-it-nvfp4, default flags0.90 * total + 2 GiB= 111.5 GiB.Before and after:
--parallel 32 --ctx-size 32768, 2 interleaved rounds (n=2)The before arm is main
927e71510. Each cell lists round 1, round 2. The bench sends random ~512-token prompts with 128 output tokens and ignore_eos over streaming/v1/completions. It uses 16 prompts at c=1 and 4c prompts otherwise, after one warmup.The paired deltas change sign between rounds at c=8 and c=32. c=1 is not slower in either round. The after arm here used the uncapped 14 GiB cache bound. The final binary uses 8 GiB, which is the best-measured bound below.
Cache-limit sweep (branch binary, n=2)
Under the issue's rule (keep the derived formula only within 3% of the best TPOT), the derived 14 GiB was within 1.2% at c=8 but 6.2% behind at c=32. 8 GiB was best at both concurrencies in both rounds, so the derived value is capped at 8 GiB. The round-1 32 GiB refusal is the plan working as intended: lower free memory that round left 27.79 GiB for a 29.50 GiB KV need. With n=2 on a loaded host this choice should be re-swept on the B200.
Tests
memory_estimate76,memory_plan8,model_worker46,gemma4314 (41 ignored),cli_input170.cache::paged158,paged_geometry1,memory::27,per_layer_slab1.--test-threads=1under the GPU lock.--features cuda -D warningson-p mlxcel --liband-p mlxcel-core --lib --testsis clean,cargo fmt --all --checkpasses, andscripts/ci/check_env_var_docs.pypasses.--parallel 32, 8192 tokens per slot) against the hand calculation within 1%. The None-geometry test pins the previous block budget and slab size.Deferred to the B200 follow-up measurement issue
nvidia/Gemma-4-31B-IT-NVFP4 --parallel 32 --ctx-size 262144) and itsnvidia-smipeak check.Closes #3664