Repository navigation
[Frontend][Core] Add release_kv_cache_memory() API - #44890
Conversation
Signed-off-by: Dakai An <dakaian108@gmail.com>
|
This pull request has merge conflicts that must be resolved before it can be |
|
Hi @andakai — this is closely related to #46438 ( The overlap:
The difference is scope: Would it make sense to build |
Sure. I did the allocator-level logic and the higher layers all in a single pr now. I checked we share the same logic betweeen |
|
Sounds good — I'll ping you once #46438 is merged so you can rebase on top of it. Happy to help review the integration on your side too. |
Add a discard() method to CuMemAllocator that releases GPU physical memory for the specified tags without backing up to CPU first. Unlike sleep(), which operates on all allocations (offloading some and discarding the rest), discard() only touches allocations matching the given tags and leaves everything else mapped and usable. This is needed for multi-model and RL weight-sync scenarios where stale data (e.g. a previous model's KV cache) should be freed to make room for new allocations while the current weights remain on GPU. Reuses the existing is_asleep flag to prevent sleep() from double- unmapping already-discarded handles. wake_up() already clears the flag when remapping. Signed-off-by: AlanFokCo <alanfok2868@gmail.com>
sleep() without arguments defaults to offload_tags=("default",),
but test_discard_tags uses custom tags "weights" and "kv_cache".
Without explicit offload_tags, weights memory was unmapped without
CPU backup, causing wake_up to remap with zeroed physical pages.
Signed-off-by: AlanFokCo <alanfok2868@gmail.com>
Co-authored-by: AlanFokCo <alanfok2868@gmail.com> Signed-off-by: Dakai An <dakaian108@gmail.com>
# Conflicts: # vllm/device_allocator/__init__.py # vllm/device_allocator/cumem.py # vllm/v1/worker/gpu_worker.py
# Conflicts: # tests/basic_correctness/test_mem.py # vllm/device_allocator/__init__.py # vllm/device_allocator/cumem.py # vllm/device_allocator/xpumem.py
|
Documentation preview: https://vllm--44890.org.readthedocs.build/en/44890/ |
|
/ci run |
|
✅ Triggered Buildkite CI #89582 for commit |
|
/ci run |
|
✅ Triggered Buildkite CI #89603 for commit |
|
Heads up @andakai — the three new How I isolated it. I noticed this on my own PR #54527, which is a multimodal-only change and touches nothing in this area. Mergify updated its branch, and the same PR flipped across that update:
The only delta between those two heads is the merge of Where it fails — all three params, same line, and not the new API: The rejected-release path you assert at line 136 works correctly — The release itself also works. Each of the three subprocesses logs: and Why the fraction can't be met at block size 64. XPU picks a 64-token block: The KV cache is floored to a whole number of blocks, so the allocation is up to one block below
One block here is 7.0 MiB against a 2.56 MiB tolerance, so the assertion cannot pass for this model at block size 64 no matter how cleanly the KV cache is released. It should be deterministic rather than flaky, which matches 3/3 params failing. Suggested fix (happy to send it as a PR if you'd prefer — just say the word): compare against what was actually allocated rather than what was requested, e.g. capture the allocator's Worth noting this pipeline only runs on PRs carrying the |
|
Thanks for catching this! I’ve checked and you’re right. the test will compare against the requested budget, but block rounding leaves only 252 MiB allocated. I didn't consider this situation before. I think you can go ahead with the test fix in your pr. |
Root cause: upstream vllm#44890 added a new abstract method release_kv_cache_memory to EngineClient; MultiModelEngineClient never implemented it, so instantiation raised TypeError. Upstream: vllm-project/vllm#44890 Fix: delegate to the wrapped AsyncLLM instance, mirroring the existing sleep/wake_up passthrough pattern. Signed-off-by: Paweł Olejniczak <pawelx.olejniczak@intel.com>
Root cause: upstream vllm#44890 (same PR as the MultiModelEngineClient abstract-method break) turned Executor.is_sleeping into a read-only property computed from sleeping_tags. gaudi_reconfigure_engine's _reset_executor_sleep_state still assigned model_executor.is_sleeping directly, raising AttributeError: property 'is_sleeping' of 'UniProcExecutor' object has no setter during online model swap. Upstream: vllm-project/vllm#44890 Fix: feature-detect whether is_sleeping is a class-level property before assigning it; clearing sleeping_tags already makes the property read False on the new executor. Signed-off-by: Paweł Olejniczak <pawelx.olejniczak@intel.com>
…d skip_padding kwarg, drop stale manager.touch() (+3 more) (#1806) This PR consolidates 5 hourly-CI fixes against vllm@`9a70c233cd5d3ef3b14d79c582a6f9ddfa03cf80`. ## Bug 1: forward skip_padding kwarg through HPU MoE router factory override - **State machine id**: create_fused_moe_router_unexpected_kwarg - **Commit**: 65cc65e ### Root cause upstream vllm#56079 added a `skip_padding: bool = False` kwarg to create_fused_moe_router()/GroupedTopKRouter to invalidate sequence-parallel padding rows in grouped MoE routing. The vllm-gaudi override mirrors this factory's signature and did not accept the new kwarg, so every call site now raises: TypeError: create_fused_moe_router() got an unexpected keyword argument 'skip_padding' ### Culprit Regression introduced by [PR #56079](vllm-project/vllm#56079). ### Fix accept skip_padding on the override (signature parity) and forward it to GroupedTopKRouter; the guard it enables only fires under VLLM_MOE_SKIP_PADDING + DeepEP-v2-kernel forward context, which HPU never exercises, so this is a no-op on HPU beyond restoring the call signature. ## Bug 2: drop stale manager.touch() assertions in offloading connector test - **State machine id**: offloading_connector_touch_assertion - **Commit**: c5c5c55 ### Root cause upstream vllm#51787 ("Track cache recency once per request") removed OffloadingConnectorScheduler._touch and every manager.touch() call site, replacing per-call cache-recency tracking with req_context.set_offload_key_position() tracked once per request. vllm-gaudi's vendored copy of the unit test still asserted the old manager.touch() calls, so it now fails: AssertionError: Expected 'touch' to have been called. ### Culprit Probable culprit: [PR #51787](vllm-project/vllm#51787) - pinned by symbol archaeology, bisect not run. Candidate range: [compare](vllm-project/vllm@4be3dcf...9a70c23). ### Fix mirror upstream's own post-#51787 test update (its analogous tests/v1/kv_connector/unit/offloading_connector/test_scheduler.py) by dropping the removed-call assertions and asserting touch is no longer called for the same scenario. ## Bug 3: add missing release_kv_cache_memory to MultiModelEngineClient - **State machine id**: online_model_swap_multimodelengineclient_abstract - **Commit**: 7ba9ac9 ### Root cause upstream vllm#44890 added a new abstract method release_kv_cache_memory to EngineClient; MultiModelEngineClient never implemented it, so instantiation raised TypeError. ### Culprit Probable culprit: [PR #44890](vllm-project/vllm#44890) - pinned by symbol archaeology, bisect not run. Candidate range: [compare](vllm-project/vllm@4be3dcf...9a70c23). ### Fix delegate to the wrapped AsyncLLM instance, mirroring the existing sleep/wake_up passthrough pattern. ## Bug 4: skip is_sleeping assignment on read-only Executor property - **State machine id**: online_model_swap_multimodelengineclient_abstract - **Commit**: 198d7e9 ### Root cause upstream vllm#44890 (same PR as the MultiModelEngineClient abstract-method break) turned Executor.is_sleeping into a read-only property computed from sleeping_tags. gaudi_reconfigure_engine's _reset_executor_sleep_state still assigned model_executor.is_sleeping directly, raising AttributeError: property 'is_sleeping' of 'UniProcExecutor' object has no setter during online model swap. ### Culprit Probable culprit: [PR #44890](vllm-project/vllm#44890) - pinned by symbol archaeology, bisect not run. Candidate range: [compare](vllm-project/vllm@4be3dcf...9a70c23). ### Fix feature-detect whether is_sleeping is a class-level property before assigning it; clearing sleeping_tags already makes the property read False on the new executor. ## Bug 5: implement apply_lora_full_linear on PunicaWrapperHPU - **State machine id**: hpu_unit_tests_engine_core_init_failed - **Commit**: 18d4414 ### Root cause upstream vllm PR 53555 ("[LoRA] Support modules_to_save for sequence classification") added a new abstract method apply_lora_full_linear to PunicaWrapperABC and implemented it for CPU, GPU and XPU. PunicaWrapperHPU never implemented it, so it is no longer a concrete class and get_punica_wrapper() raises TypeError: Can't instantiate abstract class PunicaWrapperHPU without an implementation for abstract method 'apply_lora_full_linear' while loading any LoRA model on HPU, which the engine surfaces as the generic "Engine core initialization failed". ### Culprit Probable culprit: [PR #53555](vllm-project/vllm#53555) - pinned by symbol archaeology, bisect not run. Candidate range: [compare](vllm-project/vllm@4be3dcf...9a70c23). ### Fix implement the hook with plain torch ops, mirroring the CPU and GPU versions: route rows through the prompt-level sampler_indices mapping and hand off to the inherited _select_full_linear_output helper for the bias and module-enabled selection. Multiplying against every adapter and gathering the routed row afterwards keeps the weight operand statically shaped for HPU graph compilation. The new method only references _select_full_linear_output at call time, and its only caller (ClassificationHeadWithLoRA) postdates PR 53555, so the change stays compatible with older VLLM_STABLE_COMMIT builds. --------- Signed-off-by: Paweł Olejniczak <pawelx.olejniczak@intel.com>
Signed-off-by: Dakai An <dakaian108@gmail.com> Signed-off-by: AlanFokCo <alanfok2868@gmail.com> Signed-off-by: aoshen02 <aoshen@inferact.ai> Signed-off-by: Dakai An <77474977+andakai@users.noreply.github.com> Co-authored-by: AlanFokCo <alanfok2868@gmail.com> Co-authored-by: aoshen02 <aoshen@inferact.ai> Co-authored-by: OpenAI Codex <noreply@openai.com>
…e_async (verl-project#7373) ### What does this PR do? Allow the hybrid GPUs to switch to the rollout mode in separate_async trainer to reduce trainer idle. Once the prompts for a step have been submitted, the trainer keeps its replicas in rollout mode and helps generate until the replay buffer holds enough sampleable groups, then reclaims the GPUs and trains. We use an adaptive threshold tracks how starved the trainer actually is. The threshold-adaptation idea is adapted from the dynamic resource scheduling introduced for `fully_async` in verl-project#6556; this PR applies the same principle at the step boundary of the `separate_async` trainer. Gated behind `trainer.v1.separate_async.enable_switch`, **off by default**. With it off the behaviour is unchanged. This PR also uses `sleep(level=2) + wake_up(tags=["weights"])` to simulate `release_kv_cache()` / `resume_kv_cache()` for the vLLM server, otherwise OOM when updating standalone weights. Once vllm-project/vllm#44890 (`release_kv_cache()` API, itself waiting on vllm-project/vllm#46438 `CuMemAllocator.discard()`) lands, this can be replaced by a direct tag-selective discard, which will also save the weight remap. A `TODO` records this. ### Test #### Setup Two end-to-end runs differing **only** in `trainer.v1.separate_async.enable_switch`. | | config| |---|---| | Hardware | 3 × 8 H100 — 2 nodes hybrid (trainer) + 1 node standalone rollout | | Model | Qwen3.5-35B-A3B | | Data | DAPO-Math-17k | | Trainer | Megatron, TP=2, PP=2, CP=2, EP=8, ETP=1 | | Rollout | vLLM, TP=4, `gpu_memory_utilization=0.7`, `n=8` | | Batching | `train_batch_size=64`, `ppo_mini_batch_size=16`, `parameter_sync_step=4` | | Lengths | `max_prompt_length=2048`, `max_response_length=32768` | Both runs went well past 150 steps; **all numbers and plots below are the first 150 steps of each.** #### Result: 12.6% less wall clock, 10.1% more tokens/s | | enable_switch | baseline | | |---|---|---|---| | wall clock for 150 steps | **16.43 h** | 18.80 h | **−12.6%** | | tokens / s (total tokens ÷ total wall clock) | **16 687** | 15 150 | **+10.1%** | | `perf/throughput` (arithmetic mean) | 712.3 | 663.8 | +7.3% | <img width="1634" height="581" alt="fig1_gen_and_step" src="https://github.com/user-attachments/assets/72bdbf03-ad64-4e3d-b32a-68d8ec247e13" /> `switch_wait` is **not** new overhead: during that window the trainer's GPUs are generating, whereas the `gen` time it replaces was pure idling. #### Training quality <img width="1634" height="617" alt="fig4_quality" src="https://github.com/user-attachments/assets/d02f7138-70d7-442d-bfa5-32f610067de8" /> | | enable_switch | baseline | |---|---|---| | `critic/score/mean` | 0.7888 | 0.7878 | | `training/off_policy/trajectory_staleness/mean` | 0.556 | 0.522 | | `training/off_policy/trajectory_spans/mean` | 1.436 | 1.470 | The reward curves are almost the same. Staleness rises 6.5% in the mean, which is expected — when the `switch_threshold_ratio` is higher than perfect, `update_weights` will be delayed. #### Throughput over time <img width="480" height="305" alt="fig3_throughput" src="https://github.com/user-attachments/assets/a36f5ded-557e-4866-aca9-89fdf7f9bfd2" /> #### Unit tests ```bash pytest tests/trainer/ppo/v1/test_separate_async_step_switch_on_cpu.py -v pytest tests/trainer/ppo/v1/test_replay_buffer_on_cpu.py -v ``` #### Limitations - Only validated on the 2-hybrid + 1-standalone ratio above. That ratio is favourable to this feature — the trainer owns 2/3 of the GPUs, so there is a lot of idle capacity to reclaim. Expect smaller gains as standalone rollout capacity grows. - The current implementation is inherently sticky: every decision extrapolates from measurements taken on previous steps, which assumes the sample production rate stays roughly constant from one step to the next. If generation throughput oscillates sharply between steps, the benefit degrades. - `enable_switch` is rejected together with rollout disaggregation (PD). ### API and Usage Example New keys under `trainer.v1.separate_async`, all inert unless `enable_switch=true`: ```yaml trainer: v1: separate_async: # Allow the trainer to switch to rollout mode to reduce idle. enable_switch: false # Fraction of train_batch_size that must be sampleable before the rollout replicas are # reclaimed. switch_threshold_ratio: 0.4 # Optional threshold adaptation. Starvation raises the ratio immediately; calm steps lower it # only after the configured release interval. adaptive_switch_threshold: true switch_threshold_step_up: 0.05 switch_threshold_step_down: 0.03 # Consecutive idle/calm steps required before ratio adjusts in that direction. switch_threshold_release_steps: 2 # Window size for calculating average switch cost. switch_cost_window_size: 3 ```
Motivation
Sleep level 2 releases KV cache memory, but it also discards model weights. This
is unnecessarily expensive when a framework only needs temporary GPU headroom
while keeping the same model instance resident.
One concrete use case is model weight update in RL training. The workaround in
verl#7373 uses
sleep(level=2)followed bywake_up(tags=["weights"])before updating thestandalone model. Releasing only the KV cache reduces peak GPU memory and can
avoid OOM during the update, without discarding and remapping weights.
Summary
This PR adds
release_kv_cache_memory()as a dedicated KV-only partial-sleepoperation. It discards KV cache allocations, keeps model weights resident, and
pauses scheduling until the released memory is restored with the existing
wake_up()API.Implementation
Call flow
The offline and server entry points converge on the same engine path:
EngineCorefirst pauses the scheduler and clears the prefix cache. Dependingon the selected pause mode, it either handles existing requests immediately or
waits for in-flight requests to finish before asking all workers to discard KV
cache allocations. The scheduler remains paused after release; a discard
failure also fails closed instead of resuming scheduling with potentially
partially unmapped memory.
At allocator level, only mapped allocations tagged
kv_cacheare unmapped andreleased, without a CPU backup. Per-allocation mapping state prevents duplicate
unmap or map operations when release, sleep, and wake-up calls are mixed.
Interaction with sleep levels
release_kv_cache_memory()is treated as a KV-only partial sleep. A latersleep(1)orsleep(2)can upgrade that state to a full sleep:release_kv_cache_memory()sleep(1)sleep(2)wake_up(["kv_cache"])wake_up(["kv_cache"])wake_up()The executor tracks the exact internal state with
sleeping_tags. Schedulingis resumed only after no sleeping tags remain.
Logging and observability
This PR reuses the existing sleep-state logger instead of adding a dedicated
kv_cache_releasedPrometheus state. After KV release, the existing metricsreport
awake=0,weights_offloaded=0, anddiscard_all=0: the engine is notavailable for scheduling, but it is not in sleep level 1 or 2. The precise
resource state remains available internally through
sleeping_tags.There is currently no requirement to monitor KV-only release separately. If
that becomes useful, a dedicated Prometheus state and its transition logic can
be added in a follow-up change.
Scope
The public API intentionally supports only KV cache release. Existing sleep
levels already cover the other current cases:
sleep(1)offloads weights and discards KV cache memory.sleep(2)discards all managed GPU memory.A generic public tag API would also need to define whether each tag is discarded
or offloaded, increasing the API surface and overlapping with existing sleep
semantics. More fine-grained public memory management can be discussed when a
concrete additional use case appears; the internal
discard(tags)path remainsextensible.
Related work
tag-level sleep management. This PR instead provides a smaller, explicit
end-to-end API for the known KV-only use case.
allocator-level selective-discard work.
downstream model-update use case and its current sleep/wake workaround.
This PR does not duplicate the generic public API proposed in #42658; its scope
and semantics are intentionally narrower.
Tests
Local validation used an Enroot container on one NVIDIA H200 with Python 3.12.3
and Torch 2.13.0+cu130. The PR Python source was tested with the image's
precompiled native libraries (vLLM distribution 0.1.dev20073+g8e685d198).
Result: 5 passed. Rejection coverage checks an unpaused scheduler, pending
requests, and pending batches independently, with no cache reset or discard on
failure. Removing each guard in memory caused its corresponding test to fail.
.venv/bin/python -m pytest tests/basic_correctness/test_mem.py \ -k release_kv_cache_memory_preserves_generation \ -x -v -o addopts="" --timeout=600Result: 2 passed. Real Qwen3-0.6B generation covers rejection without a pause,
KV-only release/wake-up, and release followed by full level-1 sleep/wake-up.
Checks use process-local mapped memory and compare greedy token IDs before and
after restoration.
Result: all applicable hooks passed.
The test revision changes no production behavior; no additional model
benchmark was run beyond the generation-equivalence checks above.
AI assistance
AI assistance was used to review the implementation, revise and validate the tests,
and draft this description.
The submitter reviewed the resulting changes and test scope.