Skip to content

perf: plan CUDA server memory at startup with per-layer KV slabs - #3680

Merged
inureyes merged 8 commits into
mainfrom
update/issue-3664-cuda-memory-plan
Dec 2, 2026
Merged

inureyes merged 8 commits into
mainfrom
update/issue-3664-cuda-memory-plan

Conversation

@inureyes

@inureyes inureyes commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

A CUDA mlxcel-server now plans its memory at startup, after the weights load and before the scheduler starts.

  • It profiles one prefill to measure the activation peak and reads total and free device memory.
  • It sizes the paged KV pool per layer from the model's KV geometry.
  • It bounds MLX's buffer cache and sets the allocator limit.
  • If --parallel sequences at the per-slot context do not fit, it refuses to serve and names the numbers and the knobs.

--gpu-memory-utilization (env MLXCEL_GPU_MEMORY_UTILIZATION, default 0.90) sets the share of the device the plan sizes against. Part of epic #3671.

Changes

  • Per-layer KV geometry: LanguageModel::paged_layer_geometry() returns a PagedLayerGeometry per 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 their window tokens per sequence outside the pool budget.
  • Per-layer slabs: PagedBlockPool keeps one slab size per layer (set_layer_slab_blocks). A full layer gets ceil(per_slot_ctx / block) * parallel blocks 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-time paged KV planning miss.
  • Budget: 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 and MemAvailable, because the driver leaves out reclaimable page cache. That cache includes the checkpoint just read.
  • Cache bound: unless MLXCEL_CACHE_LIMIT is set, the bound is 1.25 * activation peak kept within 2 to 8 GiB, and the allocator limit is the planned total.
  • Fallbacks: models without geometry, an explicit --kv-cache-budget, the dense backend and MLXCEL_PAGED_SLAB_BLOCKS keep the previous behavior. Pinned values in a test cover this.
  • Logs: the plan logs Paged KV slabs: ... and KV 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: docs/CONTINUOUS_BATCHING.md (Startup memory plan on CUDA) and docs/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 gets v_norm (RMSNormNoScale) and no RoPE, so the cached K and V differ. A shared slab would corrupt attention, so it is not implemented. shared_kv stays 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_applies returns true only for GpuBackendKind::Cuda. A test walks GpuBackendKind::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 flags

Startup memory plan (--gpu-memory-utilization 0.90): weights 30.39 GiB, activation peak 11.21 GiB, cache limit 8.00 GiB, KV need 47.00 GiB, KV budget 51.59 GiB (utilization cap 67.86 GiB, free-memory cap 51.59 GiB), allocator limit 93.25 GiB profile_tokens=2048
Paged KV slabs: 10 full layers x 9011 blocks, 50 dense (outside the pool) layers (fused decode serves a layer only while its rows fit one slab)
KV capacity: 262144 full-attention tokens (32 sequences at 8192 tokens per slot), sliding layers sized for 32 sequences
  • The c=32 512/128 cell completed 128/128 requests, 0 failed (TPOT median 608 ms, 45.0 output tok/s).
  • Peak host-wide used memory (MemTotal - MemAvailable, other tenants included) was 96.9 GiB, at or below 0.90 * total + 2 GiB = 111.5 GiB.
  • The NVRM count was 461 before and after, and no planning-miss warning appeared.

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.

c TPOT median ms, before after paired delta TTFT median ms, before after out tok/s, before after
1 170.6, 159.8 163.8, 159.5 -4.0%, -0.2% 857, 823 837, 817 5.6, 6.0 5.9, 6.0
8 298.3, 283.0 289.1, 285.0 -3.1%, +0.7% 3699, 3626 3779, 3667 23.1, 26.0 25.2, 25.7
32 573.9, 558.6 559.2, 599.9 -2.6%, +7.4% 13968, 13636 14064, 13678 47.1, 48.3 48.1, 44.2

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)

cache bound c=8 TPOT median ms c=32 TPOT median ms
derived 1.25 x peak (14.0 GiB) 289.1, 285.0 559.2, 599.9
4 GiB 285.2, 288.8 557.6, 586.1
8 GiB 281.8, 285.3 545.9, 545.7
16 GiB 287.1, 281.4 565.1, 554.1
32 GiB plan refused (round 1), 287.5 plan refused (round 1), 549.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

  • mlxcel memory_estimate 76, memory_plan 8, model_worker 46, gemma4 314 (41 ignored), cli_input 170.
  • mlxcel-core cache::paged 158, paged_geometry 1, memory:: 27, per_layer_slab 1.
  • Run with --test-threads=1 under the GPU lock.
  • Clippy --features cuda -D warnings on -p mlxcel --lib and -p mlxcel-core --lib --tests is clean, cargo fmt --all --check passes, and scripts/ci/check_env_var_docs.py passes.
  • The geometry test checks the Gemma 4 31B fixture (--parallel 32, 8192 tokens per slot) against the hand calculation within 1%. The None-geometry test pins the previous block budget and slab size.
  • Remote CI was cancelled per the epic's policy; the local scoped gate above is the merge gate.

Deferred to the B200 follow-up measurement issue

  • The B200 acceptance run (nvidia/Gemma-4-31B-IT-NVFP4 --parallel 32 --ctx-size 262144) and its nvidia-smi peak check.
  • The B200 c=32 TPOT target of 138.8 ms and the c=1 within-3% check on B200.
  • Re-running the cache-limit sweep on the B200.
  • The shared K/V slab test is not applicable (see above).

Closes #3664

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.
@inureyes inureyes added type:performance Performance improvements priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific status:review Under review labels Dec 2, 2026
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.
An earlier commit on this branch was taken from a tree that predated #3677 and #3679 and dropped their files and lines; restore them from main so this PR changes only the memory plan.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Dec 2, 2026
@inureyes
inureyes marked this pull request as ready for review December 2, 2026 07:31
@inureyes
inureyes merged commit aa52c2f into main Dec 2, 2026
36 of 37 checks passed
@inureyes
inureyes deleted the update/issue-3664-cuda-memory-plan branch December 2, 2026 07:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific priority:high High priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: Plan CUDA server memory at startup with a per-layer-type KV pool

1 participant