Skip to content

GRPO: opt-in parking of optimizer state and gradients on host during rollout - #13866

Merged
danielhanchen merged 6 commits into
mainfrom
dh/opt-park-during-rollout
Oct 16, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
dh/opt-park-during-rollout

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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=1 copies every CUDA optimizer state tensor and every pending .grad into reusable pinned host buffers before _generate_and_score_completions, frees the CUDA blocks, and restores them when the call returns (also when generation raises).

  • Tensors shared between parameters, such as the bitsandbytes quantization maps, are parked once and stay shared after the restore.
  • bitsandbytes paged state is skipped (bnb pages it itself).
  • DeepSpeed, FSDP and multi-process runs are skipped: they own their state layout, and DDP may keep grads as bucket views.
  • The first step, before any optimizer state exists, is a no-op.
  • With the variable unset, nothing changes: the wrapper reads one env var and calls nothing new.

_generate_and_score_completions exists 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 in torch.cuda.memory_allocated around the park call.

Arm Optimizer Parks Freed per park Step losses / grad norms
off (A/A, 2 runs) adamw_8bit 0 n/a reference, identical
on adamw_8bit 4 72 MB (0 on step 1) identical to off
off adamw_torch 0 n/a reference
on adamw_torch 4 282 MB (0 on step 1) identical to off
on, steps_per_generation = 1 adamw_torch 7 282 MB / 422 MB (pending grads mid-accumulation) identical to off

CPU 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=1 together with parking, whether the freed bytes become a larger KV cache or a lower peak, and timing.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-16T01:18:39.641199Z 30c736e New commits
🔒 Security Review ⚠️ Failed 2026-10-15T14:59:45.052036Z b318960 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/rl.py Outdated
Comment on lines +897 to +898
torch.cuda.synchronize()
torch.cuda.empty_cache()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread unsloth/models/rl.py
Comment on lines +884 to +886
for name, value in state.items():
if _is_parkable_tensor(value):
states.append((state, name, park(value, (id(param), name))))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread unsloth/models/rl.py
Comment on lines +851 to +854
return (
isinstance(value, torch.Tensor)
and value.is_cuda
and not getattr(value, "is_paged", False)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c0a3c1d: only strided CUDA tensors are parked; sparse grads stay where they are.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/rl.py Outdated
# 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c0a3c1d: every device that holds a parked tensor is synchronized before empty_cache.

Comment thread unsloth/models/rl.py
Comment on lines +861 to +862
optimizer = trainer.optimizer
optimizer = getattr(optimizer, "optimizer", optimizer)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c0a3c1d: layer-wise optimizers (optimizer_dict) are declined explicitly with the same message rather than reported as a successful no-op.

Comment thread unsloth/models/rl.py
Comment on lines +872 to +875
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: c0a3c1d761

ℹ️ 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".

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 28f734fbcb

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@danielhanchen
danielhanchen merged commit c7824b0 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/opt-park-during-rollout branch October 16, 2026 03:29
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 19, 2026
…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.
danielhanchen added a commit that referenced this pull request Oct 20, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant