Repository navigation
perf: remove host-built inputs from the CUDA decode step - #3695
Merged
Merged
Conversation
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
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
5 of 7 tasks
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
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
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
Member
Author
Security and performance reviewNo CRITICAL or HIGH findings. Checked: staging bounds and size arithmetic, view lifetime after Fixed in b8dcb1b
Not changed
Verification (GB10)
|
…oc-free-decode-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
marked this pull request as ready for review
December 2, 2026 13:26
This was referenced Dec 3, 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
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
cudaMemcpyAsynccalls 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 fromdecode_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/metricsexposes that count and the padded steps.Path statement
--ctx-sizeruns) and the lookahead pipeline (the default without it) are covered.MLXCEL_PAGED_SLIDINGoff 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 andMLXCEL_PAGED_SLIDING=1. It is not padded: dense and scheduler-owned rows have no slot for a pad row without a model rewrite.step_inputs::enabled_from(env, backend)is false off CUDA whatever the environment says, so the buffers are never constructed, and every consumer callsstage_i32/stage_f32, which are exactlyfrom_slice_*when no step is active on the thread. Unit-tested for every backend;cargo check -p mlxcel --lib --testsat default features passes.MLXCEL_STEP_INPUTS=0andMLXCEL_DECODE_PADDING=0restore the old step on CUDA.What the measurement changed
The issue's 99k
cudaMallocManaged/cudaFreefigures came from the unmerged #3650 branch, which released the allocator cache between steps. Main does not (clear_cache_between_steps,MLXCEL_STEP_CACHE_CLEARand 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 withMLXCEL_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/metricscounters and tests, and the parity and counter runs below are on the final commit.cudaMallocManagedcudaFree/cudaFreeAsynccudaMallocAsynccudaMemcpyAsyncafterMLXCEL_PAGED_SLIDING=1The 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).cudaGraphLaunchper step on Llama is unchanged at 17.2.Deviations from the issue text
V2Context::from_persistentand nomlxcel_step_inputs_uploadfunction:V2Context::buildand 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.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 theactive_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 fp8the 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. WithMLXCEL_STEP_INPUTS=0and 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
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 withoutMLXCEL_PAGED_SLIDING=1.decode_bucket_forunit tests cover 1..=32, 33..=64, the cap and the panic.step_inputsunit 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.mlxcel-serveragainst 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 andMLXCEL_PAGED_SLIDING=14/4.--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.batch::scheduler349 passed; corestep_inputs13,paged_285;scheduler_step_inputs --ignored8/8 on the f16 pool and 8/8 on the FP8 pool (MLXCEL_STEP_INPUTS_FP8=1, test-only);block_reclaim31 including 7 pad-row reclaim tests. Before the merge: corepaged_v294,paged_batch31,engine::86,memory::27,sampling216; Gemma 3scheduler_real_batch_parity2 passed; scoped clippy on both crates, fmt,make verify-*contract checks.MLXCEL_STEP_INPUTS=0on 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 4bitMLXCEL_PAGED_SLIDING=1with 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. Nounevaluated, stale-view or capacity warnings in any server log.serving_compare.pytable was not run, per the 2026-12-02 decision that timing is optional.Changes during review
StepInputScopeholds anRcin the thread-local, so scopes dropped out of order cannot leave a dangling pointer; failed construction releases its pinned slots and events;capacity_forsaturates instead of overflowing; staging rejects negative and oversized shapes and no longer builds a placeholder array per staged input.docs/CONTINUOUS_BATCHING.mdgained a "Persistent step inputs and bucket padding on CUDA" section.Deferred to the B200 follow-up measurement issue
cudaFreeunder 100,cudaMallocAsyncper step at most 8).paramsarray per paged v2 launch, the cascade launch arrays, and the FP8full_f32scale constant when a checkpoint declares a scale other than 1.0.Closes #3667