Repository navigation
Block CUDA graphs: decide before recording, release the pool, cap FSDP2 kept weights, drop unneeded copies - #15352
Conversation
…P2 kept weights, drop unneeded copies UNSLOTH_BLOCK_CUDAGRAPHS=1 (opt-in) cost time and memory where it could not help: - Packed / padding-free rows: graphs never engaged; now they stay off from the first call with one rank-0 notice saying so. - Variable padded lengths: each new length re-recorded until 8 shapes, then a graphs-off copy compiled mid-run while the graph pool stayed reserved (+3 to 4.75 GB on a T4, one OOM). The cap is now 2 shapes (one length plus a short last batch), graphs go off for every block class at once (they share one cudagraph tree per device) with a notice, and the pool is released with reset_cudagraph_trees() once no forward is pending and every tree function came from a block compile (otherwise it is kept and the notice says why). - Native FSDP2: the gathered weights kept for graphs are capped per rank (UNSLOTH_BLOCK_CUDAGRAPHS_FSDP2_KEEP_GB, default 0.5); over it nothing is kept and those blocks run without graphs (a sharded full finetune kept 1.64 GiB fp32 per rank for no speedup). The kept-bytes count read dtypes FSDP2 only sets at lazy init, so it always said 0.00 GiB. - Block outputs and input gradients are no longer cloned out of the pool for grad-mode calls outside backward: a pending forward keeps cudagraph trees in one generation until the backward. Checkpointed blocks (no-grad forward, recompute inside backward) still copy. Flag unset: unchanged.
LoRA keeps tens of MiB of adapters per rank, which printed as 0.00 GiB.
Two get_manager lookups per block call become one cached read. The manager is looked up before the first call too, so functions another region recorded earlier are never counted as ours.
… like its recompute The trial before a checkpointed block's first no-grad call stands in for the recompute; it now takes the recompute's copy path, as before, so it records what the recompute replays.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…heckpoint [skip ci]
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…s-costs # Conflicts: # unsloth/models/_block_compile.py [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a7922b15d2
ℹ️ 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".
| stack.extend(n for n, _ in node.next_functions if n is not None) | ||
| return False |
There was a problem hiding this comment.
Copy input gradients that reach leaves through view operations
With block CUDA graphs enabled and checkpointing disabled, caller-provided inputs_embeds created as a view of an external trainable parameter (for example, embedding_param.view(batch, length, dim)) bypasses the gradient copy: this traversal visits ViewBackward and AccumulateGrad, then returns False. A view backward can pass the graph-pool gradient through without allocating new storage, so the parameter's first accumulated .grad can still alias the replay buffer and be overwritten on a subsequent backward. The new direct-leaf check fixes leaf hidden_states, but not this non-leaf path to a leaf; treat an encountered AccumulateGrad as requiring a copy unless an intervening operation guarantees independent gradient storage.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 58c5f69. The walk now tracks, per path, whether it passed an op whose backward writes a new input gradient (mm / addmm / mul / embedding / norm / softmax and similar). Reaching an AccumulateGrad without one on the path (a view, add or clone of a leaf, like inputs_embeds = param.view(...)) counts as needing the copy. New test_input_viewing_a_trainable_param_copies_its_gradient: the view and view + add cases fail on the previous head and pass now, the embedding lookup case still takes no copy. tests/test_block_cudagraphs_clone.py 36 passed (CPU), tests/test_block_cudagraphs_gpu.py 3 passed on B200.
…ough view or add ops [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 58c5f690ac
ℹ️ 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".
| "SoftmaxBackward", | ||
| "SiluBackward", | ||
| "GeluBackward", | ||
| "CatBackward", |
There was a problem hiding this comment.
Preserve input-gradient copies across concatenation backward
With block CUDA graphs enabled and checkpointing disabled, concatenating a trainable prompt with embeddings can still leave the prompt's .grad aliasing the replay buffer. The new CatBackward allowlist entry marks this path as having independent gradient storage, but concatenation backward returns narrowed views of its incoming gradient rather than allocating new storage. For contiguous slices (for example, sequence concatenation with batch size one), AccumulateGrad can retain that storage, allowing a subsequent replay to overwrite the accumulated prompt gradient. Remove CatBackward from the allocating-backward allowlist so these inputs retain _CloneGrad protection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in f3d179d: CatBackward is out of the allocating list (its backward returns narrowed views of the incoming gradient), so a leaf reached through a concatenation keeps the copy. The other entries (slice / select / index backward and the matmul, elementwise and norm backwards) write a new tensor. New cat case in test_input_viewing_a_trainable_param_copies_its_gradient (a trainable prompt concatenated in front of other rows): fails on the previous head, passes now; the file has 37 passed.
…ut gradient copy through it
…ming gradient, keep the copy on that edge [skip ci]
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
[skip ci]
# Conflicts: # tests/test_block_cudagraphs_clone.py # unsloth/models/_block_compile.py [skip ci]
… regions Other compiled functions (e.g. a compiled prompt preprocessor) can pass the incoming gradient straight to a trainable leaf, so their first .grad would alias the graph pool. Tag the autograd nodes of graphed block calls and copy conservatively for any other compiled producer. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
) ## Problem `UNSLOTH_BLOCK_CUDAGRAPHS=1` under native FSDP2 keeps the all-gathered weights of every parameter inside a compiled decoder block allocated (`_keep_unsharded_for_block_cudagraphs`, #15215), so the block CUDA graphs see one address per weight and replay instead of re-recording. Since #15553, `_block_compile` runs MoE blocks compiled without CUDA graphs (`_graphs_unsafe_moe`: routing outputs are overwritten across replays and the grouped GEMM copies offsets to the host during capture). FSDP2 still kept the gathered weights of those blocks. Those graphs never record, so nothing reads the fixed addresses. The cost is that every rank holds every expert of every MoE block unsharded after the first forward. For MoE models, the experts are most of the weights, so most of what FSDP2 shards stays fully gathered on every rank. ## Fix `_compiled_block_modules` skips blocks that `_block_compile._graphs_unsafe_moe` marks as MoE. It uses the same check that routes them to the graphs-off path, so the two cannot disagree. Their gathered weights are freed at reshard as usual. Dense blocks keep theirs, and nothing changes without `UNSLOTH_BLOCK_CUDAGRAPHS=1` or without block compile, because the check only runs on blocks `_block_compile` wrapped. ## Tests `tests/test_fsdp2_native_block_cudagraphs_moe_gloo.py` (CPU, gloo, world size 2). It uses a tiny random Qwen3-MoE whose layer 0 is dense (`mlp_only_layers=[0]`) and layer 1 is MoE, `UNSLOTH_BLOCK_CUDAGRAPHS=1`, full finetune, 2 steps, `_block_compile.py` loaded by file path: | test | main | this branch | |---|---|---| | `test_moe_block_weights_are_freed_under_block_cudagraphs` | FAIL (MoE block storages kept, size > 0) | PASS (size 0) | | `test_dense_block_weights_stay_kept_under_block_cudagraphs` | PASS | PASS | The existing `tests/test_fsdp2_native_block_cudagraphs_gloo.py` and `tests/test_block_cudagraphs_clone.py` still pass (61 passed with the new file, main at d21d016). `tests/test_fsdp2_native_units.py` passes too (40 passed, before the rebase onto #15352). All runs used torch 2.13 and transformers 5.17 on CPU. ## Not covered - No GPU run. The change only affects which FSDP2 parameters skip `free_unsharded_param`, and the CPU gloo test checks that directly. - Flex attention blocks (Gemma3, which #15553 also routes off graphs) are detected per call from a `BlockMask` argument, so they cannot be known when FSDP2 shards. Their gathered weights are still kept. They are dense, so the cost is far smaller. - Since #15352, the kept bytes are checked against `UNSLOTH_BLOCK_CUDAGRAPHS_FSDP2_KEEP_GB` (0.5 GB by default), and over that budget no block keeps its weights and every block runs without graphs. MoE weights used to count toward that budget, so a MoE model could turn graphs off for its dense blocks as well. With MoE blocks skipped, only the blocks that can be graphed count. This follows from the code and was not measured on a GPU. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…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>
… the block backend compiled (#15777) ### Problem With `UNSLOTH_BLOCK_CUDAGRAPHS=1`, going past the shape cap turns block graphs off and releases the cudagraph tree pool via `reset_cudagraph_trees()`, but only when every tree function belongs to a block compile (#15352). Ownership was taken as every tree function created during a graphed block call (`ids_to_funcs` before / after delta in `_graphed_call`). A third-party `torch.compile(mode="reduce-overhead")` function that is first called inside a block (behind a graph break, e.g. through a `torch.compiler.disable` helper) registers its tree function during that same call, so it was counted as the block's. Past the cap the release then reset the shared tree, and the next call of that function failed with `AssertionError: Running CUDAGraph after shutdown`. ### Change The graphs-on block compile now uses a subclass of the stock inductor backend (`torch._TorchCompileInductorWrapper`, same options) that records `CompileContext.current_compile_id()` for every graph it compiles. A foreign region compiles through its own backend, so its compile ids are never recorded. `_graphed_call` only counts new tree functions whose compile id the block backend recorded; anything else makes the release verdict "foreign" and the pool is kept, as already happens for regions created before the first block call. The backward tree function carries the forward's compile id, so a block-only tree is still released. If the backend cannot be built, nothing counts as the block's and the pool is kept. The graphs-off copy and runs without `UNSLOTH_BLOCK_CUDAGRAPHS=1` are unchanged. ### Tests `tests/test_block_cudagraphs_clone.py`: - `test_foreign_function_first_called_inside_a_block_is_not_ours`: a mocked tree manager gets a block and a foreign tree function during one `_graphed_call`; only the block one is ours and the verdict is "foreign". Fails on main. - `test_block_backend_notes_the_compile_ids_it_builds`, `test_only_the_graphs_on_compile_gets_the_owning_backend`: the backend records the compile id and keeps the block options; only the graphs-on compile gets it. - `test_graphed_call_records_the_compile_ids_it_created` updated for the recorded ids. CPU: `test_block_cudagraphs_clone.py`, `test_block_compile.py`, `test_block_compile_discovery.py`, `test_legacy_block_compile_install.py`, `test_fsdp2_native_block_cudagraphs*_gloo.py`: 138 passed, 6 skipped, 1 failed (`test_sm_count_is_read_outside_the_trace` needs a CUDA device and fails the same way on main). GPU (RTX PRO 6000 Blackwell, torch 2.14.1+cu130): one decoder layer whose forward calls a `reduce-overhead` helper through a `torch.compiler.disable` boundary, sequence lengths 40, 48, 56 so the third shape passes the cap of 2: | | foreign helper inside the block | block only | | --- | --- | --- | | main | pool released, then `Running CUDAGraph after shutdown` at step 8 | pool released | | this change | pool kept, every step and a later standalone helper call succeed | pool released | ### Not covered torch 2.7 to 2.13 on GPU were not run (the backend class and `CompileContext.current_compile_id()` exist across that range). Multi GPU runs were not run. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
`Repo tests (CPU, fsdp2)` on #15833's staging run passed every test and still went red: ``` 364 passed, 28 skipped, 80 warnings in 2092.29s (0:34:52) ##[error]Process completed with exit code 124. ``` The shard's pytest step runs under `timeout --signal=INT --kill-after=60 2100`. pytest finished 8 s under that cap, and the cap then fired while it was exiting. ## Cause #15291 moved the FSDP2 gloo tests into their own shard at about ten minutes of runner time. They have grown since, with most of a dozen FSDP2 PRs merged today adding tests there (#15756, #15748, #15720, #15709, #15708, #15352, ...). Over the last twenty-odd staging runs this job took 21 to 38 minutes, so it now sits at its cap on an ordinary runner. Nothing failed; the shard is simply too big for its timeout. ## Fix Split the shard in two by file name, balanced on measured time. Per-test durations on main, summed per file across all 76 files: | shard | selection | files | tests | measured time | |---|---|---|---|---| | `fsdp2` | `tests/test_fsdp2_[!n]*.py tests/test_fsdp2_n[!a]*.py tests/test_fsdp2_native_[abc]*.py` | 34 | 237 | 1156 s (45%) | | `fsdp2-native` (new) | `tests/test_fsdp2_native_[!abc]*.py` | 42 | 276 | 1406 s (55%) | | both together, unchanged total | `tests/test_fsdp2*.py` | 76 | 513 | 2562 s | `fsdp2` keeps its name, so its check name is unchanged. The step timeout and job cap are left alone, so each half gets the whole budget. ## Guards - `tests/test_ci_repo_cpu_shards.py` already fails when a file lands in no shard or in two. It caught my first draft, which dropped `test_fsdp2_non_cuda_accelerate_route.py`; hence the `n[!a]` glob. - A new check, `TestEveryGlobRootMatchesAFile`, fails if a shard glob matches no test file. bash passes an unmatched glob through literally and pytest then fails the whole shard on a missing path. Sabotage: adding `tests/test_fsdp2_zz*.py` to a selection fails it with `[('fsdp2', 'tests/test_fsdp2_zz*.py')]`. - `tests/studio/test_backend_ci_parallel_isolation.py` pins the number of parallel runs, now nine (six repo-root shards). ## Verification - `tests/test_ci_repo_cpu_shards.py` and `tests/studio/test_backend_ci_parallel_isolation.py`: 56 passed. - With `tests/studio/test_cache_budget_discipline.py` added: everything passes except the guard on my first draft, fixed above. - `--collect-only` on the two selections gives 237 + 276 = 513, the same as the old single glob. The per-file times are from a local `-n 8` run, so the split ratio is approximate. The first runs of the two new shards will show the actual runner times.
…AGRAPHS_DDP=1, -20% to -27% step on 2xT4) (unslothai#18873) ## Problem Auto mode for block CUDA graphs (unslothai#15768) never turns graphs on when a process group has more than one rank. `_auto_static_reason` returns `"distributed"` for any initialized group with world > 1. The rule was written as a precaution and never measured. The only multi-GPU number on record is the forced-graphs DDP matrix in unslothai#15352, which ran 1,024-token rows with checkpointing on a T4 and came out a tie (1478 / 1490 / 1486 ms). That step is GPU-bound, and auto mode's own probe already keeps graphs off for that case on one GPU. Launch-bound DDP runs, such as small models with short padded rows, lose the 1-GPU gain. ## Change Auto mode may now turn graphs on under **plain DDP over every rank**: block weights are replicated and no collective runs inside a block. - Every rank probes exactly as on one GPU: shape, packed rows, non-reentrant checkpointing, MoE, flex, launch / GPU ratio and free memory. Each rank then publishes its verdict (`on`, or `off:<why>`) to the process group's store. - A rank switches graphs on, at a forward-pass boundary, only once **every** rank published `on`. Any `off` keeps graphs off on every rank, with the reason naming the rank, for example `rank 1: batch shape changed`. So does no full set of verdicts within `UNSLOTH_BLOCK_CUDAGRAPHS_AGREE_TIMEOUT` seconds (default 120). - No collective is issued, only store `set` / `check` / `get`. A rank that turned off early, or never reaches a block call, cannot hang the others or interleave with DDP's gradient all-reduce. - Graphs stay off as before for: - FSDP2 / tensor parallel (DTensor block weights), - DDP over a sub-group (pipeline or TP x DP), - context parallel (`get_cp_manager()` is active), - a process group with no DDP forward around the block (`DistributedDataParallel._get_active_ddp_module()` is None), - a block outside the DDP module, - no store. Full finetuning, ROCm and torch < 2.13 keep their existing rules. `UNSLOTH_BLOCK_CUDAGRAPHS=0` / `=1` keep their meaning. - The "graphs on" notice prints on rank 0 once every rank agreed, with `(every rank agreed)` appended. - Gradient flow is unchanged. The existing first-write `.grad` clone (`_param_grads_out_of_pool`) runs as a tensor hook, before DDP's post-accumulate bucket hook, so buckets never read graph pool memory. Under `no_sync`, gradients accumulate into the cloned `.grad` as on one GPU. ## Kaggle 2x T4 A/B (2 ranks, torch 2.14.1, fp16) Setup: - Model: Qwen3-0.6B, LoRA r16 on all linear layers, `use_gradient_checkpointing = "unsloth"`, 1 row per rank, `max_length` 512, `padding_free = False`, adamw_8bit. - Base = `main` (f5dfe68) as installed. Head = the same install with this branch's `_block_compile.py`. Every arm checks which tree it imported. - Arms run base, head, head, base, each a fresh `torchrun` with a fresh compile cache, so each side has its own A/A pair. - Step time = mean over ranks of the median steady step. GA 1: 60 steps, first 15 dropped. GA 4: 30 steps, first 8 dropped. Variable-length cells: 40 / 20 steps, rows of uniform random length in 128-512. | cell | base s/step | head s/step | delta | A/A base / head | auto on head (both ranks) | graphs built per rank | peak alloc / reserved GiB, base to head | |---|---|---|---|---|---|---|---| | 16-bit LoRA, GA 1, padded | 0.2353 | 0.1765 | **-25.0%** | 0.2% / 2.2% | on (ratio 2.1-2.6) | 2 | 1.56 / 1.59 to 1.61 / 1.72 | | 16-bit LoRA, GA 4, padded | 0.8156 | 0.6700 | **-17.9%** | 2.3% / 0.1% | on (ratio 1.95-2.0) | 2 | 1.60 / 1.62 to 1.65 / 1.74 | | QLoRA, GA 1, padded | 0.3419 | 0.2168 | **-36.6%** | 1.8% / 5.6% | on (ratio 2.8-3.2) | 8 | 0.99 / 1.03 to 1.03 / 1.16 | | QLoRA, GA 4, padded | 1.2243 | 0.7998 | **-34.7%** | 2.5% / 2.1% | on (ratio 2.7-3.0) | 8 | 1.02 / 1.06 to 1.07 / 1.18 | | 16-bit LoRA, GA 1, variable length | 0.2482 | 0.2443 | -1.6% | 6.5% / 1.4% | off, `batch shape changed` | 0 | unchanged | | 16-bit LoRA, GA 4, variable length | 0.8362 | 0.8632 | +3.2% | 0.5% / 4.7% | off, `batch shape changed` | 0 | unchanged | | QLoRA, GA 1, variable length | 0.3509 | 0.3459 | -1.4% | 0.2% / 0.3% | off, `batch shape changed` | 0 | unchanged | | QLoRA, GA 4, variable length | 1.2773 | 1.2865 | +0.7% | 0.9% / 5.8% | off, `batch shape changed` | 0 | unchanged | Base reported `distributed` on both ranks in every cell. - **Where graphs engage** (fixed-shape padded rows), the step is 17.9% to 36.6% faster, above the A/A spread plus 5% in all four cells. Both ranks report phase `on`, and rank 0 printed the `(every rank agreed)` notice. The graph count is the same at GA 1 (60 steps) and GA 4 (30 steps), so nothing re-records per step. Cost: +0.04 to +0.05 GiB peak allocated and +0.12 to +0.13 GiB peak reserved per rank. - **Variable-length rows**: both ranks turn off at the second forward pass, before anything is timed or recorded, and 0 graphs are built. The head deltas sit inside the A/A spread of the noisier side. The +3.2% cell comes from one head arm, 0.8812 / 0.8857 s on its two ranks; the other head arm ran 0.8428 / 0.8431 s, +0.8% against the base mean. After that pass the head code path is the base path plus one store write, so I read it as T4 drift, not a cost. - **Losses**: no pair of runs is bitwise equal, base against base included, so the check is against that run-to-run spread. Max |diff| of logged losses, base against head, stayed inside the run-to-run band in every cell: | cell | base vs base | head vs head | base vs head, closest pair | base vs head, worst pair | |---|---|---|---|---| | 16-bit LoRA, GA 1, padded | 6.8e-4 | 2.5e-3 | 4.6e-4 | 2.2e-3 | | QLoRA, GA 1, padded | 1.4e-3 | - | - | 1.1e-3 | | the other six cells | 2.1e-4 to 7.8e-4 | - | - | 2.0e-4 to 8.2e-4 | Mean loss over 60 steps (16-bit LoRA, GA 1, padded): 3.00858 / 3.00870 base, 3.00869 / 3.00855 head. - **One-off cost**: the graphed region is compiled and recorded once at the switch, as on one GPU. Whole-run wall time for these short runs, base to head: - 16-bit LoRA, GA 1: 33.9 / 29.1 s to 36.5 / 33.1 s (60 steps). - QLoRA, GA 1: 77.2 / 59.1 s to 94.7 / 81.1 s (60 steps). The per-step saving pays this back after roughly 60 to 150 steps on these shapes. unslothai#15768 measured the same one-off cost (about 5 s, break-even about 45 steps on one A100). ## Tests `tests/test_block_cudagraphs_auto_ddp_gloo.py` (new, CPU, gloo world 2, real DDP and the real store; compile and timing stubbed as in `test_block_cudagraphs_auto.py`): - A process group without a DDP forward keeps graphs off (`distributed, not DDP`). - Under DDP both ranks turn graphs on at the same step. - One GPU-bound rank keeps graphs off on both ranks (`rank 1: GPU-bound ...`). - A batch shape change on one rank keeps graphs off on both (`rank 1: batch shape changed`). - A rank that never decides makes the other time out to off instead of waiting. All 5 fail on `main`: every case reports `distributed`, and in the timeout case rank 0 turns graphs on alone. All 5 pass here. `test_block_compile*.py`, `test_block_cudagraphs*.py` and `test_fsdp2_native_block_cudagraphs_gloo.py`: 191 passed, 29 skipped on this branch. On `main` the only failures are the 5 new tests. ## Not covered - Only Kaggle 2x T4, one model (Qwen3-0.6B) and one row shape (1 x 512). No L4 / A100 / H100 multi-GPU run, no 4+ rank run, no bf16 run. - FSDP2, tensor, pipeline and context parallel are deliberately unchanged. No timing for them here. - A rank that turns off after the others already read an all-`on` set (a shape change exactly at the switch pass) leaves graphs on for the others only. The math is still correct, since DDP averages the same gradients, but that run gains nothing. Covered by reasoning, not by a test. - torch 2.13 under DDP was not run; only 2.14.1. - GPU-bound DDP shapes (long rows), where auto should report `GPU-bound` on every rank, were not run in this A/B. They are covered by the 1-GPU probe and the CPU test. ## Update (7d28175): one collective per agreement point The rank agreement no longer polls the TCP store. The first eager block call inside a DDP forward attaches a forward pre-hook to that DDP wrapper. On grad-synced DDP forwards only (which DDP already requires every rank to run), the hook runs one eager `all_reduce(MIN)` on the DDP process group carrying each rank's state (off / probing / ready) and its vote count. Graphs turn on only from that result, so every rank switches in the same forward; any veto or a count mismatch turns them off everywhere. - Later rank-local fallbacks (packed rows, the shape cap, a failed graph compile, a block called outside the DDP module, context parallel) turn graphs off on that rank at once, and the other ranks follow at the next check (1, 2, 4, ... up to every 64 synced forwards). - Ownership, DTensor weights and context parallel (Unsloth's and torch's native `context_parallel()`) are checked on every block call, including the fast path. FSDP2 modules, DTensor parameters and sub-group DDP are refused at enrollment. - `DDP.join()`, `torch.compile` around the DDP model, a rank still probing after 64 synced forwards, and graphs enabled before the process group existed all keep graphs off on every rank. - The store keys, round keys, deadlines and `UNSLOTH_BLOCK_CUDAGRAPHS_AGREE_TIMEOUT` are gone. `UNSLOTH_BLOCK_CUDAGRAPHS_DDP=0` turns the DDP path off. - Test workers drop inherited `UNSLOTH_*` settings and use `tests._rendezvous_port.free_port`. Tests (CPU gloo, world 2): the new test file has 11 tests; 7 fail on the previous store protocol (ranks switching at different steps under `no_sync()`, a late shape-cap veto ignored by the peer, a block outside the DDP module, context parallel turned on late, a probe before the process group, `join()` with uneven inputs, a rank that never finishes probing) and all 11 pass now. The block-compile and CUDA-graph suites give 229 passed, 30 skipped (GPU). Kaggle 2xT4, Qwen3-0.6B 16-bit LoRA, 1 x 512 padded rows, base = merge base, each side run twice: | | base s/step | head s/step | change | A/A base / head | peak reserved GiB, base -> head | |---|---|---|---|---|---| | GA 1 | 0.2443 | 0.1859 | -23.9% | 2.7% / 1.2% | 1.59 -> 1.72 | | GA 4 | 0.8615 | 0.7014 | -18.6% | 3.1% / 1.5% | 1.62 -> 1.74 | Both ranks report graphs on with identical vote counts. Loss differences base vs head (1.9e-3 at GA 1, 2.5e-4 at GA 4) are within the earlier run-to-run spread. ## Update (9f3544537): DDP path is opt-in, enrollment at DDP construction, join pauses the vote Default under DDP is back to what main does: any process group keeps block CUDA graphs off, `DistributedDataParallel` is not touched, no hook is registered and no collective is added. Set `UNSLOTH_BLOCK_CUDAGRAPHS_DDP=1` (the same on every rank, before Unsloth loads a model) to turn the agreement on. Single-GPU auto mode is unchanged. With the variable set: - Every DDP wrapper is enrolled right after it is built, on every rank (the constructor already runs collectives on every rank). Before, a rank enrolled at its first eager block call, so a rank-local first forward (an eval pass on rank 0, an extra `no_sync()` microbatch) made one rank vote a forward earlier than the other and aborted the collective. - The hook sits on `ddp.module`, so it runs inside the DDP forward after DDP's own pre-forward collectives (bucket rebuild, buffer broadcast, join notification). - Under `DDP.join()` no vote is taken and the vote count stands still on every rank, so ranks with different numbers of inputs leave the window on the same schedule. A rank that runs a forward inside the window turns its graphs off, and the first vote after the window turns them off everywhere. - Local refusals (graphs mode not auto, block compile disabled, no compiled blocks, not CUDA, platform, `torch.compile` inside or around the DDP wrapper, FSDP2 / DTensor) are sent as votes of 0. A rank never skips a vote. - The vote tensor sits on the module's own GPU for NCCL (not the current device, which can be another rank's GPU when `device_ids=None`) and on the CPU for gloo. - A session replaced by a newer model or a re-wrap votes 0 without touching the new state. A DDP veto is cleared for the next model once its graph pool is released. - Graph pool release on every veto path (compiled and stock calls), ownership checks for stock calls, DTensor checks repeated when a block's parameters change, checkpoint recomputes use graphs only after a forward in the owning DDP forward, `BackendCompilerFailed` subclasses (`InductorError`) fall back to plain blocks under DDP, a late gradient-carrying side input and a new shape at the switch both veto. Tests (CPU, gloo, 2 ranks): `tests/test_block_cudagraphs_auto_ddp_gloo.py` has 15 tests. Against the previous commit, 5 fail: the default run issues votes and turns graphs on; a rank-local eval forward first and a rank-local `no_sync()` microbatch first abort with a gloo collective mismatch (SIGABRT); an uneven `join()` window after graphs are on aborts the same way; a persistent context-parallel veto never releases the graph pool. All 15 pass now, also with `UNSLOTH_COMPILE_DISABLE=1 UNSLOTH_BLOCK_CUDAGRAPHS=1` in the parent environment. The default-off test also passes on the merge base. Block compile, CUDA graph and FSDP2 block suites: 361 passed, 39 skipped. Kaggle 2x T4, Qwen3-0.6B 16-bit LoRA, 1 x 512 padded rows, seconds per step (median of both ranks), merge base vs this commit. Two sessions, each arm run twice in the same session: | | base | `UNSLOTH_BLOCK_CUDAGRAPHS_DDP=1` | change | unset | change | A/A spread base / on / unset | |---|---|---|---|---|---|---| | Session 1, GA 1 | 0.2418 | 0.1920 | -20.6% | 0.2398 | -0.8% | 0.9% / 3.3% / 2.5% | | Session 1, GA 4 | 0.8264 | 0.7253 | -12.2% | 0.8356 | +1.1% | 1.0% / 0.4% / 4.0% | | Session 2, GA 1 | 0.2457 | 0.1795 | -26.9% | | | 1.5% / 1.0% | | Session 2, GA 4 | 0.8382 | 0.6679 | -20.3% | | | 2.0% / 0.3% | Session 2 also ran the previous commit in the same session: 0.1793 (GA 1) and 0.6664 (GA 4) s/step, within 0.2% of this commit. So the new checks cost nothing measurable, and the GA 4 gap in session 1 comes from that machine. On a CPU microbenchmark the per-call check went from 0.7 to 1.7 us, under 1 ms per GA 4 step. With the variable set, both ranks report graphs on, the same vote count (GA 1: 9, GA 4: 5) and the same schedule. Peak reserved memory per rank goes from 1.59 to 1.72 GiB (GA 1) and from 1.62 to 1.74 GiB (GA 4). With it unset, every rank reports graphs off for `distributed` (main's reason), 0 Unsloth collectives, an unpatched `DistributedDataParallel.__init__`, the same reserved memory as base, and step times within the base A/A spread. Final losses match base to within the run-to-run spread (largest difference 2e-4). Not covered: NCCL with `device_ids=None` (the vote device is checked on CPU only), QLoRA, variable-length rows, more than 2 ranks, GPUs other than T4. ## GPU check at the current head Kaggle 2x T4 at the current head 8cf9916, NCCL: the one-rank `ddp.module.compile()` repro hits the 200 s NCCL watchdog at 82a391d and completes 4 steps here with both ranks agreeing graphs off. Plain LoRA with `UNSLOTH_BLOCK_CUDAGRAPHS_DDP=1`: graphs engage on every run (2 graphs, 9 votes per rank, every rank agreed), step 0.2076 -> 0.1737 s (-16.3%, three interleaved pairs, A/A 1.6% / 1.1%), peak 1.646 -> 1.665 GiB.
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
Decide before recording.
packed_seq_lengths,cu_seq_lens_q,cu_seq_lens_k,cu_seqlensin 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.UNSLOTH_BLOCK_CUDAGRAPHS_MAX_SHAPESstill overrides it.Release the pool. Once graphs are off, the next block call frees the tree with
torch._inductor.cudagraph_trees.reset_cudagraph_trees(), then runstorch.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 inCUDAGraphTreeManager.runwith "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:manager.ids_to_funcs/manager.id_to_compile_id. The backward of the same compile shares its compile id;running_forwards_with_pending_backwardsis false;live_cudagraph_pool_storages_in_curr_execution()is empty.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.reset_cudagraph_treesis at 2.10 L304, 2.13 L350 and 2.14 L362;shutdownis at 2.10 L2205, 2.13 L2374 and 2.14 L2620.Native FSDP2: cap what is kept gathered.
_keep_unsharded_for_block_cudagraphsnow adds up the bytes it would keep per rank before keeping anything.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.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.Drop copies out of the pool outside checkpointing. Block outputs and input gradients are no longer cloned for a grad-mode call outside backward:
CUDAGraphTreeManager.runmarks a forward as pending (2.10 L2037, 2.13 L2182, 2.14 L2410);can_start_new_generationthen starts no new generation until a backward runs (2.10 L2377, 2.13 L2557, 2.14 L2820);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.py29 passed on each version. Of these, 16 fail on main.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.pyfailures 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):empty_cache()Where block graphs pay (timing)
Setup:
seqtokens, 60 steps.Tiers:
Graphs on / off on this branch (B1/B0, below 1 = graphs faster), and this branch / main with graphs on (B1/M1), single GPU:
Native FSDP2 at world size 1 (sharded by hand,
adamw_torch; compare only within this table):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):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:
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:
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.
released the block CUDA graph pool (5.17 GiB reserved freed).Not covered
reduce-overheadregion shares the tree is covered only by the CPU fake-manager test, not on a GPU.