Skip to content

Block CUDA graphs: copy parameter gradients out of the graph pool - #15207

Merged
danielhanchen merged 5 commits into
mainfrom
dh/s6-fix-cudagraph-grads
Oct 25, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
dh/s6-fix-cudagraph-grads

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow up to #15154. This only affects the opt-in UNSLOTH_BLOCK_CUDAGRAPHS=1.

Problem

With block CUDA graphs on, the compiled backward of a decoder block writes parameter gradients into the cudagraph pool. When .grad is None, AccumulateGrad keeps that buffer as .grad without copying it. The next replay can then overwrite it, for example:

  • the next block's recompute under reentrant checkpointing
  • the next micro step under gradient accumulation

torch raises:

RuntimeError: Error: accessing gradient tensor output of CUDAGraphs that has been overwritten by a subsequent run.

#15154 already clones the block outputs and the hidden_states gradient. It does not clone parameter gradients. This was reproduced for full fine-tuning in fp32, bf16 LoRA, and 2-rank DDP. With the flag off, or with .grad preallocated, the same runs pass.

Fix

The first graph call of each wrapped layer registers one hook per trainable parameter. The hook copies the incoming gradient only when .grad is None, which is the case where AccumulateGrad would keep the pool buffer. Later gradients in the same step are added in place into the owned buffer, and nothing extra is copied. An existing .grad is kept as is (zero_grad(set_to_none=False), DDP bucket views).

The cost is one copy of each trainable parameter's gradient per optimizer step, and only with the flag on. The hooks are not registered with the flag off.

Non-reentrant checkpointing (torch.utils.checkpoint(..., use_reentrant=False)) fails for a second reason. Its saved tensor hooks free recomputed inputs while the block's backward graph is recording, and cudagraph trees raise graph recording observed an input tensor deallocate during graph recording that did not occur during replay. This also happens on main with preallocated grads, so the copy above does not cause it. Inside a non-reentrant checkpoint, the block now runs the graph-free compile for both its forward and its recompute. Unsloth's own checkpointing is reentrant (it turns use_reentrant=False into True), so it keeps graphs.

Tests

tests/test_block_cudagraphs_clone.py, CPU, with a stand-in for the pool: the backward writes the weight gradient into one reused buffer per shape and returns a fresh tensor on that storage, which is what a replay returns.

  • test_param_grads_are_copied_out_of_the_graph_pool[1|2]: reentrant checkpointing, with 1 and 2 micro steps. Each .grad must be off the pool buffer and match an eager reference.
  • test_preallocated_grads_are_accumulated_in_place: an existing .grad keeps its storage and value.
  • test_param_grads_hooked_only_with_graphs
  • test_nonreentrant_checkpoint_runs_without_graphs: the forward and the recompute both take the graph-free compile under use_reentrant=False, and the graph compile under use_reentrant=True.

Results:

  • Before (main): 3 failed (the 2 pool tests and the non-reentrant test), 8 passed.
  • After: 11 passed.
  • tests/test_block_compile.py, discovery, attention dispatch and clone tests: 84 passed, 8 skipped, 1 failed. The failure, test_sm_count_is_read_outside_the_trace, also fails on main on a host with no GPU.

GPU, Colab L4, torch 2.13.0 and 2.14.1

Standalone probe: 4 wrapped decoder layers (Linear 256 + sin), 6 steps, seed 42. Every trainable parameter .grad is read and compared against an fp32 eager reference. Results were the same on both torch versions.

case main, graphs on this PR, graphs on this PR, graphs off
reentrant checkpointing, fp32 full FT FAIL (overwritten) PASS, 15 recorded / 57 replays, max rel err 1.7e-7 PASS, 1.7e-7
reentrant checkpointing, bf16 LoRA FAIL (overwritten) PASS, 15 / 57, 5.6e-3 (same as graphs off) PASS, 5.6e-3
no checkpointing, 2 micro steps FAIL (overwritten) PASS, 8 / 80, 1.8e-7 PASS, 1.8e-7
reentrant checkpointing, 2 micro steps FAIL (overwritten) PASS, 15 / 129, 1.8e-7 PASS, 1.8e-7
non-reentrant checkpointing, fp32 FAIL (overwritten); with preallocated grads, FAIL (input deallocate) PASS, runs without graphs PASS

