Repository navigation
GRPO: opt-in parking of optimizer state and gradients on host during rollout - #13866
Conversation
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b318960778
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| torch.cuda.synchronize() | ||
| torch.cuda.empty_cache() |
There was a problem hiding this comment.
Drop loop-held CUDA references before emptying the cache
When the last iterated parameter has a CUDA gradient or optimizer-state tensor, the function locals grad and value still reference those tensors when empty_cache() runs. Replacing param.grad and the state entries therefore does not free the final tensors until this helper returns—after the only cache flush—so their blocks remain reserved by PyTorch and unavailable to colocated vLLM; this can retain substantial memory when the final parameter is a large output embedding. Clear those loop locals (or move collection into a helper scope) before synchronizing and emptying the cache.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed: the loop locals are cleared before synchronize / empty_cache, and a new test checks with weakrefs that no parked grad or state tensor is still referenced when empty_cache runs (it fails without the change).
| for name, value in state.items(): | ||
| if _is_parkable_tensor(value): | ||
| states.append((state, name, park(value, (id(param), name)))) |
There was a problem hiding this comment.
Park nested Q-GaLore projector tensors
When the repository's Q-GaLore optimizer is used, each ranked parameter stores a GaLoreProjector under state["projector"] (unsloth/optimizers/q_galore_adamw.py:184-186), and that object retains CUDA tensors such as ortho_matrix, its quantization tensors, and past_ortho_vector (unsloth/optimizers/q_galore_projector.py:50-68). This loop only recognizes top-level tensor values, so the projector and all of those optimizer-state allocations remain on the GPU during every rollout, defeating a potentially significant part of the opt-in memory saving. Traverse or explicitly handle the projector state, or disable parking for this optimizer rather than reporting a partial park.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c0a3c1d: parking now declines optimizers whose state holds anything other than tensors and scalars (Q-GaLore's projector), with a one-time message, instead of parking part of it.
| return ( | ||
| isinstance(value, torch.Tensor) | ||
| and value.is_cuda | ||
| and not getattr(value, "is_paged", False) |
There was a problem hiding this comment.
Exclude sparse tensors from the dense parking path
When a GRPO model has a sparse CUDA gradient, such as an nn.Embedding(sparse=True) trained with SparseAdam, this predicate accepts it as parkable. park() then allocates a dense strided CPU tensor and attempts host.copy_(sparse_grad), but PyTorch does not implement sparse-to-dense copy_, so the rollout fails before generation instead of merely skipping that gradient. Restrict this path to strided tensors or preserve the source tensor's sparse layout.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c0a3c1d: only strided CUDA tensors are parked; sparse grads stay where they are.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ecdd212a59
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # Loop locals still hold the last CUDA tensors; drop them so empty_cache can release those blocks. | ||
| value = grad = None | ||
| # D2H copies must land before the CUDA blocks are handed to vLLM / released. | ||
| torch.cuda.synchronize() |
There was a problem hiding this comment.
Synchronize every device before releasing parked tensors
When a supported single-process model places optimizer state on a non-current GPU (for example, an hf_device_map split across cards), the asynchronous D2H copies for that GPU are not covered by this call: torch.cuda.synchronize() without a device only synchronizes the current device. The code then drops the source references and empties the cache despite its stated requirement that all copies have landed, which can leave those allocations unavailable during rollout and can interact unsafely with allocator backends processing pending work. Collect the devices recorded in parked and synchronize each one before calling empty_cache().
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c0a3c1d: every device that holds a parked tensor is synchronized before empty_cache.
| optimizer = trainer.optimizer | ||
| optimizer = getattr(optimizer, "optimizer", optimizer) |
There was a problem hiding this comment.
Descend into layer-wise optimizer dictionaries
When GRPO uses a Transformers layer-wise optimizer such as galore_adamw_layerwise or apollo_adamw_layerwise, unwrapping Accelerate here yields a LayerWiseDummyOptimizer: its visible parameter group contains only a CPU sentinel, while the real per-parameter optimizers and their CUDA states live in optimizer_dict (Transformers implementation). Consequently this helper finds neither state nor real parameters, returns None, and the enabled parking option silently frees no optimizer memory for these supported single-GPU optimizer modes. Traverse the optimizers in optimizer_dict, or explicitly reject layer-wise optimizers rather than reporting a successful no-op.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c0a3c1d: layer-wise optimizers (optimizer_dict) are declined explicitly with the same message rather than reported as a successful no-op.
| host = buffers.get(key) | ||
| if host is None or host.shape != tensor.shape or host.dtype != tensor.dtype: | ||
| host = torch.empty(tensor.shape, dtype = tensor.dtype, device = "cpu", pin_memory = True) | ||
| buffers[key] = host |
There was a problem hiding this comment.
Preserve tensor strides in host buffers
When a trainable parameter and its optimizer state use a non-default strided layout, such as channels-last vision weights or a transposed parameter with fused AdamW, this allocation converts every parked state and gradient to contiguous layout; restoring with host.to(device) preserves that new layout rather than the source strides. PyTorch deliberately initializes Adam state with memory_format=torch.preserve_format (Adam implementation), and fused Adam requires parameters, gradients, and moments to have matching layouts, so the first optimizer step after a rollout can fail with a layout mismatch. Allocate the reusable buffer with the source tensor's strides or preserved memory format instead of shape and dtype alone.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c0a3c1d: host buffers are allocated with empty_like (preserve_format) and reallocated when strides differ, so the restored state keeps the source layout. Checked on GPU that a transposed CUDA tensor round-trips with strides (1, 32), plus a CPU test.
…timizer state [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
[skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
pre-commit.ci run |
1 similar comment
|
pre-commit.ci run |
…uantized adamw_flash moments (unslothai#14201) ## Summary Two follow-ups on opt-in optimizer features. Both default paths are unchanged. 1. **Optimizer parking under an outer `torch.inference_mode()`** (`UNSLOTH_PARK_OPTIMIZER_DURING_ROLLOUT=1`, unslothai#13866). When `generate_and_score` ran inside `inference_mode`, for example during an eval between train calls, the pinned host buffers and the restored moments and grads became inference tensors. The next `optimizer.step()` then raised `Inplace update to inference tensor outside InferenceMode is not allowed`. Parking and restoring now run under `torch.inference_mode(False), torch.no_grad()`. After restore the values are byte-equal, nothing is an inference tensor, and two park / step cycles in a row pass. 2. **`adamw_flash` with trainable fp16 parameters** (unslothai#13881). With `quantize=False`, flashoptim stores the Adam moments in the parameter dtype (`flashoptim/optimizers.py`, 0.1.4). An fp16 variance (`grad**2 * (1 - beta2)`) underflows to 0 for small gradients, so the update becomes momentum / eps. In a repro, one fp16 weight went to -46.375 where an fp64 AdamW reference gives 0.99833. Upstream avoids this only through its `quantize=True` default, which stores the variance as a square root with per-group scales. Keeping the variance in fp32 would need a change to flashoptim's kernel, so `UnslothFlashAdamW` now raises a clear error for trainable fp16 parameters in a group with `quantize` off. The message says to cast to float32 / bfloat16 or set `optim_args = 'quantize=True'`. With `quantize=True` the results match main (max error 2.05e-4 against the reference), and bf16 / fp32 parameters are unaffected. ## Tests - `tests/test_grpo_park_optimizer_during_rollout.py::test_park_under_outer_inference_mode_restores_ordinary_tensors` (CPU): fails on main, passes here. - `tests/utils/test_flash_adamw_optim.py::test_adamw_flash_rejects_fp16_params_with_unquantized_moments` (CPU, stubbed flashoptim): fails on main, passes here. - Both files on GPU with the real flashoptim 0.1.4: 49 passed. ## Not covered here - No end-to-end GRPO run with parking, and no Trainer run through an fp16 trainable parameter path; the helpers and the optimizer were tested directly. - torch 2.13 only.
…LLM resume/teardown paths (#13438) ### What `_maybe_prepare_vllm_for_resume()` returned early whenever `torch.cuda.is_available()` was `False`, so the vLLM `sleep()` plus the cache release that follows it never ran on NPU / XPU. The two release loops also called `torch.cuda.empty_cache()` directly, which is a silent no-op off CUDA, so the blocks freed by the dropped model stayed reserved in the active accelerator's allocator - exactly the state this path exists to avoid before re-loading for a resume. The neighbouring loader-retry flush and the q_galore fence were moved to `clean_gpu_cache()` / `device_synchronize()` for the same reason. - `unsloth/models/rl.py`: gate on `DEVICE_COUNT` (the active accelerator's device count) instead of CUDA availability, and flush through `clean_gpu_cache()`. - `unsloth/dataprep/synthetic.py`: the vLLM server-teardown release loop flushes through `clean_gpu_cache()`. - `tests/test_device_helpers.py`: `test_model_call_sites_use_shared_cache_dispatch` now covers these two files as well. CUDA / HIP behaviour is unchanged: `DEVICE_COUNT >= 1` there, and `clean_gpu_cache()` dispatches to `torch.cuda.empty_cache()`. ### Verification Real machine, 4x Ascend 910B, `torch 2.15.0.dev20260917+cpu` / `torch_npu 2.15.0.dev20260917`: ``` torch.cuda.is_available() = False -> old guard returned before flushing reserved after 256 MiB npu alloc = 258.0 MiB del + gc.collect() + torch.cuda.empty_cache() -> 258.0 MiB (old call: released nothing) npu.empty_cache() (= clean_gpu_cache() path) -> 0.0 MiB ``` `pytest tests/test_device_helpers.py::test_model_call_sites_use_shared_cache_dispatch` - **1 passed** with the change. Reverting only `unsloth/models/rl.py` and `unsloth/dataprep/synthetic.py` to the pre-change revision, the same test **fails** at `assert "if not torch.cuda.is_available():\n return" not in rl_source`. ### Not tested An actual vLLM / vLLM-Ascend sleep-mode resume (no vLLM in the verification environment), Intel XPU hardware, and a CUDA box. No open PR rewrites these call sites (`is:pr is:open empty_cache` and `is:pr is:open clean_gpu_cache` both return 0). ## Tests `tests/test_device_helpers.py` now checks the resume helper by itself instead of all of `rl.py`. Since #13866, `rl.py` has a CUDA-only optimizer parking path with its own `torch.cuda.is_available()` gate and `torch.cuda.empty_cache()` call. That made the file-wide string checks fail once `main` was merged in. The helper is pulled out with `ast` and run against a fake vLLM engine: - `DEVICE_COUNT` of 1 or 4: `llm.sleep(1)` runs once and the cache is flushed 3 times through `clean_gpu_cache()`. This covers both `trainer.llm` and `model.vllm_engine`. - Sleep mode off: nothing is released. - `DEVICE_COUNT` of 0: nothing is called. All 4 new or updated tests fail on the merge base and pass on this branch. Behaviour on CUDA / ROCm is unchanged: there `DEVICE_COUNT == torch.cuda.device_count()` and `clean_gpu_cache()` calls `torch.cuda.empty_cache()`. CUDA no-regression check (B200, vLLM 0.11.2, torch 2.9.0, transformers 4.57.6, TRL 0.24.0): GRPO with `fast_inference=True` and vLLM sleep mode on `trl-internal-testing/tiny-Qwen3ForCausalLM`, 2 steps, save, resume from `checkpoint-2` to step 4. Base and this branch match exactly: `llm.sleep(1)` called, 3 cache flushes, the same bytes released, and identical losses before and after the resume. --------- Signed-off-by: li-lizhe <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Daniel Han <[email protected]>
During GRPO rollout the optimizer state and any pending gradients sit on the GPU, even though nothing reads them until the next optimizer step. With colocated vLLM (
fast_inference = True) that memory competes with the KV cache and the scoring passes. verl offloads the optimizer around generation for the same reason.Setting
UNSLOTH_PARK_OPTIMIZER_DURING_ROLLOUT=1copies every CUDA optimizer state tensor and every pending.gradinto reusable pinned host buffers before_generate_and_score_completions, frees the CUDA blocks, and restores them when the call returns (also when generation raises)._generate_and_score_completionsexists across TRL 0.22.2 to 1.15, so no version-specific hooks are needed.Results
Qwen2.5-0.5B, LoRA r=64,
fast_inference = True(vLLM 0.29), batch 4, gradient accumulation 2, 4 generations, fixed seeds. "Freed" is the drop intorch.cuda.memory_allocatedaround the park call.steps_per_generation = 1CPU tests (
tests/test_grpo_park_optimizer_during_rollout.py) cover the exact round trip, grads released during generation, the off path, shared tensors, the first-step no-op and the gating; all fail on main.Not covered:
UNSLOTH_VLLM_STANDBY=1together with parking, whether the freed bytes become a larger KV cache or a lower peak, and timing.