Skip to content

Opt-in CUDA graphs for compiled blocks under gradient checkpointing (UNSLOTH_BLOCK_CUDAGRAPHS=1) - #15154

Merged
danielhanchen merged 7 commits into
mainfrom
dh/s6-cudagraph
Oct 24, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
dh/s6-cudagraph

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Opt-in CUDA graphs for compiled decoder blocks (UNSLOTH_BLOCK_CUDAGRAPHS=1)

With UNSLOTH_BLOCK_CUDAGRAPHS=1 set, each compiled decoder block is captured as a CUDA graph and replayed. One graph launch then replaces about 58 kernel launches per block call on Qwen3, which matters when a step is limited by the host launching kernels. On Qwen3-0.6B LoRA at sequence length 512, a step is 40% faster on an L4 and 59% faster on an A100. Losses match the default path. The flag is off by default, and with it off the code path is the same as main.

Why the flag needs more than triton.cudagraphs

Turning on triton.cudagraphs alone fails under Unsloth gradient checkpointing:

  • The checkpointed forward runs each block under no_grad. Each block call is a separate compiled invocation with no pending backward. As a result, every call starts a new cudagraph tree generation, and the next block's replay overwrites the previous block's outputs.
  • The checkpoint keeps the raw block input when it is 2 MiB or smaller (always true for the last layer). The recompute in backward then reads an output that has already been overwritten. torch raises accessing tensor output of CUDAGraphs that has been overwritten.
  • Backward has the same problem with the input gradient a block returns.

When graphs are on, the wrapper now clones the block outputs, and an identity autograd function clones the input gradient. Two other options were tried and both still fail: cloning the outputs alone, and torch's cudagraph_trees_generation_cloning="user_visible".

Variable-length batches (rows padded to the batch maximum) would record a new set of graphs for every new length. On an L4 that made steps 3.5x slower, and the graph pool grew on every step. Two limits handle this:

  • Only the first UNSLOTH_BLOCK_CUDAGRAPHS_MAX_SHAPES block input shapes (default 8) record graphs.
  • Once one more shape arrives, that layer kind turns graphs off for good and runs the same compiled block without them.

Without the second limit, shapes that had already been recorded kept recording again at new tree positions, so memory still grew.

Results

Setup: Qwen3-0.6B LoRA r16, bs 2, ga 2, adamw_8bit, Unsloth GC, 50 steps (5 warmup), synthetic fixed data, torch 2.14.1, transformers 5.17.0, TRL 1.15.0. Base is main with no flag. Arms ran back to back in one VM per tier, in ABBA order. Step time is the median of 42 timed steps per run. Spread is the max-min range of the per-run medians.

GPU, config base ms (runs, spread) graphs ms (runs, spread) change
L4 bf16 s512 456.8 (3, 1.2%) 275.2 (3, 3.2%) -39.7%
L4 bf16 s512, after the shape cap 455.8 (2, 0.3%) 274.4 (2, 0.3%) -39.8%
L4 bf16 s512, final commit 452.0 (1) 268.0 (1) -40.7%
L4 bf16 s2048 1165.2 (2, 0.2%) 1192.7 (2, 0.1%) +2.4%
A100 bf16 s512 448.6 (2, 0.8%) 185.5 (2, 1.4%) -58.6%
A100 bf16 s2048 471.0 (2, 0.1%) 340.8 (2, 0.1%) -27.6%
L4 QLoRA 4-bit s512 524.5 (1) 280.3 (1) -46.6%
L4 lora_dropout 0.05 s512 473.6 (1) 291.1 (1) -38.5%
L4 GC off s512 314.2 (1) 210.3 (1) -33.1%
L4 variable lengths, padded, 300 steps, final commit 462.8 (1) 460.5 (1) -0.5%
T4 fp16 + GradScaler s512 550.1 (3, 7.7%) 567.7 (3, 9.8%) +3.2%, inside noise

On an L4 at s512, host-side launch calls per step drop from 10996 to 1588. Kernels per step go up by about 11% because of the clones. At s2048 the L4 is already GPU-bound, so the clones make it 2.4% slower. That is why the flag stays opt-in.

Memory (peak allocated / peak reserved GB, base then graphs):

  • L4 s512: 1.88 / 1.89, then 1.98 / 2.38 to 2.42.
  • L4 s2048: 1.87 / 1.90, then 2.09 / 2.68 to 2.70.
  • QLoRA: 1.30 / 1.31, then 1.40 / 1.78.
  • GC off: 2.87 / 2.88, then 3.28 / 3.38.
  • Variable lengths, 300 steps: 1.88 / 1.93, then 1.88 / 2.06.

With fixed shapes, 111 graphs are recorded on the first step and then replayed; the count does not change after that. Reserved memory is flat from step 5 to step 50. In the 300-step variable-length run, reserved memory stays at 2106 to 2108 MiB from step 30 to step 300. Before the second limit it grew about 1.4 MiB per step (2220 to 2630 MiB). Before any limit it grew from 1432 to 2488 MiB in 50 steps, after 7113 recordings.

Correctness

  • The step-1 loss is identical in every arm. Step-1 grad norms are within 2e-4 of base, and base against base differs by up to 6e-4.
  • Fixed shapes, 50 steps: the largest per-step loss difference against base is 0.0013 to 0.0035. Base against base is 0.0017 to 0.0072. The mean is 0.0004 in both cases.
  • T4 fp16 with GradScaler: every loss is finite. The largest difference against base is 0.0006 to 0.0009, and base against base is 0.0006.
  • Variable lengths: the mean per-step difference is 0.0007 against base, while base against base is 0.0005 and graphs against graphs is 0.0005. The calls past the cap run a separately compiled block, so a small codegen difference is expected here.
  • Each graphs arm counted cloned outputs (5628) and input-gradient clones (2800), and replays were above 0 (8313). With the flag off, the head file gives the same numbers as base (449.0 ms, 0 graphs).

