Repository navigation
[rl] Add reprefill_after_model_state_dict_load="next_turn"; drop the KV reset on load - #5953
felipemello1 wants to merge 5 commits into
Conversation
A training sample kept its opening turn's min_policy_version and widened only the max. A later turn can be older: the router moves a session off an overloaded generator (repin_load_ratio), and the new generator may not have finished the same model state dict load. The sample's age then read too low. Widen the min the same way as the max, as the verifiers generation server already does.
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 3m 24s —— View job Needs discussion: review posted. Removing the reset mode and adding the controller check are sound; whether |
There was a problem hiding this comment.
Verdict: Needs discussion -- deleting the reset mode and adding the controller check are sound and should land. "next_turn" is a new mode that nothing in the repo uses, its motivation isn't linked, and the measured cost is high, so maintainers need to decide whether it lands before the A/B.
What this PR does. It replaces reset_kv_cache_on_model_state_dict_load: bool with reprefill_after_model_state_dict_load: Literal["new_groups", "next_turn"]. The vLLM engine now always salts each request with min_policy_version and never resets the prefix cache. "next_turn" stamps each request with the installed policy version instead of its group's pin. The batch-invariant recipes drop the reset flag. Controller.Config now requires target_offpolicy_steps=0 for batch_invariant.
Example. One rollout; load v+1 lands while turn 2 decodes.
main default / "new_groups" main reset=True "next_turn"
turn 2 at load keeps KV, decodes on preempted, recomputes keeps KV, decodes on
turn 3 (salt) group pin v -> reuses old KV no salt, cache empty v+1 -> full history prefill
turn 4 reuses reuses reuses turn 3's KV
Must fix
- PR description -- the "Summary (human-written)" section is empty. The author needs to fill it in.
generator.py:156--"next_turn"has no in-repo consumer. Its only user is a planned A/B, and its source ("Figure 33 of a lab's RL training report") isn't linked yet. Your own timeline check measured 2.9x the computed prefill tokens and a p99 queue wait of 25.4 s (vs 2.3 s), and the TODO atengine_loop.py:525means it doesn't fully hold under the burst it creates. Smallest path: split the PR. Land the reset removal and thetarget_offpolicy_steps=0check now (net about -150 LoC). Add"next_turn"(about +30 LoC: the Literal, one branch, docstring) together with the report link and the A/B results. If maintainers want it now, link the report in the field docstring.engine_loop.py:525-- the TODO depends on an upstream vLLM gap but has no issue link (inline).
Should consider
generator.py:153-- the router-replay TODO refers to a feature the repo doesn't have (inline).generator.py:173-- thesession_kv_holder+"next_turn"interaction is documented only in the PR description (inline).
Questions
- For the A/B: some
"next_turn"turns will be admitted with a stale salt (queued at a load). Is the existing policy-age metric enough to measure that fraction, or does the A/B need a dedicated count?
Details
Is the reset removal safe for batch-invariant configs? Yes, as far as I can tell from the code. Every batch_invariant recipe sets target_offpolicy_steps=0. At that setting, capacity is num_prompts_per_train_step, and the trainer releases slots only after pull_model_state_dict returns (controller.py:1312). So no training group is admitted or running when a load lands. A slot freed for an untrainable_group is refilled at the current version, and the step waits for it. Group ids increase monotonically, so a new group never inherits an older pin, and at a given version every request gets the same salt. The prefix-cache hits therefore match main's reset path. Validation groups use negative ids, are released after each validation, and get the current version's salt. Stale cached blocks now stay until LRU evicts them instead of being cleared, which changes scheduler free-block counts but not batch-invariant numerics. This agrees with the bitwise-equal 10-step loss guard in the description.
Overlap. #5811 and #5812 (SGLang) touch the same flag, as the description notes.
Not verified: GPU parity/integration runs (8-GPU tests/integration_tests/rl.py not run by the author either). A maintainer still needs to review.
| # TODO: a request still queued in vLLM when a later load lands keeps this salt and | ||
| # can reuse pre-load KV (min_policy_version stays honest). The re-prefill burst | ||
| # after each load makes such queues. Fix: re-salt queued requests at the load, | ||
| # which needs vLLM to rebuild their block hashes. |
There was a problem hiding this comment.
This TODO depends on an upstream vLLM gap ("needs vLLM to rebuild their block hashes"), but it has no upstream issue link (CLAUDE.md principle 3). The gap also hits "next_turn" exactly when it costs the most: the re-prefill burst after a load is what leaves requests queued (30.2 s max wait in the timeline check), so a load during that burst lets those turns reuse pre-load KV. Please file the vLLM issue (re-salting / rehashing a waiting request) and link it here.
There was a problem hiding this comment.
Reply from claude: The fix fits in our engine, so it needs no vLLM issue. At a "next_turn" load, VLLMEngine can abort the requests still waiting with no computed tokens and re-add them with the new stamp, on every rank (same priority and arrival time, so they keep their queue place). The TODO now says that (a5041ec, engine_loop.py:525-529). It stays a follow-up: the timeline check saw 0 queued requests at its 4 loads.
| # TODO: once the trainer replays the MoE expert choices the generator recorded (router | ||
| # replay), the "next_turn" full prefill should also replay the expert ids recorded when | ||
| # the history was first computed, so its KV matches the trainer's replayed forward. |
There was a problem hiding this comment.
Router replay doesn't exist anywhere in the repo (no matches for router/routing replay under torchtitan/). So this TODO describes a constraint on a feature that hasn't been designed yet, and whoever adds router replay will have to work out how it interacts with re-prefill anyway. Suggest dropping this TODO, or moving it to the router-replay design issue if one exists.
There was a problem hiding this comment.
Reply from claude: Removed the TODO from the code (a5041ec). The follow-up is a NOTE in the PR body instead: once router replay exists, the "next_turn" full prefill should replay the recorded expert ids.
| A request already queued in the engine at the load, but not yet started, keeps the older | ||
| version: it can reuse KV from before the load, and its ``min_policy_version`` says so. |
There was a problem hiding this comment.
This PR removes the session_kv_holder + reset ban in vllm/engine.py, so session_kv_holder + "next_turn" is now allowed. After a load, though, every held block has the old salt, and the session's next turn can't hit it. Those holds then only take memory away from the re-prefill burst until the holder releases them under memory pressure. The PR description notes this (item 7), but the code doesn't. Suggest one sentence here: "With session_kv_holder, a session's hold is unusable after a load until its next prefill replaces it." Or, if the A/B doesn't need the holder, ban the combination in __post_init__.
There was a problem hiding this comment.
Reply from claude: Added the sentence to the field docstring (a5041ec, generator.py:172-173): with "next_turn" and the session KV holder, a session's hold is unusable after a load until its next prefill replaces it. Kept the combination allowed: outputs stay correct, and the holder releases idle sessions under memory pressure.
Bitwise parity needs the trainer to score each sample with the weights that sampled it. At target_offpolicy_steps > 0 the trainer scores samples with newer weights, and a turn running across a model state dict load samples under two versions, so the logprobs can't match even with hot_swap=False. Every in-repo batch-invariant config already runs with target_offpolicy_steps=0; the check makes the requirement explicit, and BITWISE_PARITY.md lists it.
Generator.Config.reset_kv_cache_on_model_state_dict_load is removed. Its only users were the batch-invariant configs, which a generator check forced to set it. They all run at target_offpolicy_steps=0, where no request is in vLLM at a load, so the group-pin salt alone gives every request the same cache hits as the reset; the previous commit states that requirement in the controller. The vLLM engine now always salts each request by its min_policy_version (the group's pinned version) and never resets the prefix cache, so it no longer needs the mode, and the session KV holder's guard against the reset goes with it.
Generator.Config.reprefill_after_model_state_dict_load: Literal["new_groups", "next_turn"] = "new_groups" chooses which requests prefill again under the new weights after a model state dict load. - "new_groups" (default, today's behavior): a request's cache salt is its group's version at first admission, so later turns and siblings reuse the group's KV across loads. - "next_turn": the engine loop stamps each request with the installed version. A turn running at a load keeps its KV; the next turn misses the cache once and prefills its whole history under the new weights.
…cache salt Completion and RolloutTurn said "oldest policy version among this turn's decode". The code stamps min at admission, and it is the request's prefix cache salt; GenerateFn.group_id points to the new field for reuse across policy versions.
2efa402 to
acdf878
Compare
|
Reply from claude: On must-fix 2 ("next_turn" has no in-repo consumer): the author keeps it in this PR rather than splitting it out. "next_turn" is for an A/B against "new_groups" that the author is setting up, and the report link will be added when available. The PR is now stacked on #5954 (an unrelated min-version fix in the trainer; no shared files). Changes since your review: the three inline items (a5041ec), and a body NOTE on the red @claude please review |
|
Claude finished @felipemello1's task in 1m 14s —— View job Needs discussion: review posted. Your three inline fixes are resolved. Still open: the empty human-written summary, and a maintainer call on landing |
There was a problem hiding this comment.
Verdict: Needs discussion -- the code is ready. A maintainer still has to accept landing "next_turn" before its A/B, and the human-written summary is still empty.
Re-review of a5041ec..acdf878 against the previous review.
Earlier items
- Resolved:
engine_loop.py:525TODO. The fix fits inside torchtitan (abort and re-add requests still waiting with no computed tokens), so no upstream vLLM gap exists and no issue link is needed. The TODO now spells out the fix. - Resolved: the router-replay TODO is out of the code and now a NOTE in the PR body.
- Resolved: the
session_kv_holder+"next_turn"interaction is documented in the field docstring (generator.py:167-168). - Resolved: the question about counting queued turns. The answer under "You may ask" holds: min/max policy version can't tell a queued turn from a turn that spans a load, so the A/B needs its own count.
Must fix
- PR description -- "Summary (human-written)" is still empty. Only the author can write it (still open).
generator.py:153--"next_turn"still has no in-repo consumer and no linked source (still open, maintainer call). The author has chosen to keep it in this PR for the planned A/B. The code for it is small (one Literal value, one branch, a docstring), and the measured cost is stated honestly. A maintainer needs to accept that explicitly before merge. If they do, put the report link in the field docstring once it exists.
New commits
I found no new problems. All callsites of the removed flag are updated: GenerationEngine's kwargs, VLLMEngine (the only engine subclass), EngineLoop, Generator, the 7 recipe sites, and the tests. No references remain. In "next_turn" mode, release_groups still pops with a default (engine_loop.py:235), so it is safe when the group was never pinned.
Details
Check placement. The old guard keyed on generator.debug.batch_invariant. The new one keys on trainer.debug.batch_invariant (controller.py:422), next to the other batch-invariant checks. A generator-only batch_invariant=True no longer has an on-policy check. Parity needs both sides anyway, so this doesn't matter in practice.
TODO wording. The fix described at engine_loop.py:527 runs "in VLLMEngine at a 'next_turn' load". Since this PR, the engine no longer knows the mode, so that follow-up will have to pass the mode back in (or carry it on the load decision). Worth knowing when the follow-up is written. No change needed now.
Not verified: the GPU parity and 8-GPU integration runs. A maintainer still needs to review.
…ore (#6027) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why A multi-turn session's KV lives on one generator. When its next turn lands on another generator (after a repin, or with non-sticky routing), that generator recomputes the whole history. This is the SGLang counterpart of #5727 (vLLM). **Background: SGLang HiCache.** SGLang's hierarchical cache (HiCache) keeps prefix KV in three tiers. Only L3 is shared across generators: | Tier | Where | Shared across generators? | SGLang (`extra_server_args`) | vLLM counterpart in TorchTitan | | --- | --- | --- | --- | --- | | L1 | GPU memory | no | prefix (radix) cache, on by default | prefix cache | | L2 | host memory | no | `enable_hierarchical_cache=True`, `hicache_size` (already supported, see the README's "CPU KV offload") | `SimpleCPUOffloadConnector` (#5847) | | L3 | storage backend | yes | `hicache_storage_backend="mooncake"` (this PR) | `MooncakeStoreConnector` (#5727) | L3 works through L2: a load goes Store -> host -> GPU, so enabling the Store also enables L2. SGLang itself moves KV between tiers, prefetches from L3, and keeps TP ranks consistent, so unlike #5847/#5727 this needs no connector or coordination code in TorchTitan: users can already turn L3 on through `extra_server_args`. But turned on as is, L3 silently serves KV that other weights computed in two cases. This PR adds one config check for each: 1. **Across runs.** Store keys are the model path, the request's cache salt (its pinned policy version: "0", "1", ...), the token prefix and the TP rank. Every run starts at policy version 0, so two runs' keys for the same prompt are identical. The Store outlives a run, so run B loads KV that run A's weights computed, and Mooncake's write-once `put` keeps run B's own KV from replacing it. **Check:** `"mooncake"` requires a non-empty `extra_backend_tag`, a key prefix that scopes keys to a run. A resume can keep its tag to reuse KV; the README notes the catch (KV the previous launch computed after the checkpoint). 2. **With `reset_kv_cache_on_model_state_dict_load=True`.** This mode relies on clearing all KV at each weight load, so requests carry no cache salt and keys depend only on tokens. But SGLang's KV reset (`flush_cache`) clears L1 and L2, never L3, for any storage backend, so after a load a request can load KV that earlier weights computed. verl hit the same gap (verl-project/verl#8323). **Check:** a storage backend with this mode raises; the default mode (False) salts requests by their pinned policy version, so it is safe. **Example of case 2** (reproduced locally, Qwen3-0.6B, TP 2): ```text generator A, reset mode, weights at version 0: turn 1 -> KV written to the Store (unsalted keys) generator B, reset mode, weights at version 7: turn 2 -> 649 of 650 history tokens loaded from the Store, i.e. KV that version-0 weights computed ``` ## What changed - `engine.py` (config validation only): - Case 1, `Config.__post_init__`: with `hicache_storage_backend="mooncake"`, raises unless `hicache_storage_backend_extra_config` sets a non-empty `extra_backend_tag`. The tag is the key prefix that scopes keys to a run, like #5727's `cache_prefix`; the check cannot tell a new tag from a reused one. Other storage backends raise: their keys can also outlive a run (e.g. `file` keeps them on disk under `/tmp/hicache`) and have no verified run-scoped prefix. - Case 2, `__init__`: raises when any storage backend is combined with `reset_kv_cache_on_model_state_dict_load=True`; the error tells users to keep it False. #5953 proposes removing the reset mode; this check goes away with it. - `README.md`: a new section covering setup (`scripts/install_rl_env.sh` already installs the Mooncake SDK for the transport API; start one `mooncake_master` per SGLang's deployment guide; each generator contributes Store memory, as in #5727), how the Store sits below HiCache's host memory, configuration, key semantics, constraints and measured results. No new config fields: users configure Mooncake through `extra_server_args`, as they already do HiCache. ## Performance **What is compared.** Turn 2 of 4 sessions on a generator that has not seen them, done two ways: - **Recompute:** a fresh generator without a Store prefills each session's whole history (16,024 tokens). - **Load from the Store:** generator A runs turn 1 (16,000 distinct random tokens per session, 16 decoded tokens) and stays alive, keeping the KV in the Store memory it contributed. Generator B, on other GPUs with empty GPU and host caches, runs turn 2: it loads 16,015 of the 16,024 history tokens per session from the Store and prefills only the rest. Time is wall clock from submitting the 4 turn-2 requests until all finish (16 decoded tokens each). **Setup.** One host, 8x H100; each generator TP 2 on its own GPUs; RDMA over 1 NIC; prefetch policy `wait_complete`. The Store side runs HiCache with 16 GB of host memory per rank (the L2 that every Store load goes through: Store -> host -> GPU) and contributes 32 GB to the Store; the recompute side runs without HiCache (its caches would be empty anyway). One run per cell, no warmup. | Model | Recompute (s) | Load from the Store (s) | Store vs. recompute | | --- | ---: | ---: | --- | | Qwen3-8B | 1.38 | 1.93 | 1.4x slower | | Qwen3-32B | 5.24 | 2.45 | **2.1x faster** | **Takeaway.** From 8B to 32B, recompute time grew 3.8x but load time only 1.3x: loading scales with KV size, recompute with model compute. The Store pays off when recomputing costs more than moving KV: bigger models, longer histories, faster interconnect (RDMA). **Caveats.** - The engine's 1-token pages (needed for batch invariance) make one Store object per token, K and V, and TP rank, so loads move many small objects. - No end-to-end RL run was measured. ## Known issues / follow-ups - Not verified: linear attention (GDN, KDA, whose HiCache already raises), MLA, sliding window, or a Store shared across hosts. - 1-token pages make many small Store objects. Newer SGLang adds `l3_page_span`, which could group them.
Summary (human-written)
Agent details
TLDR: A new generator mode re-prefills a rollout's next turn after a model state dict load, instead of reusing
KV computed under older weights. The running turn keeps its KV. The scheme comes from Figure 33 of a lab's RL
training report (link to follow). The "reset all KV on load" mode is removed, and
batch_invariantnow states itsreal requirement:
async_loop.target_offpolicy_steps=0.No in-repo config sets "next_turn" yet. It is for a planned learning A/B against "new_groups".
Problem
min_policy_versionis its vLLMcache_salt. A request reuses only KV cached by requests with thesame salt.
versions ago.
Solution
Generator.Config.reset_kv_cache_on_model_state_dict_load: boolbecomesreprefill_after_model_state_dict_load: Literal["new_groups", "next_turn"] = "new_groups".salt and misses the cache once. Later turns at that version hit it.
forced them to. All run at
target_offpolicy_steps=0, where no request is in vLLM at a load. There the defaultsalt gives every request the same cache hits as the reset, so those configs now use the default.
Controller.Confignow raises unless abatch_invariantrun hasasync_loop.target_offpolicy_steps=0: a turn running across a load samples under two policy versions, so thetrainer's and the generator's logprobs can't match. Main's reset did not fix that case either.
min_policy_versionstays a lower boundof the versions its KV and tokens come from, in both modes.
min_policy_versionand never resets.its next prefill replaces the hold (also in the field docstring).
Results
Timeline check: 1 GB300, Qwen3.5-9B-Base, the real
Generatordriven by 192 agent sessions x 12 turns (2,048-tokenprompt shared by 32 siblings). Model state dict loads at 40 s (hot), 80 s (two hot) and 120 s (drain). Only the
weight copy is skipped; the salt and version path is real. One run per mode.
* Other jobs shared the host during the "new_groups" run, so +8.6% may understate the cost. The computed prefill
tokens don't depend on that.
RL loss guard config (
rl_grpo_qwen3_0_6b_varlen_batch_invariant, now on the default "new_groups"), main vs thisPR, 10 steps, TP2 on 4 GB300:
loss/meanis bitwise equal at every step.You may ask:
reset_prefix_cache(reset_running_requests=False)at each load? vLLM resets only when no block is in use.With requests running, it logs a warning and does nothing.
KV from the old weights.
end with min v and max >= v+1. The A/B needs its own count: requests still waiting in vLLM, with no computed tokens,
at each load.
minus the shared prompt. In the timeline check, computed prefill went from 1.78M to 5.14M tokens over 4 loads
(+3.37M, 2.9x the "new_groups" total). Flip the default only if the learning A/B pays for it.
NOTE: A request still queued in vLLM when a load lands keeps the older salt and can reuse KV from before the load;
its
min_policy_versionrecords that. "next_turn" itself creates such queues: the re-prefill burst after each loadkept requests waiting up to 30.2 s in the timeline check. So a load inside that burst finds queued turns (the check's
loads missed the bursts: 0 queued at 4 loads). The fix fits in our engine, with no vLLM change: at the load, abort the
requests still waiting with no computed tokens and re-add them with the new stamp. TODO in
engine_loop.py.NOTE: Follow-up once router replay exists (it is not on main): the "next_turn" full prefill should replay the expert
ids recorded when the history was first computed.
NOTE: #5811 and #5812 (SGLang) also touch this reset flag; whichever lands second drops it.
NOTE: Stacked on #5954 (a separate min-version fix in the trainer; no shared files).
NOTE: CI
RL Multi-GPU Unit Testsis red onTestBitwiseParityQwen35DebugVarlen:test_trainer_vs_vllm_prefillat2efa402 (max_delta 2.34e-03),
test_reload_after_generateat acdf878 (max_delta 5.01e-04). Both flake on main:test_trainer_vs_vllm_prefillin 5 of today's runs (e.g. 42507290038),test_reload_after_generatein run42532195905. These tests build a raw vLLM
LLMEngineand read no field this PR changes; this PR edits only a commentin that file.
Test plan
GPU unit tests as CI runs them (1-GPU job, 3 bitwise-parity classes on 2 GPUs): all pass except 2 that also fail
on main.
test_generator_dist_moe_mxfp8needs a torchrun env (RANK); it passes undertorchrun --nproc-per-node=1.TestBitwiseParityQwen35DebugVarlen::test_trainer_vs_vllm_prefillfails on one rank in 2 of 3 runs on main.Not run: the 8-GPU batch-invariant integration tests (
tests/integration_tests/rl.py); the test box has 4 GPUs. The4-GPU loss guard above ran instead.