Skip to content

perf: remove host-built inputs from the CUDA decode step - #3695

Merged
inureyes merged 12 commits into
mainfrom
update/issue-3667-alloc-free-decode-step
Dec 2, 2026
Merged

inureyes merged 12 commits into
mainfrom
update/issue-3667-alloc-free-decode-step

Conversation

@inureyes

@inureyes inureyes commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Unit of epic #3671. On CUDA the scheduler's decode step no longer builds its per-step inputs as host arrays: token ids, RoPE offsets, paged page tables and plan arrays, KV write slots and token-bias rows are written to a pinned staging slot and uploaded with at most two cudaMemcpyAsync calls per step into one device buffer whose address is fixed for the scheduler's life (mlxcel_core::step_inputs::StepInputBuffers). Pooled decode steps are padded to bucket sizes from decode_bucket_for, the single source #3668 reuses. The CUDA allocator overlay counts the unified buffers it hands out (mlxcel_core::memory::unified_alloc_count()), and /metrics exposes that count and the padded steps.

Path statement

  • Pooled families (Llama, Qwen): persistent inputs and padding are on by default on CUDA. Both the synchronous step (what a server with an explicit --ctx-size runs) and the lookahead pipeline (the default without it) are covered.
  • Gemma 4 on CUDA decodes from dense per-sequence caches by default (MLXCEL_PAGED_SLIDING off since fix(cuda): default paged sliding-window KV off on CUDA #3676; that default is not changed here, the decision belongs to the end of perf: Capture and replay the whole decode step as bucketed CUDA graphs #3668). Its host arrays (token ids, RoPE offsets, the pooled full-attention layers' page tables) move to the persistent buffer on both the default path and MLXCEL_PAGED_SLIDING=1. It is not padded: dense and scheduler-owned rows have no slot for a pad row without a model rewrite.
  • Metal, ROCm, CPU: unchanged. step_inputs::enabled_from(env, backend) is false off CUDA whatever the environment says, so the buffers are never constructed, and every consumer calls stage_i32 / stage_f32, which are exactly from_slice_* when no step is active on the thread. Unit-tested for every backend; cargo check -p mlxcel --lib --tests at default features passes. MLXCEL_STEP_INPUTS=0 and MLXCEL_DECODE_PADDING=0 restore the old step on CUDA.

What the measurement changed

The issue's 99k cudaMallocManaged / cudaFree figures came from the unmerged #3650 branch, which released the allocator cache between steps. Main does not (clear_cache_between_steps, MLXCEL_STEP_CACHE_CLEAR and the Gemma4 sm100 report do not exist on main and are not added), so its size-keyed buffer cache already absorbs the host arrays: on GB10 main was under the issue's nsys thresholds before this PR. The arrays were still requested every step, which is what the counter shows and what #3668 cannot replay, so the counter counts requests, not driver calls.

GB10, four concurrent requests (about 430 prompt tokens, greedy), 10 s steady window, --parallel 8 --ctx-size 65536. "Requests" is unified buffer requests per decode step from /metrics (before = same binary with MLXCEL_STEP_INPUTS=0); nsys counts are per window, with steps in the window in brackets. The nsys rows were taken on a19f081 plus the pad-row eviction change; the last commit adds only the two /metrics counters and tests, and the parity and counter runs below are on the final commit.

Config Requests per step cudaMallocManaged cudaFree / cudaFreeAsync cudaMallocAsync cudaMemcpyAsync after
Llama 3.2 1B 4bit, pooled 163 -> 0 18, 16 -> 0 0 / 6, 7 -> 0 / 0 0 -> 1 1990 (994 steps)
Gemma 4 12B 4bit, MLXCEL_PAGED_SLIDING=1 483 -> 0 0 -> 0 0 -> 0 204, 176 -> 176 (about 126 steps) 254
Gemma 4 12B 4bit, default dense 99 -> 0 0 -> 0 0 -> 0 322, 322 -> 322, 322 (about 118 steps) 117

The remaining cudaMallocAsync (1.4 to 2.7 per step on Gemma, under the issue's 8) is identical with and without this change, so it does not come from host arrays; it was not attributed further (the release binary is stripped and an unstripped run showed 2 calls in its window). cudaGraphLaunch per step on Llama is unchanged at 17.2.

Deviations from the issue text

  • No V2Context::from_persistent and no mlxcel_step_inputs_upload function: V2Context::build and the other consumers call the staging helpers, and the upload is a lazy MLX node the staged views depend on, so ordering with the encoder comes from the graph and a failed copy surfaces as the step's eval error with the CUDA error string.
  • The buffers are created at the scheduler's first decode step (the server's startup warmup), because the slab sizes that size them are installed after construction.
  • A pad row is a real pool-backed sequence rewound to one token before each padded forward, not an empty CSR range: a zero-page request breaks the paged plan's chunk-per-request assumption and gives NaN rows.
  • The fused sampler's temperature, top-p, top-k and seed are scalars passed by value, so only the token-bias rows moved. The cascade launch (off by default), the per-row sampler chain, prefill and speculative or MTP verify steps keep host arrays. Sampled token readback needed no change: the allocator moves a token buffer to unified memory once and then reuses it, so moves are 0 in every steady window measured (the Gemma 4 lookahead test arm shows about 1030 moves during prefill and warmup, 0 in its measured window).
  • Fallbacks. A batch the buffers cannot hold (inputs past the capacity, which also covers a row with more blocks than the plan sized for): the rest of that step builds host arrays, logged once. KV pool growth during decode: the grown layer leaves the fused read as before (multi-slab decline, already logged once per outcome) and its gather indices still stage or fall back by size. Speculative and MTP verify steps (L > 1) never open a step scope, so they keep today's path; every caller of the padded entry points is a single-token decode tick. No pool slot or KV block for a pad row: the step runs unpadded, logged once. Pad rows give their slots and blocks back before a request is refused or anything is evicted: every block reclaim (decode reservation, prefill admission, chunked-prefill reservation) first calls PagedBlockReclaimer::release_spare_blocks, which closes the pad rows, and a pad row is not opened when no block is free beyond the real rows' need plus the admission headroom. Known minor gaps: the batched-prefill window (paged_prefill_room) and the prompt-lookup verify fit checks count free blocks without reclaiming, so pad rows can shrink a batched prefill or turn a verify step into a plain decode; surplus pad rows after a bucket shrink stay open until the batch empties or a reclaim runs, and they count in the active_count() gauge.

FP8 KV pool (#3666, merged into this branch)

The staging and padding do not branch on pool dtype; FP8 per-layer scales are scalars, not per-step host arrays. With --cache-type-k fp8 --cache-type-v fp8 the persistent inputs and padding work unchanged (server smoke below). One observation that is not introduced here: with an FP8 pool, a request's greedy tokens depend on the batch shape late in a long generation. With MLXCEL_STEP_INPUTS=0 and no padding, request 0 alone vs in a batch of 3 or 4 diverges near token 47 on Llama 3.2 1B, while the f16 pool does not; consequently padded vs unpadded FP8 runs diverge between about token 100 and 150 at 160 tokens (each arm is deterministic, and 64-token runs match). The FP8 arm of the padding test therefore compares the first 32 tokens; the f16 arm compares every token. This looks like an FP8 decode-kernel property from #3666 and is left for a follow-up.

Test plan

  • Server test scheduler_step_inputs (Llama 3.2 1B 4bit, 4 rows, 50 steady steps): +0 unified requests on the gather, fused v2 and lookahead arms. Checked failing first on main plus the counter (stage A commit): +12150, +8630, +12132 (all three arms ran the gather path at that commit; the fused arm got its slab size in stage B). Gemma 4 12B own-path arms: +0 with and without MLXCEL_PAGED_SLIDING=1.
  • Padding: three rows in the 4-row bucket give the same 114 greedy tokens per request as with padding off (gather, fused, lookahead arms). decode_bucket_for unit tests cover 1..=32, 33..=64, the cap and the panic.
  • step_inputs unit tests (13): values, fixed device address, an in-flight step surviving the next step's staging, stale evaluation error, overflow fallback, scopes dropped out of order, negative and oversized staging shapes, the gates.
  • Greedy parity on mlxcel-server against the main 11f1c0a binary, 64 tokens, two repetitions each, compared repetition for repetition (main's own two repetitions differ in one row at c=5 and on Gemma, so each is matched to its counterpart): Llama c=4 4/4, c=3 (padded) 3/3, c=5 (padded to 8) 5/5; Gemma 4 12B default 4/4 and MLXCEL_PAGED_SLIDING=1 4/4.
  • Server counters (Llama 3.2 1B): 0 unified requests over 566 steps at c=4, 673 at c=3 (672 padded), 374 at c=5 (all padded), 648 at temperature 0.7, and 790 pipelined steps without --ctx-size. Gemma 4 12B without --ctx-size: 0 over 74 steps (default) and 76 (MLXCEL_PAGED_SLIDING=1); it stays on the synchronous step there, so the Gemma pipeline is covered by the scheduler test only.
  • After merging main (FP8 pool): batch::scheduler 349 passed; core step_inputs 13, paged_ 285; scheduler_step_inputs --ignored 8/8 on the f16 pool and 8/8 on the FP8 pool (MLXCEL_STEP_INPUTS_FP8=1, test-only); block_reclaim 31 including 7 pad-row reclaim tests. Before the merge: core paged_v2 94, paged_batch 31, engine:: 86, memory:: 27, sampling 216; Gemma 3 scheduler_real_batch_parity 2 passed; scoped clippy on both crates, fmt, make verify-* contract checks.
  • Server smoke after merging main, release binary, 4 concurrent greedy requests, 64 tokens, two prompt lengths, default vs MLXCEL_STEP_INPUTS=0 on the same binary: token-identical 4/4 on Llama 3.2 1B 4bit (f16 pool), Llama 3.2 1B 4bit FP8 pool, Gemma 4 12B 4bit default, Gemma 4 12B 4bit MLXCEL_PAGED_SLIDING=1 with FP8, and Qwen3 1.7B 4bit. Unified buffer requests over each whole run (prefill included), default vs kill switch: 161 vs 18458, 226 vs 18462, 1338 vs 13810, 1728 vs 61093, 351 vs 31544. No unevaluated, stale-view or capacity warnings in any server log.
  • Timing, indicative only (shared host, load 2.4 to 8.8, n=2): Llama 3.2 1B decode steps per second at c=8, main 93, 90 against this branch 90, 90 (paired -3.2%, -0.6%); padding on against off on this branch, c=3 119, 115 against 109, 112, c=5 78, 83 against 77, 81. The c=1/8/32 serving_compare.py table was not run, per the 2026-12-02 decision that timing is optional.

Changes during review

  • Pad rows now release their KV blocks on every reclaim path (prefill admission and chunked-prefill reservation were missing), not only on the decode reservation and slot paths.
  • StepInputScope holds an Rc in the thread-local, so scopes dropped out of order cannot leave a dangling pointer; failed construction releases its pinned slots and events; capacity_for saturates instead of overflowing; staging rejects negative and oversized shapes and no longer builds a placeholder array per staged input.
  • A pad row is not opened when the pool has no block to spare, instead of opening and closing it every tick under pressure.
  • docs/CONTINUOUS_BATCHING.md gained a "Persistent step inputs and bucket padding on CUDA" section.

Deferred to the B200 follow-up measurement issue

  • nsys over a 25 s c=8 512/128 window on Gemma 4 31B NVFP4 (managed plus cudaFree under 100, cudaMallocAsync per step at most 8).
  • The c=1, 8, 32 serving table with the 3% regression bound, and any 31B number (the 31B was not loaded here).
  • The cost of padding between buckets on a B200, including 5 to 7 rows padding to 8 past the 7-row amortizing kernel.
  • Remaining host arrays left for perf: Capture and replay the whole decode step as bucketed CUDA graphs #3668: the one-element params array per paged v2 launch, the cascade launch arrays, and the FP8 full_f32 scale constant when a checkpoint declares a scale other than 1.0.

Closes #3667

Stage A of #3667. The CUDA allocator overlay now counts requests for a unified (host-visible) buffer above the scalar pool's 8-byte block, device buffers moved to unified memory for a host read, and the driver allocations behind both. `mlxcel_core::memory::unified_alloc_count()` and `unified_alloc_stats()` expose them (0 / `None` off CUDA).

The count is of requests, not of `cudaMallocManaged` calls, because the allocator's size-keyed buffer cache serves most of them: on GB10 at main 11f1c0a, nsys over a 10 s steady window of four concurrent requests shows 18 `cudaMallocManaged` on Llama 3.2 1B and none on Gemma 4 12B, while every step still builds its inputs from host slices. The driver-call count depends on what the cache holds; the request count does not.

`mlxcel_core::step_inputs::enabled_from(env, backend)` is the gate for the persistent step-input buffers that stage B adds: CUDA only, `MLXCEL_STEP_INPUTS=0` turns them off there, and no value turns them on elsewhere. Unit test covers every backend.

`scheduler_step_inputs_tests` drives four requests through the real scheduler on Llama 3.2 1B 4bit and asserts the count does not move across 50 steady 4-row steps. It fails on this commit as intended: +12150 requests (243 per step) on the long-prompt arms and +8630 on the short-prompt arm. Stage B makes it pass.

Refs #3667
Stage B of #3667. On CUDA a decode step no longer builds its per-step inputs as host arrays. `mlxcel_core::step_inputs::StepInputBuffers` owns one device buffer whose address is fixed for its life plus two pinned staging slots. A step writes its values into the current slot and gets lazy typed views of the device buffer back; the views depend on one upload node, so evaluating the step commits MLX's pending graph and issues at most two `cudaMemcpyAsync` calls on MLX's stream (one per used region: fixed-size arrays from offset 0, variable-length page tables from the end). A failed copy throws from the step's eval with the CUDA error string, like a failed kernel launch.

The staging slot alternates per step because the lookahead pipeline builds step N+1 while step N's copy may still be queued; a slot is reused only after the event recorded behind its copy completes. A view or upload evaluated after the next step began throws instead of reading that step's values.

Consumers go through `step_inputs::stage_i32` / `stage_i32_tail` / `stage_f32`, which are exactly `from_slice_*` when no step is active on the thread, so Metal, ROCm, CPU, prefill, the CLI and the speculative verify steps keep their code path: the scheduler's token ids, `rope_offsets_array` (batched RoPE), the paged v2 page table and plan arrays (`V2Context::build`, `launch_with_lse`), the v1 fused arrays and the gather indices in `paged.rs`, the KV write pairs of `write_decode_rows`, and the token-bias rows of the fused sampler (the fused sampler's other parameters are scalars passed by value, so there was nothing else to move). The cascade launch (off by default) and the per-row sampler chain keep host arrays.

The scheduler creates the buffers at its first decode step, sized from the pool's per-layer slab blocks, only when `step_inputs::enabled()` holds (CUDA, `MLXCEL_STEP_INPUTS` not 0). A step whose inputs do not fit builds the rest as host arrays and logs once.

Validation on GB10: `scheduler_step_inputs_tests` (Llama 3.2 1B 4bit, four rows, 50 steady steps) now reports +0 unified requests and +0 moves on the gather, fused v2 and lookahead arms, from +12150 at stage A; one upload per step, nothing rejected, nothing left unevaluated, device address unchanged. `step_inputs` unit tests (10) cover values and shapes, the fixed address, an in-flight step surviving the next step's staging, the stale-evaluation error, overflow fallback, a second upload after an early evaluation, and the gate.

Refs #3667
@inureyes inureyes added status:review Under review 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 labels Dec 2, 2026
Stage C of #3667. `decode_bucket_for(rows, max_batch)` in `scheduler/step_rows.rs` is the one list of decode batch sizes (1, 2, 4, 8, 16, 24, 32, then every 16, capped at the batch limit, which is therefore always the largest bucket); #3668 reuses it for its graphs. It panics when a step exceeds the limit.

On the pooled CUDA path a decode step now runs at its bucket size. The scheduler opens pad rows as ordinary pool-backed sequences and passes them to `Engine::step_padded` / `Engine::submit_padded`, which run the forward over the real rows followed by the pad rows and return the real rows' logits, so sampling, finishing, the lookahead feedback and every offset see the batch they always saw. A pad row takes token id 0 and is rewound to one token before each padded forward, so its KV write lands in the second slot of its own block every step, where no request reads it.

This differs from the issue's sketch (an empty CSR range per pad row) on purpose: a zero-page request breaks the paged decode plan's no-merge assumption that chunk r is request r, and an empty attention range gives NaN rows; a row that attends to its own two tokens needs no special case in the plan, the kernels or the write path.

Padding applies only when the persistent step-input buffers are on, `MLXCEL_DECODE_PADDING` is not 0, the step has at least two rows and every row is pool-backed with plain per-layer caches. Dense and model-owned rows (Gemma 4 on CUDA by default, and its scheduler-owned paged sliding state) are not padded: their per-sequence caches have no slot for a pad row without a model rewrite, and #3668 targets the pooled path. A pool with no slot or block to spare runs the step unpadded and logs once. Pad rows are closed when the batch empties.

Validation on GB10 (Llama 3.2 1B 4bit): three concurrent requests in the 4-row bucket produce the same 114 greedy tokens each as the same scheduler with padding off, on the gather, fused v2 and lookahead arms; the 4-row allocation test still reports +0 unified requests. `decode_bucket_for` unit tests cover 1..=32, 33..=64, the cap and the panic. Docs: `MLXCEL_STEP_INPUTS` and `MLXCEL_DECODE_PADDING` in docs/environment-variables.md.

Refs #3667
Follow-up to stage C of #3667, from the scoped scheduler suite and the server runs.

Pad rows no longer change what a request sees. They take a pool slot only while it is free: `allocate_sequence_state` closes the pad rows and retries when the pool refuses a request, and the decode block reservation releases them before it evicts a prefix or preempts. The pool capacity is `max_batch + max_queue_depth` again (the extra slots broke `vlm_fallback_abort_tests`, which counts on that bound).

`/metrics` gains `mlxcel_cuda_unified_buffer_requests_total` (the allocator's unified buffer requests plus moves) and `mlxcel_batch_decode_padded_steps_total`, so a server shows without a profiler that its steady decode builds no host arrays and whether a batch is padded. The forward call-site table in `prefill_span_coverage_tests` names `step_padded` and `submit_padded`. The allocation test gets two arms for a checkpoint with its own decode path (`MLXCEL_STEP_INPUTS_MODEL`, allowlisted as test-only).

Validation on GB10: `batch::scheduler` 340 passed; `scheduler_step_inputs` 8 passed on Llama 3.2 1B and the two own-path arms pass on Gemma 4 12B with and without `MLXCEL_PAGED_SLIDING=1` (+0 requests, +0 moves); core `step_inputs` 11, `paged_v2` 94, `paged_batch` 31, `engine::` 86, `memory::` 27, `sampling` 216 passed; Gemma 3 `scheduler_real_batch_parity` 2 passed under `MLXCEL_SDPA_DETERMINISTIC=1`; scoped clippy on both crates, `cargo check -p mlxcel --lib --tests` at default features and the `make verify-*` contract checks pass.

Refs #3667
`allocate_sequence_state` closes the decode pad rows of #3667 and retries when the pool refuses a request. The new case in `vlm_fallback_abort_tests` holds one of two slots with a pad row and checks that two requests still fit, the pad row is closed, and a third request is refused as it was without padding.

Refs #3667
Decode pad rows each hold one KV block per layer. They were released before decode reclaim and on slot shortage, but prefill admission (admit_with_watermark) and the chunked prefill reservation (reserve_chunk_blocks) ran the shared reclaim loop while pad rows still held blocks, so they evicted cold prompt-cache prefixes, preempted running requests, deferred the request, or failed a chunk for blocks no request needed.

The PagedBlockReclaimer trait gains release_spare_blocks (default no-op), which reclaim_blocks calls once as step 0 when the pool has no room, before any eviction or preemption. BatchScheduler implements it by closing the decode pad rows, the Unreserved view forwards it, and ReclaimOutcome records whether it fired for the reclaim logs. The explicit release in reserve_decode_step_blocks is now covered by the choke point and removed. open_decode_pad_row also keeps the admission watermark headroom free, so pad rows do not reopen right after an admission released them.

Validated on GB10 with the test-fast CUDA lib binary under gpu-lock: block_reclaim (31 passed, 7 new pad-row cases covering decode, admission and chunk reservation with spare blocks covering the need and falling short of it), batch::scheduler::step_rows (4), admission_watermark (3), a_request_takes_back_the_slot_of_a_decode_pad_row (1), the new block_reclaim_releases_the_decode_pad_rows_first scheduler test (1), and scheduler_step_inputs_tests --ignored on llama-3.2-1b-instruct-4bit (8). fmt, scoped CUDA clippy, default-feature cargo check and the verify-* contract targets pass.

Refs #3667
Three review findings on the persistent step-input buffers.

The active step's buffers were a raw pointer restored by each scope on drop, so two scopes dropped out of nesting order could restore a pointer to buffers already freed and the next stage_i32 would read through it in safe code. The thread-local now owns an Rc of the active buffers and each scope owns the one it restores, so any drop order leaves live buffers behind.

A failed second pinned staging allocation or event creation threw from the State constructor after the first slot was acquired; the destructor does not run for a partly constructed object, so up to one pinned slot and one event leaked on exactly the path where the scheduler falls back. The constructor now releases what it acquired before rethrowing.

capacity_for multiplied max_batch before saturating, which overflows for huge batch limits; the multiplication now saturates.

Validated on GB10: core step_inputs 12 passed (new out-of-order scope test), core paged_ 275 passed, batch::scheduler 349 passed, scheduler_step_inputs --ignored on Llama 3.2 1B 4bit 8 passed; fmt, scoped CUDA clippy on mlxcel-core, default-feature cargo check and the verify-* contract checks pass.

Refs #3667
@inureyes

inureyes commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make the CUDA decode step read every per-step input from a persistent fixed-address device buffer, pad pooled steps to decode_bucket_for buckets, and count unified allocations, with Metal, ROCm and CPU unchanged.

Findings Addressed

  • Decode pad rows kept their KV blocks while prefill admission and the chunked-prefill reservation evicted prefixes, preempted running requests or failed a chunk. Every reclaim now releases pad rows first through PagedBlockReclaimer::release_spare_blocks in reclaim_blocks, and pad rows no longer open inside the admission watermark headroom (46fa913) (HIGH)
  • StepInputScope restored a raw pointer, so scopes dropped out of order could leave a dangling active buffer reachable from safe code. The thread-local now owns an Rc (8f130e6) (MEDIUM)
  • The State constructor leaked a pinned slot and an event when the second allocation failed (8f130e6) (MEDIUM)
  • capacity_for overflowed before saturating (8f130e6) (LOW)

Remaining Items

Verification

  • All stated requirements implemented (B200-only items deferred as the body states)
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: core step_inputs 12, core paged_ 275, batch::scheduler 349, block_reclaim 31, and scheduler_step_inputs --ignored 8 on Llama 3.2 1B 4bit, all on GB10

Security and performance review follow-up for #3667.

`step_inputs::stage` multiplied the shape's dimensions as unsigned values before comparing the product with the staged byte count, so a shape with negative dimensions (for example `[-1, -4]` for four int32 values) could wrap back to the byte count and produce an array with a negative shape over the device buffer. It also rounded the reservation up before comparing it with the free space, which would wrap for a size near the address-space limit. Negative dimensions are now an error, a shape with more elements than the buffer has bytes is a plain rejection, and the free-space check runs before rounding. Every caller is internal and passes slice lengths, so this is hardening, not a reachable bug.

The bridge built a scalar placeholder array (a small-pool allocation) for every staged array, about 160 per decode step; `stage` now returns `std::optional<array>`.

Under KV pool pressure a padded step opened a pad row, found no block budget for it and closed it again, every tick. The real rows' need and the admission headroom do not depend on the pad row, so a pool with no block beyond them now skips the open.

Validation on GB10: core `step_inputs` 13 (one new shape-guard test), `scheduler_step_inputs --ignored` 8 on Llama 3.2 1B 4bit, `batch::scheduler` 349, scoped clippy on both crates and fmt.

Refs #3667
@inureyes

inureyes commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL or HIGH findings. Checked: staging bounds and size arithmetic, view lifetime after begin_step, slot and event reuse under the lookahead pipeline, the thread-local scope, cleanup on failed construction, pad rows holding slots or blocks (46fa913 verified: every reclaim_blocks caller releases pad rows first, and allocate_sequence_state retries after closing them), the new /metrics counters, and per-step host waits.

Fixed in b8dcb1b

  • stage multiplied the dimensions as unsigned values, so negative dimensions could wrap back to the byte count ([-1, -4] for four int32 values), and it rounded the reservation before the free-space check. Negative dimensions now throw, an oversized shape is a rejection, and the check runs before rounding. Every caller passes slice lengths, so this was not reachable (LOW)
  • The bridge built a placeholder scalar array (a small-pool allocation) for each of the ~160 arrays staged per step; stage now returns std::optional<array> (LOW)
  • Under KV pool pressure a padded step opened a pad row, found no budget and closed it again on every tick. It now skips the open when no block is free beyond the real rows' need and the admission headroom (MEDIUM)

Not changed

  • A staged view evaluated after begin_step throws, which is safer than reading the next step's values. A family whose KV write is not an ancestor of the step's logits would therefore fail every CUDA decode step. unevaluated is 0 on every arm measured and logs a warning otherwise, but no test covers every family (MEDIUM, latent)
  • Pad-row blocks are not counted by paged_prefill_room (batched prefill window) or by the prompt-lookup verify fit check, neither of which reclaims, so pad rows can narrow a prefill batch or turn a verify into a plain decode. The single-sequence admission gate reclaims and is unaffected (LOW)
  • The buffers are sized after the perf: plan CUDA server memory at startup with per-layer KV slabs #3680 startup memory plan: up to 64 MiB of device memory plus 2 x 64 MiB pinned host memory that the plan does not count. On GB10 test configurations the buffer is a few hundred KiB (LOW)
  • mlxcel_cuda_unified_buffer_requests_total is a process-wide allocation count and leaks nothing request-specific.

Verification (GB10)

  • Core step_inputs 13 passed (one new test for the shape guard), scheduler_step_inputs --ignored 8 passed on Llama 3.2 1B 4bit, batch::scheduler 349 passed. Scoped clippy on both crates, fmt, a default-feature cargo check -p mlxcel-core and the make verify-* checks pass.
  • Fused and lookahead arms: slot_waits 0 and one upload per step over 50 steps, so the staging slot adds no host wait per step.

…input tests

After merging main (#3693, FP8 E4M3 paged KV pool) nothing in the step-input staging branches on the pool dtype, so no code change was needed there: the FP8 scales are per-layer scalars, not per-step host arrays. The scheduler_step_inputs harness now accepts MLXCEL_STEP_INPUTS_FP8=1, which stores the pool as FP8 E4M3; the allocation-flat and padded-versus-unpadded tests pass in both arms.

The padded-versus-unpadded comparison under FP8 checks the first 32 tokens only. The fused FP8 kernel is not batch-shape invariant on its own: with MLXCEL_STEP_INPUTS=0 and no padding, one request alone and the same request in a batch of three diverge near token 47 (f16 does not). That drift predates this branch.

docs/CONTINUOUS_BATCHING.md gains a short section on the persistent step inputs and bucket padding. MLXCEL_STEP_INPUTS_FP8 is allowlisted in the env-var docs check as test-only.

Validation:
- core step_inputs 13 passed, paged_ 285 passed, mlxcel batch::scheduler 349 passed
- scheduler_step_inputs --ignored: 8 passed on llama-3.2-1b-instruct-4bit, f16 and FP8 pools
- scoped clippy (cuda) on mlxcel-core and mlxcel, default-feature cargo check, fmt and the verify-* list clean

Refs #3667
@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 13:26
@inureyes
inureyes merged commit 22ee939 into main Dec 2, 2026
1 check passed
@inureyes
inureyes deleted the update/issue-3667-alloc-free-decode-step branch December 2, 2026 13:26
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: Remove device and managed allocations from the CUDA decode step

1 participant