Tests

tests/test_block_cudagraphs_clone.py (CPU) covers:

  • the clone autograd function;
  • output cloning;
  • the env flag;
  • the shape cap: shapes up to the cap use graphs, and the first shape past it turns graphs off for every later call;
  • parsing of the cap env var.

tests/test_block_compile.py gives the same result as on main: test_sm_count_is_read_outside_the_trace fails on this CPU host on main too.

Not covered

  • Padding-free and packing batches do not use block compile at all, because packed_seq_lengths keeps the stock forward. The flag changes nothing there: same speed and memory, 0 graphs. Unsloth turns padding-free on by default for SFT, so in that default setup the flag has no effect.
  • Not run:
    • multi-GPU (DDP, FSDP2);
    • GRPO / DPO;
    • MoE, vision and other architectures;
    • H100 / B200;
    • torch versions other than 2.14.1;
    • runs longer than 300 steps.
  • LoRA dropout was checked only through the loss curve, not by comparing the dropout mask between the checkpointed forward and its recompute.
  • The s2048 arms do offload block inputs, and those runs matched. A race between an offloaded input and the next replay is not ruled out in general.
  • No rule for turning this on automatically was found to be safe. On the L4 at s2048 it is slower, and every arm uses 0.5 to 0.8 GB more reserved memory.

UNSLOTH_BLOCK_CUDAGRAPHS=1 turns on triton.cudagraphs for the per-layer compiled
blocks. Under Unsloth checkpointing every block call starts a new cudagraph tree
generation, so the next replay overwrote block outputs the checkpoint saved and
the input gradient handed to the previous block. Both are now cloned out of the
graph pool whenever block cudagraphs are on.
With UNSLOTH_BLOCK_CUDAGRAPHS=1 every new block input shape recorded a fresh graph set. On
variable-length batches that made steps 3.5x slower and grew the graph pool every step (L4,
Qwen3-0.6B LoRA, 262 shapes and 7113 graphs in 50 steps). Only the first
UNSLOTH_BLOCK_CUDAGRAPHS_MAX_SHAPES (default 8) shapes now record graphs; later shapes run the
same compiled block without graphs.
Admitted shapes kept recording at new cudagraph tree positions after the cap, so the pool still
grew about 1.4 MiB per step over 300 variable-length steps on an L4. One shape past the cap now
runs every later call of that layer kind through the compiled block without graphs.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T19:50:24.494223Z 7ba5f58 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 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: af748474b9

ℹ️ 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 tests/test_block_cudagraphs_clone.py Outdated

import torch

from unsloth.models import _block_compile as bc

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 Load the block module without importing the GPU package

On a CPU-only test runner, this top-level import initializes unsloth and fails during collection: tests/conftest.py explicitly sets UNSLOTH_DISABLE_CPU_FALLBACK=1 so importing the package without an accelerator is rejected. Consequently, these CPU-only regression tests cannot run and also interrupt collection of other tests. Load _block_compile.py directly by file path, as tests/test_block_compile.py does, instead of importing through unsloth.models.

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 test now loads unsloth/models/_block_compile.py by file path (the same loader tests/test_block_compile.py uses) instead of importing through unsloth.models, so it collects and runs on a CPU-only runner with UNSLOTH_DISABLE_CPU_FALLBACK=1 (5 passed there without UNSLOTH_ALLOW_CPU).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 7ba5f58d7d

ℹ️ 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 8feaae2 into main Oct 24, 2026
@danielhanchen
danielhanchen deleted the dh/s6-cudagraph branch October 24, 2026 20:50
danielhanchen added a commit that referenced this pull request Oct 24, 2026
## Summary


`tests/test_block_cudagraphs_clone.py::test_new_shapes_past_the_cap_skip_graphs`,
added by #15154, fails in the `Repo tests (CPU, rest)` shard (for
example #15162):

```
tests/test_block_cudagraphs_clone.py:108: in test_new_shapes_past_the_cap_skip_graphs
    assert step(16) == {"graphs"}
E   AssertionError: assert set() == {'graphs'}
```

That shard runs with `UNSLOTH_COMPILE_DISABLE=1`. The wrapped block's
`forward` checks `_enabled()` on every call and takes the eager path
when the kill switch is set. So the fake `torch.compile` the test
installs is never called, and it records no call. The product is right:
the kill switch is supposed to win. The test assumed compile was on. It
passes locally with the variable unset and fails with it set to `1`.

## Change

- Same autouse fixture as `tests/test_block_compile.py`: clear
`UNSLOTH_BLOCK_COMPILE`, `UNSLOTH_COMPILE_DISABLE` and
`UNSLOTH_FORCE_FLOAT32` for each test.
- The layer/step setup moved into `_cap_layer_step()`, so a second test
can use it.
- `test_compile_disable_still_bypasses_the_block`: sets the kill switch
after the block is wrapped and checks that the next call skips the
compiled path. This pins down the behaviour the old test tripped over.

## Verification