Step time, Qwen3-0.6B LoRA r16, bs 2, ga 2, seq 512, bf16, Unsloth checkpointing, 50 steps, median of 42 timed steps. One L4 per job; arms ran one after another on the same card.

job graphs off (A/A) graphs on (A/A) delta
this PR 473.7 / 460.5 / 467.0 ms (spread 2.8%) 269.9 / 272.2 / 273.7 ms (spread 1.4%) -41.7%
first commit only, with main graphs on as a control 464.0 / 448.0 / 453.2 ms (spread 3.5%) 271.1 / 273.5 / 273.0 ms; main: 273.3 / 272.6 ms -39.8%, same as main

In every graphs-on arm: 111 graphs were recorded and 8313 replayed, reserved memory stayed flat from step 5 to step 50, and the step 50 loss was within 0.0004 of graphs off.

Not covered

  • The real Unsloth trainer path on main also ran these 50 steps without an error with graphs on. The overwrite was reproduced only with the standalone wrapper probe above, not through UnslothSFTTrainer.
  • DDP / FSDP were not run with this change: no multi-GPU card was used.
  • Parameters that become trainable after the first graph call of a layer are not hooked.

With UNSLOTH_BLOCK_CUDAGRAPHS=1 the compiled backward writes parameter
gradients into the cudagraph pool, and AccumulateGrad keeps that buffer
as .grad. The next replay (reentrant checkpoint recompute, the next
micro step) overwrote it: torch raises "accessing gradient tensor output
of CUDAGraphs that has been overwritten". A per parameter hook now copies
the gradient only when .grad is None; later gradients are added in place
into the owned buffer, and preallocated grads (DDP bucket views) are kept.
torch.utils.checkpoint(use_reentrant=False) frees recomputed inputs
while the block's backward graph records, and cudagraph trees raise
"graph recording observed an input tensor deallocate during graph
recording". This also fails on main with preallocated grads, so it is
not the parameter gradient copy. Its forward and recompute both take the
graph-free compile now; reentrant checkpointing (Unsloth's) keeps graphs.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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 ✅ Completed 2026-10-25T06:19:32.709771Z fe276e0 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. 🎉

Reviewed commit: 85653d6a85

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

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: fe276e0f2e

ℹ️ 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
danielhanchen merged commit f9ee5b8 into main Oct 25, 2026
@danielhanchen
danielhanchen deleted the dh/s6-fix-cudagraph-grads branch October 25, 2026 09:56
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…d LoRA runs (#15768)

## Summary

Block CUDA graphs (`UNSLOTH_BLOCK_CUDAGRAPHS=1`, #15154, #15207, #15352,
#15553) cut LoRA step time by 25 to 57% when a run is launch-bound and
every batch has the same shape. Today they are opt-in, because forcing
them on costs time when the GPU is the bottleneck and when batch shapes
vary. This PR makes the choice automatically, per run, and only turns
graphs on when they are measured to help.

`UNSLOTH_BLOCK_CUDAGRAPHS` now means:

| value | behaviour |
|---|---|
| unset or `auto` (new default) | decided per run, see below |
| `1` | forced on, same as before |
| `0` or anything else | off, same as before (previously every value
other than `1` meant off) |

## How auto decides

1. Static rules, else graphs stay off for the run: CUDA, not ROCm, torch
>= 2.13 (the graphed region gets its own recompile bucket via
`isolate_recompiles`), not distributed, LoRA / QLoRA only (more than
half of a block's weights trainable counts as full finetuning).
2. Probe with graphs off (the same compiled region as before this PR):
every block call must have the batch shape of the first call, and no
call may carry packed / padding-free kwargs, run under non-reentrant
checkpointing, or be a MoE or flex attention block. Any of those turns
auto off for good.
3. Forward passes are counted at the first block's call outside backward
(checkpoint recomputes and the grad-mode trial do not count). Passes 1
and 2 warm up. In pass 3, four block calls are timed: the block's
kernels are queued behind a short `torch.cuda._sleep`, so a CUDA event
pair after the sleep measures GPU time with no launch gaps, while the
host measures how long the launches took. If launching outlasts the
sleep, the GPU time includes gaps, which can only make the ratio
smaller.
4. Graphs turn on at the next forward pass when host launch time >= 1.2
x GPU time and at least max(2 GiB, 10%) of device memory is free. One
line is printed when that happens, naming `UNSLOTH_BLOCK_CUDAGRAPHS=0`.
5. After that the existing safeguards apply unchanged: more than 2 batch
shapes turns graphs off and releases the pool, packed rows turn them
off, MoE / flex blocks run without graphs.

A newly patched model starts a new decision, so a launch-bound model
loaded first cannot turn graphs on for a GPU-bound one.

The 1.2 threshold comes from A100 runs with graphs forced on: ratios
from 0.22 to 0.97 gained nothing (-1.5% to +1.0%), 1.08 gained 5.5%,
1.33 to 1.43 gained 15.7 to 19.6%, and 1.9 or more gained 32 to 57%.

## Results

Colab, torch 2.14.1, transformers 4.57.6, TRL 0.24.0. LoRA r=16 on all
linear layers, `use_gradient_checkpointing="unsloth"`,
`transformers.Trainer`, fixed-length batches, 30 steps. Every run is a
fresh process. Arms are interleaved per config: base (merge base
63b85ca), auto (this PR, env unset), on (this PR, `=1`), base again
(A/A). Times are median step time over steps 8 to 30. Deltas are against
the mean of the two base runs.

Where auto turns graphs on:

| GPU | model | bits | seq | bs | base s | A/A % | auto % | forced on %
| ratio |
|---|---|---|---|---|---|---|---|---|---|
| A100 | Qwen3-0.6B | 16 | 512 | 1 | 0.2224 | 0.2 | -52.9 | -53.9 | 6.54
|
| A100 | Qwen3-0.6B | 16 | 512 | 8 | 0.2329 | 2.1 | -31.8 | -32.8 | 2.00
|
| A100 | Qwen3-0.6B | 16 | 2048 | 1 | 0.2276 | 0.1 | -48.7 | -48.2 |
2.76 |
| A100 | Qwen3-0.6B | 4 | 512 | 1 | 0.2589 | 1.3 | -53.5 | -56.0 | 5.54
|
| A100 | Qwen3-0.6B | 4 | 512 | 8 | 0.2685 | 0.7 | -37.2 | -38.5 | 2.09
|
| A100 | Qwen3-0.6B | 4 | 2048 | 1 | 0.2584 | 1.5 | -50.5 | -51.7 | 3.02
|
| A100 | Llama-3.2-1B | 16 | 512 | 1 | 0.1251 | 1.0 | -54.3 | -54.2 |
3.30 |
| A100 | Llama-3.2-1B | 16 | 512 | 2 | 0.1354 | 0.9 | -49.8 | -50.5 |
1.90 |
| A100 | Llama-3.2-1B | 16 | 512 | 4 | 0.1357 | 1.0 | -19.8 | -19.6 |
1.38 |
| A100 | Llama-3.2-1B | 16 | 2048 | 1 | 0.1353 | 2.0 | -15.4 | -15.7 |
1.33 |
| A100 | Llama-3.2-1B | 4 | 512 | 1 | 0.1409 | 2.4 | -55.9 | -57.5 |
2.62 |
| A100 | Llama-3.2-1B | 4 | 2048 | 1 | 0.1508 | 0.8 | -18.7 | -18.8 |
1.43 |
| L4 | Qwen3-0.6B | 16 | 512 | 1 | 0.2274 | 0.8 | -50.3 | -50.8 | 5.19 |
| L4 | Qwen3-0.6B | 4 | 512 | 1 | 0.2658 | 1.6 | -51.8 | -53.7 | 5.76 |
| L4 | Qwen3-0.6B | 4 | 2048 | 1 | 0.3076 | 0.8 | -3.1 | -3.1 | 1.71 |
| L4 | Qwen3-0.6B | 16 | 2048 | 1 | 0.2972 | 0.1 | -0.3 | -0.3 | 1.49 |
| L4 | Llama-3.2-1B | 16 | 512 | 1 | 0.1490 | 2.5 | -30.0 | -30.3 | 2.26
|
| L4 | Llama-3.2-1B | 4 | 512 | 1 | 0.1642 | 0.6 | -25.0 | -25.2 | 2.04
|
| T4 | Qwen3-0.6B | 16 | 512 | 1 | 0.2213 | 5.7 | -29.1 | -28.8 | 2.15 |
| T4 | Qwen3-0.6B | 4 | 512 | 1 | 0.2531 | 6.5 | -24.3 | -25.9 | 2.34 |

Where auto keeps graphs off (GPU-bound), it matches base inside the A/A
spread, while forcing graphs on costs time:

| GPU | model | bits | seq | bs | base s | A/A % | auto % | forced on %
| ratio |
|---|---|---|---|---|---|---|---|---|---|
| A100 | Qwen3-0.6B | 16 | 2048 | 8 | 0.5526 | 0.1 | -0.0 | +0.6 | 0.55
|
| A100 | Qwen3-0.6B | 4 | 2048 | 8 | 0.5567 | 0.1 | +0.1 | +0.5 | 0.66 |
| A100 | Llama-3.2-1B | 16 | 2048 | 8 | 0.7230 | 0.0 | +0.2 | +1.0 |
0.22 |
| A100 | Llama-3.2-1B | 4 | 2048 | 8 | 0.7286 | 0.0 | -0.0 | +0.7 | 0.25
|
| L4 | Llama-3.2-1B | 16 | 512 | 4 | 0.3481 | 0.1 | +0.0 | +1.5 | 0.67 |
| L4 | Llama-3.2-1B | 16 | 512 | 8 | 0.7083 | 1.1 | +0.2 | +1.6 | 0.31 |
| L4 | Llama-3.2-1B | 16 | 2048 | 1 | 0.3693 | 0.3 | -0.1 | +1.1 | 0.64
|
| L4 | Llama-3.2-1B | 16 | 2048 | 8 | 3.2199 | 1.3 | +1.0 | +2.0 | 0.07
|
| L4 | Llama-3.2-1B | 4 | 2048 | 8 | 3.2285 | 2.0 | +0.9 | +2.7 | 0.08 |
| L4 | Qwen3-0.6B | 16 | 512 | 8 | 0.5153 | 2.0 | +0.7 | +3.6 | 0.80 |
| L4 | Qwen3-0.6B | 4 | 512 | 8 | 0.5288 | 0.4 | -0.2 | +2.9 | 0.91 |
| L4 | Qwen3-0.6B | 16 | 2048 | 2 | 0.5939 | 0.6 | -0.2 | +2.9 | 0.71 |
| L4 | Qwen3-0.6B | 16 | 2048 | 8 | 2.4181 | 0.9 | +0.5 | +2.1 | 0.16 |
| L4 | Qwen3-0.6B | 4 | 2048 | 8 | 2.4317 | 0.7 | +0.7 | +2.8 | 0.18 |
| L4 | Llama-3.2-1B | 4 | 2048 | 1 | 0.3901 | 0.3 | -0.1 | +0.8 | 0.72 |
| L4 | Llama-3.2-1B | 4 | 512 | 8 | 0.7393 | 0.6 | +0.2 | +1.4 | 0.34 |
| T4 | Llama-3.2-1B | 4 | 512 | 1 | 0.2574 | 2.1 | +0.8 | +1.2 | 0.82 |
| T4 | Qwen3-0.6B | 16 | 2048 | 1 | 0.6802 | 1.2 | +0.9 | +3.2 | 0.69 |
| T4 | Qwen3-0.6B | 4 | 2048 | 4 | 2.5835 | 0.1 | -0.1 | +0.7 | 0.17 |

The L4 gray zone: on L4, block ratios of 1.49 to 1.71 turned graphs on
for little or nothing (-3.1% to +0.5%), while on A100 ratios of 1.33 to
1.43 gave 15 to 20%. None of these cases is slower than base beyond the
A/A spread, so the threshold stays at 1.2 and keeps the A100 gains. The
price on L4 there is 0.3 to 0.5 GB more reserved memory.

Other checks:

- Variable padded lengths (pad to the longest row of each batch): auto
stays off (`batch shape changed`), +0.5% on A100 and -0.6% on L4 (A/A
1.0% and 0.1%). Forced on recorded 189 graphs and was 4.3% (A100) and
1.5% (L4) slower.
- `use_gradient_checkpointing=True` (torch reentrant) and `False`: auto
on, -50.6% and -45.4% on A100, +0.5% and -1.1% on L4 (single base run,
ratios 1.58 / 1.59), losses within the A/A band.
- Full finetuning: auto stays off by rule (forced on was 10.7% faster on
A100, but full-finetune losses are not reproducible enough between two
base runs to check parity, so it is left out).
- torch 2.10: FastLanguageModel LoRA blocks are not compiled before
2.11, so graphs never engage. All 2.10 arms match base within A/A (A100
and L4).
- Recordings after step 5: 0 in every auto-on run (no recapture churn).
- Loss parity: the largest |loss diff| between auto and base over 30
steps is in the same range as base vs base (about 1e-3 for bf16). Runs
are not bitwise identical, and neither are two base runs.
- Memory: when auto turns graphs on, peak reserved goes up by 0.1 to 0.8
GB. When it keeps them off, peak memory is identical to base.
- One-time cost: the graphed region compiles and records at pass 4. With
a cold Inductor cache (Qwen3-0.6B, A100), that step takes 5.1 s, so a
30-step run is 2 s longer in total and the graphs pay for themselves
after about 45 steps. Timing adds one sync and four short GPU sleeps
(about 10 ms each), once.
- `tests/test_block_cudagraphs_gpu.py` (real cudagraph trees, reentrant
checkpointing and gradient accumulation weights match eager) passes on
A100, L4 and T4 with torch 2.14.1, and on A100 and L4 with torch 2.10.0.

## Tests

`tests/test_block_cudagraphs_auto.py` (CPU, fake compile and a stubbed
timer): mode parsing, the on path at a pass boundary, GPU-bound, the
ratio threshold, a shape change while probing, the shape cap after on,
packed rows, low free memory, static rules (torch floor, full
finetuning, distributed), recomputes not counted as passes, explicit off
never probing, a new model deciding again, and the hidden-states forward
hook being installed only where auto can turn graphs on (not on ROCm or
torch < 2.13). These fail on the base commit and pass here.
`test_block_cudagraphs_clone.py`, `test_block_compile.py`,
`test_block_compile_discovery.py`,
`test_legacy_block_compile_install.py` and
`test_attention_dispatch_compiled_block.py` pass, except
`test_sm_count_is_read_outside_the_trace`, which fails the same way on
the base commit.

## Not covered

- torch 2.13 is allowed by the floor but was not measured. Only 2.14.1
was measured with graphs engaged.
- G4 / Blackwell and H100 were not measured.
- Distributed runs, full finetuning and torch < 2.13 keep the old
behaviour (off unless `=1`).
- Models other than Qwen3-0.6B and Llama-3.2-1B were not measured. MoE
and flex attention blocks never use graphs.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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