Skip to content

Block CUDA graphs: hook gradients of adapters that become trainable after the first graphed call (DPO crash) - #18496

Merged
danielhanchen merged 2 commits into
mainfrom
w20a-dpo-block-cudagraphs
Nov 19, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
w20a-dpo-block-cudagraphs

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Block CUDA graphs: copy the trained adapter's grads out of the graph pool after a reference forward

Problem

With the default UNSLOTH_BLOCK_CUDAGRAPHS=auto, DPO with a PEFT model and ref_model=None crashes once block CUDA graphs turn on:

RuntimeError: Error: accessing gradient tensor output of CUDAGraphs that has been overwritten by a subsequent run.
  File ".../torch/nn/utils/clip_grad.py", line 95, in _get_total_norm

On an L4 (TRL 1.14.2, transformers 5.18) the process then segfaulted.

Root cause

_param_grads_out_of_pool registers a hook that copies each parameter's first .grad out of the CUDA graph pool. It ran once per layer, on the first graphed call, and only hooked the parameters that had requires_grad set at that moment.

TRL's DPOTrainer computes the reference log probs under use_adapter(model, "ref"), which calls PEFT's set_adapter("ref"). When there is no "ref" adapter it uses disable_adapter() instead. Both turn requires_grad off for the trained default adapter. Auto mode switches graphs on at the start of a forward pass, and in DPO that pass is the reference forward. So the hooks were attached to the ref weights, and the default LoRA grads stayed in pool memory. The next replay overwrote them before clip_grad_norm read them.

Fix

  • At every grad-mode graphed call, hook each parameter that requires grad and has no hook yet. Each parameter is hooked once, tracked by a per-layer dict of weakrefs. No-grad calls make no parameter gradient, so they skip this step.
  • The cached per-layer parameter list (shared with _trainable) is rebuilt after a global module or parameter registration. A parameter or adapter added after the first graphed step therefore gets its hook too.

Tests

  • New tests/test_block_cudagraphs_adapter_switch.py (CPU, pool stand-in like test_block_cudagraphs_clone.py).
    • On main: 3 failed, 1 passed. With this change: 4 passed.
    • Covers a reference forward under set_adapter("ref") first, disable_adapter first, an adapter added after graphed training, and one hook per parameter.
  • test_block_cudagraphs_clone.py, test_block_cudagraphs_auto.py, test_block_cudagraphs_side_grad.py and test_block_compile.py all pass: 152 passed, 21 skipped.

GPU check

Correctness only: tiny Qwen3 (8 layers, hidden 256), LoRA r=8, Unsloth gradient checkpointing, 10 steps, max_grad_norm=1.0.

stack arm result
TRL 1.18.0 + transformers 5.23.0 main, auto crash in clip_grad_norm (0 of 112 default LoRA weights hooked, 112 of 112 ref)
TRL 1.18.0 + transformers 5.23.0 this PR, auto / forced on / off trains; losses and grad norms bit-identical across the three arms
TRL 1.14.2 + transformers 5.18.0 main, auto same crash
TRL 1.14.2 + transformers 5.18.0 this PR, auto / off trains; bit-identical

Other trainers:

  • ORPO and SFT (graphs on): train.
  • SFT: losses equal between main and this PR.
  • KTO with graphs forced on: identical on main and this PR. Its first graphed call is a policy forward, so it did not hit the bug.

…e forward

TRL's DPOTrainer scores the reference with PEFT set_adapter("ref") or
disable_adapter, which flips requires_grad off on the trained adapter.
When auto mode turned graphs on at a reference forward, the copy-out
hooks were registered once, only on the parameters requiring grad then
(the "ref" adapter), so the trained adapter's .grad stayed in the CUDA
graph pool and clip_grad_norm read memory the next replay had
overwritten.

Register the hooks at every grad-mode graphed call for every parameter
that requires grad and has none yet, and rebuild the cached block
parameter list after a module or parameter registration (a new adapter).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T15:59:55.874024Z 09a8587 Manual request
ℹ️ 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

Copy link
Copy Markdown

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

Reviewed commit: 09a858737b

ℹ️ 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 added a commit that referenced this pull request Nov 19, 2026
## Summary

`Repo tests (CPU, studio)` fails on `main` (seen on #18496, whose base
already has #18490):

```
FAILED tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe
E       utils/test_rocm_sdpa_check.py:348: torch.cuda.is_available()
E       utils/test_rocm_sdpa_check.py:356: torch.cuda.is_available()
```

## Root cause

#18453 added `tests/utils/test_rocm_sdpa_check.py` with two GPU tests
gated on `torch.cuda.is_available()`.
`tests/_zoo_aggressive_cuda_spoof.py` patches that probe to `True`
process-wide, so on a CPU runner these tests un-skip and launch the SDPA
self-check children whenever they share a pytest session with the
spoofing suites. The guard caught it; the ROCm change itself is
unaffected.

## Changes

- Both skips now gate on `has_real_cuda()` first (`not has_real_cuda()
or not torch.cuda.is_available()`). `has_real_cuda()` records
`torch.cuda.is_available()` before any spoof, so it stays true on a real
ROCm or CUDA host, where these tests still run.

## Testing

- `pytest tests/utils/test_rocm_sdpa_check.py
tests/python/test_accelerator_skip_guards.py`: 48 passed, 2 skipped (the
two GPU tests, on this CPU host). The guard fails on `main` with the
error above.
@danielhanchen
danielhanchen merged commit 91211c7 into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the w20a-dpo-block-cudagraphs branch November 19, 2026 17:56
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