- `UNSLOTH_COMPILE_DISABLE=0` and `=1`: `6 passed` both ways. On main
the `=1` case is `1 failed, 4 passed`.
- Sabotage 1: with the fixture not autouse, under
`UNSLOTH_COMPILE_DISABLE=1`, `test_new_shapes_past_the_cap_skip_graphs`
fails again with the CI error.
- Sabotage 2: with the `_enabled()` check removed from the block's
`forward`, `test_compile_disable_still_bypasses_the_block` fails.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 24, 2026
…torch 2.13+ (unslothai#15157)

## Block compile: per-region recompile limit (torch 2.13+)

Each compiled decoder block (`unsloth/models/_block_compile.py`) shared
the process-wide dynamo `recompile_limit`, which unsloth-zoo raises to
1024. So a block whose guards fail on every call (a guarded attribute or
input that changes each step) could compile up to 1024 times before
falling back to eager. On a real model each compile takes seconds, which
looks like a hang. `_raise_cache_limit` also changed the global limit
for every other compiled function in the process.

torch 2.13 added `torch.compile(..., isolate_recompiles=True,
recompile_limit=N)`. This PR uses it when `torch.compile` accepts both
keywords (checked once with `inspect.signature`):

- every block class gets its own cache bucket and `recompile_limit =
max(8 * kinds + 8, 16)`, where `kinds` is the number of layer kinds of
that class, i.e. twice the 4-per-kind budget `_raise_cache_limit`
already assumed, plus slack. `UNSLOTH_BLOCK_COMPILE_RECOMPILE_LIMIT`
overrides it.
- `_raise_cache_limit` no longer runs on 2.13+, so the global limit is
left alone.
- On torch before 2.13 the `torch.compile` call and the global bump stay
exactly as they were.

Past the limit, dynamo warns and runs that region eager. Without
`fail_on_recompile_limit_hit` it does not raise, even under the
`suppress_errors=False` patch in the first-call path, so `_wrap` does
not read a limit hit as a compile failure and demote the layer.

### Evidence (CPU, torch 2.13.0)

Storm toy block, global `recompile_limit=1024`, 40 calls, each with a
new guard value:

| tree | compiles | outputs |
|---|---|---|
| base (main) | 40 (one per call, capped only at 1024) | correct |
| this PR | 16 (region limit), then eager | correct |

Two classes that share one code object: the storm region stops at 16,
the other region still compiles (1 entry), nothing is stored in the
default bucket, and a user `torch.compile` of the same function still
compiles.

Legitimate entries per region on tiny real models (eager backend, train
steps at (bs, L) = (2,16), (2,24), (2,33), (1,40), (3,17), plus a
no_grad pass, with reentrant and non-reentrant checkpointing):

| model | kinds | entries (reentrant / non-reentrant) | limit |
|---|---|---|---|
| Llama | 1 | 5 / 4 | 16 |
| Qwen3 | 1 | 5 / 4 | 16 |
| Gemma3 | 1 | 5 / 4 | 16 |
| Gemma2 | 2 | 5 / 4 | 24 |

New test `test_recompile_storm_stops_at_the_region_limit` in
`tests/test_block_compile.py`. The CPU block compile suites
(`test_block_compile.py`, `test_block_compile_discovery.py`,
`test_legacy_block_compile_install.py`, `test_fsdp2_native_units.py`,
`utils/test_hybrid_packing_default.py`): 152 passed, 6 skipped on both
base and head. `test_sm_count_is_read_outside_the_trace` fails on both,
because it needs a CUDA device and this host has none.

### Not covered

- No GPU run. The entry counts above come from the eager backend on CPU.
The flex SPLIT retry can double a class's entries on GPU (the limit
allows for that), but I did not measure it.
- If a user turns on `fail_on_recompile_limit_hit`, a storm block now
raises at 16 instead of at 1024.


## Follow-up (df4a21e)

- Measured compiled graphs per block region on GPU for 17 workloads (SFT
padded / packed, eval loop, GRPO notebook flow, DPO, vision SFT, QLoRA,
GC on / off; Llama, Qwen3, Gemma3, hybrid Qwen3.5) on torch 2.14:
one-kind models use at most 4, Gemma3 (2 kinds) SFT 12, DPO 14, GRPO 20
(flat from step 2 to 30). Counts are identical with and without this PR
and no region hit its limit; step time on L4 ABBA +2.0% inside a 5.3%
A/A spread.
- Gemma3 GRPO left only 4 graphs of headroom under the first limit, so
the default is now `max(16 * kinds + 16, 32)` (32 for one kind, 48 for
two).
- Main now has the opt-in `UNSLOTH_BLOCK_CUDAGRAPHS` (unslothai#15154), which
adds a graphs-off compile per block; it now gets the same
`isolate_recompiles` / `recompile_limit` (new test
`test_graphs_off_compile_gets_the_same_region_limit`, fails without it).
- torch < 2.13 is unchanged (same compile kwargs and the global limit
bump).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…slothai#15207)

Follow up to unslothai#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.
```

unslothai#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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…P2 kept weights, drop unneeded copies (#15352)

`UNSLOTH_BLOCK_CUDAGRAPHS=1` (opt-in,
`unsloth/models/_block_compile.py`) records one CUDA graph tree per
compiled decoder block. A Kaggle T4x2 matrix (single GPU, DDP, native
FSDP2; LoRA, QLoRA, full finetune; GC off / unsloth / hf; fixed and
variable padded lengths) found it never faster on a T4, 1.3 to 2.0x
slower in total with variable padded lengths, +0.5 to 1.2 GB reserved
per rank, +3 to 4.75 GB reserved once graphs turned off, one OOM, and
1.64 GiB of fp32 block weights kept gathered per rank under a sharded
FSDP2 full finetune. This PR removes those costs where graphs cannot
help, and keeps them where they can.

With the flag unset nothing changes: every new branch sits behind the
flag.

## Changes

1. Decide before recording.
- Packed / padding-free rows (`packed_seq_lengths`, `cu_seq_lens_q`,
`cu_seq_lens_k`, `cu_seqlens` in the layer kwargs) turn graphs off at
the first call, before anything is recorded, with one rank-0 notice. On
Unsloth's own forwards packed rows already ran the stock forward, so
graphs never engaged there. On transformers forwards the total length
changes every step, so each step recorded a new graph. The notice now
says so.
- The shape cap drops from 8 to 2: one fixed length plus a short last
batch. On a T4 the 8 admitted lengths re-recorded at every new length,
and that cost 15 to 65 s over 40 steps.
`UNSLOTH_BLOCK_CUDAGRAPHS_MAX_SHAPES` still overrides it.
- Past the cap, graphs go off for every block class at once, with one
rank-0 notice. All classes share one cudagraph tree, and so one pool,
per device. Before, the cap was per class.
2. Release the pool. Once graphs are off, the next block call frees the
tree with `torch._inductor.cudagraph_trees.reset_cudagraph_trees()`,
then runs `torch.cuda.empty_cache()`. Before, the pool stayed reserved
after graphs turned off: 3.08 to 4.75 GB on a T4, and one OOM in a DDP
full finetune with variable lengths and GC off.
- `reset_cudagraph_trees()` shuts down every device's tree. A tree
function called after that fails in `CUDAGraphTreeManager.run` with
"Running CUDAGraph after shutdown"
(`torch/_inductor/cudagraph_trees.py`: 2.10 L2030, 2.13 L2175, 2.14
L2403). So it runs only when all of these hold:
- every function in the tree came from a block compile. Each graphed
block call records the compile ids of the tree functions it created,
from `manager.ids_to_funcs` / `manager.id_to_compile_id`. The backward
of the same compile shares its compile id;
     - `running_forwards_with_pending_backwards` is false;
     - `live_cudagraph_pool_storages_in_curr_execution()` is empty.
- If another region records into the tree (a user's
`mode="reduce-overhead"`), the pool is kept and a notice says why. A
pending backward or a tensor still alive in the pool postpones the
release to a later block call.
- Source references: `reset_cudagraph_trees` is at 2.10 L304, 2.13 L350
and 2.14 L362; `shutdown` is at 2.10 L2205, 2.13 L2374 and 2.14 L2620.
3. Native FSDP2: cap what is kept gathered.
`_keep_unsharded_for_block_cudagraphs` now adds up the bytes it would
keep per rank before keeping anything.
- Over `UNSLOTH_BLOCK_CUDAGRAPHS_FSDP2_KEEP_GB` (default 0.5 GiB),
nothing is kept. Those blocks are marked and run their graphs-off
compile, with one rank-0 notice. Without kept weights, graphs would
re-record every step.
- LoRA keeps only the adapters (Qwen3-0.6B: 38 MiB), so it stays under
the budget.
- The sharded full finetune kept 1.64 GiB fp32 per rank for graphs that
measured the same speed. It is now over the budget.
- The byte count read `orig_dtype` / `param_dtype`, which FSDP2 sets
only at lazy init (the first forward). It always printed 0.00 GiB. It
now reads the mixed-precision policy, else the sharded dtype, and prints
small sizes in MiB.
4. Drop copies out of the pool outside checkpointing. Block outputs and
input gradients are no longer cloned for a grad-mode call outside
backward:
- in that case `CUDAGraphTreeManager.run` marks a forward as pending
(2.10 L2037, 2.13 L2182, 2.14 L2410);
- `can_start_new_generation` then starts no new generation until a
backward runs (2.10 L2377, 2.13 L2557, 2.14 L2820);
- the next block and the backward therefore read those outputs and
gradients inside the same generation.

Checkpointed blocks still copy: their forward runs without grad, and
their recompute runs inside backward (`torch._C._current_graph_task_id()
!= -1`), and both can start a generation. Frozen calls (inference
graphs) also still copy, and so does the grad-mode trial that runs
before a checkpointed block's first call. That trial stands in for the
recompute. Parameter gradients are still copied on their first write,
because they live across generations under gradient accumulation.

## Tests

CPU (torch 2.10.0, 2.13.0 and 2.14.1 venvs):
- `tests/test_block_cudagraphs_clone.py` 29 passed on each version. Of
these, 16 fail on main.
- The updated `tests/test_fsdp2_native_block_cudagraphs_gloo.py` (gloo,
world 2) 11 passed on each version. The over-budget test fails on main,
which keeps the weights.
- `tests/test_block_compile.py` failures are the same on main and on
this branch: 4 on 2.10 and 1 on 2.13 / 2.14
(`test_sm_count_is_read_outside_the_trace`, plus the decode-aware MoE
outer-compile tests on 2.10).

GPU (`tests/test_block_cudagraphs_gpu.py`, real cudagraph trees; torch
2.10.0, 2.13.0 and 2.14.1, on a Colab A100-40GB and an L4):

| test | this branch | main |
|---|---|---|
| fixed shape, no checkpointing, gradient accumulation 2: replays, no
re-recording after warm-up, weights match eager, no copies | pass |
fail: 36 output copies in 6 steps |
| reentrant checkpointing: copies, matches eager | pass | pass |
| variable lengths, cap 2: off at the third length, nothing recorded
after, pool released | pass | fail: 172 MiB still reserved after
`empty_cache()` |

## Where block graphs pay (timing)

Setup:
- Qwen3-0.6B and Qwen3-1.7B LoRA (r 16, all linear), bf16, fixed-length
rows of exactly `seq` tokens, 60 steps.
- Steady ms/step is the median from step 10 on, skipping any step that
recorded or recompiled.
- Each arm is a fresh process with fresh compile caches. Arms are
interleaved on one exclusive Colab card per tier. Each repeat runs main
graphs off (M0), main graphs on (M1), branch graphs off (B0) and branch
graphs on (B1) in a rotating ABBA order.
- B0 against M0 is the A/A check: with the flag unset the branch is
byte-identical. It stayed within 0.98 to 1.02.
- 95% CI is a bootstrap over 3 paired repeats.
- Software: torch 2.14.1+cu130, transformers 5.17.0, TRL 1.15.0, PEFT
0.21.2.

Tiers:
- A100 is a Colab A100-SXM4-40GB on a 12 vCPU host;
- G4 is an RTX PRO 6000 Blackwell;
- L4 ran Qwen3-0.6B only;
- H100 was not available on either account (two tries).

Graphs on / off on this branch (B1/B0, below 1 = graphs faster), and
this branch / main with graphs on (B1/M1), single GPU:

| model | seq | bs | GC | A100 ms/step off -> on (branch) | A100 on/off
[CI] | A100 branch/main on [CI] | G4 ms/step off -> on (branch) | G4
on/off [CI] | G4 branch/main on [CI] | L4 ms/step off -> on (branch) |
L4 on/off [CI] | L4 branch/main on [CI] |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0.6B | 256 | 1 | off | 164 -> 79 | 0.48 [0.48, 0.49] faster | 0.95
[0.93, 0.97] faster | 47 -> 24 | 0.52 [0.51, 0.54] faster | 1.00 [0.97,
1.05] same | 163 -> 83 | 0.51 [0.50, 0.52] faster | 0.97 [0.95, 0.98]
same |
| 0.6B | 256 | 1 | unsloth | 234 -> 118 | 0.50 [0.49, 0.50] faster |
1.02 [1.02, 1.02] slower | 71 -> 38 | 0.53 [0.52, 0.54] faster | 1.05
[1.02, 1.10] same | 234 -> 120 | 0.51 [0.51, 0.53] faster | 1.01 [1.00,
1.02] same |
| 0.6B | 256 | 4 | off | 162 -> 80 | 0.50 [0.49, 0.50] faster | 0.98
[0.97, 0.99] same | 47 -> 31 | 0.68 [0.66, 0.70] faster | 0.98 [0.98,
0.98] same | 166 -> 102 | 0.62 [0.61, 0.62] faster | 0.99 [0.99, 1.00]
same |
| 0.6B | 256 | 4 | unsloth | 228 -> 118 | 0.51 [0.51, 0.52] faster |
1.03 [1.03, 1.04] slower | 68 -> 39 | 0.57 [0.56, 0.58] faster | 1.00
[0.99, 1.00] same | 237 -> 137 | 0.58 [0.58, 0.58] faster | 1.00 [1.00,
1.01] same |
| 0.6B | 512 | 1 | off | 161 -> 77 | 0.48 [0.47, 0.49] faster | 0.95
[0.94, 0.95] faster | 47 -> 24 | 0.51 [0.50, 0.52] faster | 0.98 [0.97,
0.99] same | 166 -> 84 | 0.51 [0.50, 0.52] faster | 0.97 [0.95, 1.01]
same |
| 0.6B | 512 | 1 | unsloth | 230 -> 112 | 0.49 [0.49, 0.50] faster |
1.02 [1.00, 1.05] same | 70 -> 37 | 0.53 [0.52, 0.54] faster | 1.05
[1.02, 1.09] slower | 234 -> 121 | 0.52 [0.51, 0.52] faster | 1.02
[1.01, 1.03] slower |
| 0.6B | 512 | 4 | off | 160 -> 79 | 0.50 [0.49, 0.50] faster | 0.97
[0.96, 0.97] same | 49 -> 43 | 0.89 [0.89, 0.91] faster | 0.99 [0.99,
0.99] faster | 192 -> 191 | 0.99 [0.98, 1.00] faster | 1.00 [0.99, 1.01]
same |
| 0.6B | 512 | 4 | unsloth | 238 -> 125 | 0.53 [0.53, 0.53] faster |
1.01 [0.99, 1.02] same | 74 -> 56 | 0.76 [0.75, 0.76] faster | 1.00
[1.00, 1.00] same | 259 -> 256 | 0.99 [0.99, 1.00] faster | 1.00 [1.00,
1.01] same |
| 0.6B | 1024 | 1 | off | 158 -> 77 | 0.49 [0.48, 0.50] faster | 0.96
[0.94, 0.98] faster | 47 -> 33 | 0.71 [0.69, 0.74] faster | 0.98 [0.97,
1.00] same | 164 -> 111 | 0.67 [0.67, 0.67] faster | 1.00 [1.00, 1.00]
same |
| 0.6B | 1024 | 1 | unsloth | 223 -> 113 | 0.51 [0.51, 0.51] faster |
1.02 [1.01, 1.02] same | 67 -> 42 | 0.62 [0.60, 0.63] faster | 1.00
[0.99, 1.00] same | 231 -> 146 | 0.63 [0.63, 0.64] faster | 1.00 [1.00,
1.00] same |
| 0.6B | 1024 | 4 | off | 164 -> 117 | 0.72 [0.71, 0.72] faster | 0.99
[0.99, 0.99] same | 76 -> 73 | 0.96 [0.96, 0.96] faster | 0.99 [0.99,
0.99] faster | 405 -> 409 | 1.01 [1.01, 1.02] same | 0.99 [0.99, 1.00]
same |
| 0.6B | 1024 | 4 | unsloth | 244 -> 157 | 0.64 [0.64, 0.64] faster |
1.00 [1.00, 1.00] same | 100 -> 97 | 0.97 [0.97, 0.98] faster | 1.00
[1.00, 1.00] same | 538 -> 553 | 1.03 [1.02, 1.03] slower | 1.00 [1.00,
1.00] same |
| 1.7B | 256 | 1 | off | 162 -> 79 | 0.49 [0.48, 0.50] faster | 0.97
[0.96, 0.99] faster | 48 -> 26 | 0.53 [0.53, 0.54] faster | 0.99 [0.99,
1.00] same | - | - | - |
| 1.7B | 256 | 1 | unsloth | 236 -> 118 | 0.49 [0.49, 0.50] faster |
1.03 [1.01, 1.05] same | 73 -> 38 | 0.53 [0.50, 0.56] faster | 1.00
[0.96, 1.03] same | - | - | - |
| 1.7B | 256 | 4 | off | 166 -> 82 | 0.49 [0.49, 0.50] faster | 0.97
[0.95, 0.98] same | 50 -> 48 | 0.97 [0.96, 0.97] faster | 0.99 [0.99,
1.00] same | - | - | - |
| 1.7B | 256 | 4 | unsloth | 232 -> 118 | 0.50 [0.49, 0.52] faster |
1.01 [0.98, 1.03] same | 72 -> 65 | 0.91 [0.89, 0.93] faster | 1.00
[1.00, 1.01] same | - | - | - |
| 1.7B | 512 | 1 | off | 169 -> 82 | 0.48 [0.46, 0.49] faster | 0.96
[0.95, 0.98] same | 48 -> 34 | 0.71 [0.69, 0.75] faster | 0.98 [0.98,
0.98] same | - | - | - |
| 1.7B | 512 | 1 | unsloth | 234 -> 121 | 0.50 [0.49, 0.52] faster |
1.03 [1.01, 1.03] same | 69 -> 46 | 0.66 [0.65, 0.68] faster | 1.00
[1.00, 1.00] same | - | - | - |
| 1.7B | 512 | 4 | off | 162 -> 120 | 0.74 [0.73, 0.74] faster | 0.99
[0.99, 0.99] same | 78 -> 75 | 0.97 [0.97, 0.97] faster | 0.99 [0.99,
0.99] faster | - | - | - |
| 1.7B | 512 | 4 | unsloth | 239 -> 163 | 0.66 [0.63, 0.68] faster |
1.00 [1.00, 1.00] same | 106 -> 103 | 0.97 [0.97, 0.97] faster | 1.00
[1.00, 1.00] same | - | - | - |
| 1.7B | 1024 | 1 | off | 160 -> 81 | 0.50 [0.49, 0.51] faster | 0.97
[0.95, 0.98] same | 51 -> 50 | 0.97 [0.96, 0.97] faster | 0.99 [0.99,
0.99] faster | - | - | - |
| 1.7B | 1024 | 1 | unsloth | 240 -> 127 | 0.53 [0.52, 0.54] faster |
1.02 [1.00, 1.04] same | 76 -> 67 | 0.89 [0.88, 0.89] faster | 1.00
[0.99, 1.00] same | - | - | - |
| 1.7B | 1024 | 4 | off | 212 -> 210 | 0.99 [0.99, 0.99] faster | 0.99
[0.99, 0.99] faster | 136 -> 134 | 0.99 [0.99, 0.99] faster | 0.99
[0.99, 0.99] faster | - | - | - |
| 1.7B | 1024 | 4 | unsloth | 291 -> 290 | 1.00 [1.00, 1.00] faster |
1.00 [1.00, 1.00] same | 185 -> 184 | 0.99 [0.99, 0.99] faster | 1.00
[1.00, 1.00] same | - | - | - |

Native FSDP2 at world size 1 (sharded by hand, `adamw_torch`; compare
only within this table):

| model | seq | bs | GC | A100 ms/step off -> on (branch) | A100 on/off
[CI] | A100 branch/main on [CI] | G4 ms/step off -> on (branch) | G4
on/off [CI] | G4 branch/main on [CI] |
|---|---|---|---|---|---|---|---|---|---|
| 0.6B | 256 | 1 | off | 163 -> 79 | 0.48 [0.48, 0.49] faster | 0.95
[0.94, 0.97] faster | 52 -> 31 | 0.58 [0.55, 0.61] faster | 0.97 [0.89,
1.06] same |
| 0.6B | 256 | 1 | unsloth | 234 -> 117 | 0.50 [0.49, 0.50] faster |
1.02 [1.01, 1.02] same | 76 -> 46 | 0.58 [0.57, 0.60] faster | 1.00
[0.95, 1.03] same |
| 0.6B | 256 | 4 | off | 161 -> 80 | 0.49 [0.49, 0.50] faster | 0.95
[0.94, 0.95] faster | 55 -> 32 | 0.59 [0.57, 0.61] faster | 0.98 [0.97,
0.99] same |
| 0.6B | 256 | 4 | unsloth | 229 -> 118 | 0.51 [0.51, 0.52] faster |
1.01 [1.01, 1.01] same | 79 -> 47 | 0.60 [0.59, 0.60] faster | 1.02
[1.02, 1.03] same |
| 0.6B | 512 | 1 | off | 165 -> 80 | 0.48 [0.47, 0.49] faster | 0.97
[0.96, 0.97] faster | 55 -> 31 | 0.57 [0.54, 0.62] faster | 0.99 [0.92,
1.06] same |
| 0.6B | 512 | 1 | unsloth | 233 -> 117 | 0.50 [0.49, 0.51] faster |
1.01 [0.99, 1.03] same | 74 -> 45 | 0.59 [0.57, 0.61] faster | 1.02
[0.96, 1.08] same |
| 0.6B | 512 | 4 | off | 163 -> 82 | 0.50 [0.49, 0.50] faster | 0.95
[0.95, 0.96] faster | 56 -> 44 | 0.80 [0.79, 0.83] faster | 0.99 [0.99,
0.99] same |
| 0.6B | 512 | 4 | unsloth | 242 -> 130 | 0.54 [0.53, 0.55] faster |
1.01 [0.99, 1.03] same | 85 -> 57 | 0.67 [0.67, 0.68] faster | 1.00
[0.99, 1.00] same |
| 0.6B | 1024 | 1 | off | 161 -> 79 | 0.49 [0.49, 0.50] faster | 0.94
[0.93, 0.96] faster | 55 -> 34 | 0.61 [0.60, 0.62] faster | 1.00 [0.98,
1.03] same |
| 0.6B | 1024 | 1 | unsloth | 228 -> 117 | 0.51 [0.50, 0.52] faster |
1.01 [1.00, 1.03] same | 78 -> 48 | 0.60 [0.58, 0.61] faster | 1.01
[0.97, 1.03] same |
| 0.6B | 1024 | 4 | off | 167 -> 117 | 0.70 [0.70, 0.71] faster | 0.99
[0.99, 0.99] same | 78 -> 74 | 0.94 [0.94, 0.95] faster | 0.99 [0.98,
0.99] faster |
| 0.6B | 1024 | 4 | unsloth | 245 -> 157 | 0.64 [0.64, 0.64] faster |
1.00 [1.00, 1.00] same | 102 -> 98 | 0.96 [0.96, 0.96] faster | 1.00
[1.00, 1.00] same |
| 1.7B | 512 | 1 | off | 163 -> 80 | 0.49 [0.49, 0.49] faster | 0.96
[0.95, 0.97] faster | 56 -> 36 | 0.64 [0.61, 0.69] faster | 1.01 [0.94,
1.04] same |
| 1.7B | 512 | 1 | unsloth | 234 -> 116 | 0.50 [0.49, 0.50] faster |
1.00 [1.00, 1.01] same | 79 -> 49 | 0.61 [0.60, 0.62] faster | 1.00
[0.95, 1.02] same |

Main reproduces the earlier #15154 numbers. That PR reported Qwen3-0.6B
LoRA, seq 512, fixed length, torch 2.14.1: -40.7% step on L4, -58.6% on
A100, -27.6% at seq 2048 on A100, and +2.4% on L4 at seq 2048
(GPU-bound). The same config on current main (`fbc905fd02`), graphs on
against graphs off (M1/M0, 95% CI):

| GPU | batch 1 | batch 4 | GPU-bound check |
|---|---|---|---|
| L4 | -49.1% [-49.2, -48.9] (GC "unsloth"), -47.6% (GC off) | -0.9% /
-1.0% | batch 4 x 1024 is slower: +3.0% / +1.6% |
| A100 | -51.9% [-52.4, -51.2] (GC "unsloth"), -49.5% (GC off) | -47.7%
/ -48.4% | batch 4 x 1024: -35.2% / -27.8% |
| G4 | -49.1% / -46.1% | -25.3% / -9.5% | batch 4 x 1024: -2.6% / -2.7%
|

Peak reserved is +0.5 to 0.8 GB, as in #15154. #15154 did not record its
batch size or GC mode, so the comparison is by config, not arm for arm.
This branch keeps the same gains (B1/B0 within 0.03 of M1/M0 in every
cell).

Read across:
- **Launch-bound steps: graphs make the step up to 2x faster.** That
means batch 1, or batch 4 with short rows:
- A100, every cell but Qwen3-1.7B at batch 4 x 1024: 0.48 to 0.53. The
host CPU is slow, so the step is launch-bound there.
  - G4 and L4: 0.51 to 0.53 at batch 1 with 256 to 512 tokens.
- **The gain fades as the GPU fills:**
- G4: 0.71 at batch 1 x 1024, 0.89 at batch 4 x 512, 0.96 at batch 4 x
1024.
- L4: 0.99 at batch 4 x 512, and 1.01 to 1.03 (slower) at batch 4 x
1024.
- On T4 (earlier matrix) graphs were never faster.
- **Cost on fixed lengths:**
- memory: +0.49 to 0.57 GB peak reserved with GC off, and +0.07 to 0.80
GB with GC "unsloth";
- recording: 56 graphs (GC off) or 111 (GC "unsloth") at warm-up, none
after warm-up;
- replays: 2800 (GC off) or 4200 (GC "unsloth") over the remaining 50
steps.
- **This branch against main with graphs on:**
- GC off: 3 to 6% faster on A100 and up to 2% on G4 / L4. This comes
from dropping the output and input-gradient copies (1680 output and 1680
gradient copies per 60 steps on main, none here).
  - GC "unsloth": within noise on G4 / L4 for Qwen3-1.7B and at batch 4.
- Qwen3-0.6B at batch 1 measured 1 to 3% slower on A100 and L4 with the
first commit. That commit let the grad-mode trial before a checkpointed
block's first call skip its copies. The last commit routes the trial
back through the copy path, as on main.
- Re-measured on A100 with 6 paired repeats of main against the final
head, B1/M1 is:

    | cell | B1/M1 [95% CI] |
    |---|---|
    | seq 256, GC "unsloth" | 1.007 [0.992, 1.022], same |
    | seq 512, GC "unsloth" | 1.001 [0.983, 1.018], same |
    | seq 256, GC off | 0.955 [0.949, 0.961], faster |

The large tables above ran the first commit. The later commits change
only this trial path, the tree-manager lookup and a notice string.

## Distributed re-check (Kaggle T4x2, 2 ranks, Qwen3-0.6B, fp16, 40
steps, 2 repeats)

M0 = main graphs off, M1 = main graphs on, B1 = this branch graphs on.
Variable lengths are padded FineTome chat rows; fixed rows are 1024
tokens.

| cell (2 ranks, Kaggle T4x2) | steady ms/step M0 / M1 / B1 | train s
(40 steps, per repeat) M0 ; M1 ; B1 | peak reserved GB r0/r1 M0 ; M1 ;
B1 | records / replays M1 ; B1 | kept GiB per rank M1 ; B1 |
|---|---|---|---|---|---|
| full_ddp_var_off | 1038 / OOM 2/2 / 1024 | 82.9 / 59.0 ; OOM 2/2 ;
73.4 / 64.1 | 12.11/12.09 ; OOM 2/2 ; 12.09/12.11 | - ; 0/0 | - ; 0.00 |
| full_fsdp2_fixed_off | 1307 / 1320 / 1324 | 76.4 / 60.3 ; 73.3 / 62.7
; 61.0 / 61.1 | 9.66/9.66 ; 11.38/11.37 ; 9.66/9.66 | 56/2128 ; 0/0 |
1.64 ; 0.00 |
| lora_ddp_fixed_off | 996 / 1065 / 1138 | 51.9 / 56.4 ; 57.1 / 57.0 ;
63.5 / 58.2 | 5.76/5.76 ; 6.33/6.33 ; 6.33/6.33 | 56/2128 ; 56/2128 |
0.00 ; 0.00 |
| lora_ddp_fixed_unsloth | 1478 / 1490 / 1486 | 75.6 / 73.8 ; 76.7 /
72.8 ; 74.1 / 74.3 | 1.70/1.68 ; 2.43/2.43 ; 2.43/2.43 | 139/4364 ;
139/4364 | 0.00 ; 0.00 |
| lora_ddp_var_off | 821 / 875 / 854 | 44.2 / 44.3 ; 68.9 / 61.3 ; 48.8
/ 50.2 | 5.76/5.76 ; 10.51/10.49 ; 5.90/5.78 | 56/112 ; 0/0 | 0.00 ;
0.00 |
| lora_fsdp2_fixed_off | 1139 / 1147 / 1146 | 55.7 / 56.2 ; 57.0 / 56.9
; 58.3 / 58.2 | 5.79/5.79 ; 6.36/6.36 ; 6.36/6.36 | 56/2128 ; 56/2128 |
0.04 ; 0.04 |
| lora_fsdp2_fixed_unsloth | 1484 / 1507 / 1507 | 74.8 / 72.7 ; 74.8 /
72.6 ; 74.1 / 74.1 | 1.67/1.67 ; 2.45/2.45 ; 2.45/2.45 | 111/3273 ;
111/3273 | 0.04 ; 0.04 |
| lora_fsdp2_var_off | 877 / 905 / 873 | 45.3 / 44.4 ; 62.3 / 61.7 ;
49.2 / 49.6 | 5.79/5.79 ; 10.54/10.52 ; 5.93/5.79 | 56/112 ; 0/0 | 0.04
; 0.04 |

- **Variable lengths:**
- with graphs on, main reserved +4.75 GB per rank and trained 17 to 25 s
slower in 40 steps;
- this branch turns graphs off at the third length, before anything was
recorded (GC off warms up first), and stays within +0.14 GB;
  - the remaining 4.5 to 6 s is the one-off graphs-off compile;
  - steady steps are 2.4 to 3.5% faster than main with graphs on.
- **DDP full finetune, variable lengths, GC off:**
  - main with graphs on runs out of memory on rank 1 in both repeats;
  - this branch trains, at 1024 against 1038 ms/step;
- the notice reads `released the block CUDA graph pool (5.17 GiB
reserved freed)`.
- **FSDP2 sharded full finetune:**
- main keeps 1.64 GiB of fp32 block weights gathered per rank (11.38
against 9.66 GB peak reserved);
- this branch keeps nothing and runs those blocks without graphs, at
9.66 GB, the same as graphs off;
  - speed is the same: 1324 against 1320 ms/step.
- **LoRA at fixed length (DDP and FSDP2, GC off / "unsloth"):**
unchanged. Same records and replays, the same peak reserved, and the
same steady time within the T4's drift.
- The one outlier is the DDP GC off cell (B1 1138 against M1 1065 ms).
Its repeats were M0 863 / 1128, M1 1000 / 1128, B1 1140 / 1136. Repeat 1
agrees within 1%. Repeat 0 ran M0, M1, B1 in that order while the T4
heated up.

## Not covered

- H100: Colab gave neither account one.
- L4 ran Qwen3-0.6B only.
- Mac / AMD: block graphs are CUDA only, and the flag is unchanged off
CUDA.
- The release path when another `reduce-overhead` region shares the tree
is covered only by the CPU fake-manager test, not on a GPU.
- GRPO / DPO trainers were not timed.

---------

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