Repository navigation
Block CUDA graphs: run MoE layers and flex attention blocks compiled without graphs - #15553
Merged
Merged
Conversation
With UNSLOTH_BLOCK_CUDAGRAPHS=1, Qwen3-MoE training failed on 1 GPU and under native FSDP2: the grouped GEMM copies its offsets to the host during capture (sm80 / sm89, gradient checkpointing off), and the routing outputs are overwritten by the next replay (Unsloth gradient checkpointing on). Layers holding experts now take the existing plain compiled path.
A flex BlockMask's index tensors reach the block graph as static inputs and are rebuilt every step, so the graphs re-recorded on every call (torch 2.14 leaves StaticInputIdxMismatch out of the re-record limit). Gemma3 and Gemma3-VL with UNSLOTH_BLOCK_CUDAGRAPHS=1 trained slower than without graphs on 1 GPU and under native FSDP2. Block calls that receive a BlockMask now take the existing plain compiled path.
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. 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". |
…DeepSeek-V2/V3, GLM4-MoE) [skip ci]
[skip ci]
This was referenced Oct 28, 2026
danielhanchen
added a commit
that referenced
this pull request
Oct 28, 2026
) ## 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>
danielhanchen
added a commit
that referenced
this pull request
Oct 28, 2026
…blocks (#15756) ## Summary Follow-up to #15553 and #15720. With `UNSLOTH_BLOCK_CUDAGRAPHS=1` under native FSDP2, decoder blocks called with a flex attention `BlockMask` run compiled without CUDA graphs (`_flex_block_mask_call`), but `_keep_unsharded_for_block_cudagraphs` still kept their gathered weights allocated. That wastes the memory FSDP2 would free at reshard, and those bytes count against the `UNSLOTH_BLOCK_CUDAGRAPHS_FSDP2_KEEP_GB` budget, so in a model where only some blocks take a `BlockMask` the dense blocks could lose their graphs. There is no reliable module-level signal for "this block is flex": the `BlockMask` check is per call, and `attn_implementation == "flex_attention"` on the config does not say which layers actually receive a `BlockMask`. So the keep set is now updated from what the blocks are observed doing. ## Changes - `_block_compile.py`: `_note_block_mask_call(layer, args, kwargs)` wraps `_flex_block_mask_call` and records `_unsloth_block_flex_only` on the layer: `True` while every call so far took a `BlockMask`, `False` (sticky) after the first call without one. An observer on the layer runs on the first `BlockMask` call and on the `True -> False` change. A block whose first call had no `BlockMask` never calls it. `run()` calls it before reading `_unsloth_block_graphs_off`, so a change applies to the same call. - `fsdp2_native.py`: the keep decision moves into `_BlockWeightKeep`. Candidates are grouped per block, and `apply()` keeps the weights of every block that is not flex-only when their total fits the budget. Flex-only blocks drop the `free_unsharded_param` override, so FSDP2 frees them at the next reshard and the next all-gather allocates again. They also leave the budget, so dense blocks that were over it with them get their weights kept and their graphs back. Setup behaves as before. The observer re-runs `apply()`. - A block that sometimes takes a `BlockMask` and sometimes not stays kept once it has run a graphed call, because its graphs need one weight address. ## Tests - `tests/test_fsdp2_native_block_cudagraphs_flex_gloo.py` (CPU gloo, 2 ranks, tiny Gemma3 with `attn_implementation="flex_attention"`, so the blocks get real transformers `BlockMask`s; CPU flex has no backward, so attention goes through SDPA with the mask the `BlockMask` describes): - flex blocks: gathered storage 0 bytes after every step (main: all kept, e.g. 4096 / 8192 bytes per tensor) - SDPA blocks: still kept - flex for two steps, then SDPA: freed, then kept again - mixed model with a budget of 1.5 blocks (layer 0 without a `BlockMask`, layer 1 flex): layer 0 kept with graphs on, layer 1 freed (main: over budget, nothing kept, both blocks without graphs) - losses: with and without graphs bitwise equal, and bitwise equal to main for every arm - `tests/test_block_cudagraphs_clone.py`: the real `_wrap` / `run()` path records the flag and calls the observer exactly on `None -> True` and `True -> False`. | test | main | this PR | | --- | --- | --- | | `test_fsdp2_native_block_cudagraphs_flex_gloo.py` | 3 failed, 2 passed | 5 passed | | `test_block_cudagraphs_clone.py` | 1 failed, 48 passed | 49 passed | | `test_fsdp2_native_block_cudagraphs_gloo.py`, `test_block_compile.py`, `test_flex_mask_graph_breaks.py` | unchanged | unchanged | `test_block_compile.py::test_sm_count_is_read_outside_the_trace` fails on main as well. This applies cleanly on top of #15720 (the MoE block change). With both applied, the MoE, flex and existing block CUDA graph gloo tests pass (18 passed). ## Not covered - No GPU memory measurement. The CPU tests check FSDP2's all-gather storage sizes directly, but the actual CUDA graph recording under FSDP2 was not run here. - A block whose `_unsloth_block_mode` falls to off after setup (compile failure) still keeps its weights. That was already the case before this change. --------- 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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
UNSLOTH_BLOCK_CUDAGRAPHS=1captures each compiled decoder block in a CUDA graph. Two kinds of block cannot be captured correctly; both now take the existingplainpath (the same compiled block withouttriton.cudagraphs), as blocks already do past the shape cap or under non-reentrant checkpointing. Dense blocks keep graphs, and a one-time message names what was skipped.1. MoE layers
Problem
With
UNSLOTH_BLOCK_CUDAGRAPHS=1, Qwen3-MoE LoRA training fails on the first steps, on 1 GPU and under native FSDP2 alike (Colab L4, bf16, torch 2.14.1, transformers 5.17.0,UNSLOTH_MOE_BACKEND=grouped_mm):RuntimeError: Error: accessing tensor output of CUDAGraphs that has been overwritten by a subsequent run. The overwritten tensor is the output ofmoe_routing_sortinside the compiled block (unsloth_zoo/temporary_patches/moe_routing_triton.py), read after the next replay.RuntimeError: Cannot copy between CPU and CUDA tensors during CUDA graph capture unless the CPU tensor is pinned, raised fromextern_kernels._grouped_mmin the captured partition. On sm80 / sm89 the grouped GEMM reads its offsets on the host.Dense layers are unaffected. Llama, Qwen3, Qwen3.5, Gemma3 and Qwen2.5-VL train with graphs.
Fix
_block_compile._graphs_unsafe_moe(layer)marks a layer as MoE once, the first time it runs. A layer counts as MoE when it holds a*Expertsmodule, or a module withnum_expertsandexperts(the transformers 4.57ModuleListlayout). Such layers take the existingplainpath: the same compiled block withouttriton.cudagraphs, as already happens past the shape cap or under non-reentrant checkpointing. A one-time message says so. Dense layers keep graphs.Tests
tests/test_block_cudagraphs_clone.py::test_moe_layers_run_without_graphs(CPU, fakedtorch.compile): a dense layer runs the graphed compile, and both MoE layouts run the plain one. On main it fails for both MoE layouts (2 failed). On this branch all 14 tests in the file pass.test_block_compile.py,test_block_compile_discovery.py,test_fsdp2_native_block_cudagraphs_gloo.py,test_legacy_block_compile_install.py): 94 passed.test_sm_count_is_read_outside_the_tracefails on main too without a CUDA device.GPU (Colab L4, bf16, tiny Qwen3-MoE with the real config shrunk, LoRA, fixed lengths, 8 steps, 1 GPU and native FSDP2 at world size 1):
2. Flex attention blocks
Problem
With
UNSLOTH_BLOCK_CUDAGRAPHS=1, Gemma3 and Gemma3-VL (flex attention: sliding-window BlockMask) re-record their block graphs on every step. This happens on 1 GPU and under native FSDP2 alike, and they train slower than with graphs off (Colab L4, bf16, torch 2.14.1, transformers 5.17.0, tiny copies of the real configs, LoRA, fixed lengths, 8 steps):Dense SDPA / flash models stay put: Llama and Qwen3.5 record everything in step 0 and nothing after.
Cause, from cudagraph trees' own invariant check (
CUDAGraphNode.check_invariants, counted per call):StaticInputIdxMismatch191 times against 58 replays. Every reason isstatic input data pointer changedfor four consecutive inputs (primals_20..primals_23), whose stack trace ends inflex_attention_hop. These are the BlockMask index tensors, rebuilt each step.StaticInputIdxMismatchtowardcudagraph_unexpected_rerecord_limit(cudagraph_trees.py_run), so the graphs are never given up on.UNSLOTH_ENABLE_FLEX_ATTENTION=0(SDPA): 28 records, all in step 0.UNSLOTH_BLOCK_FLEX=outside(flex as its own region): no re-recording, but 12 graph breaks and 68.5 ms, still slower than no graphs.Fix
_block_compile._flex_block_mask_call(args, kwargs): a block call that receives aBlockMasktakes the existingplainpath (the same compiled block withouttriton.cudagraphs), with a one-time message. Other blocks keep graphs.Tests
tests/test_block_cudagraphs_clone.py::test_flex_block_mask_calls_run_without_graphs[None|tensor|block_mask](CPU, fakedtorch.compile): no mask and a tensor mask keep the graphed compile; a BlockMask takes the plain one. On main theblock_maskcase fails; here all 14 tests in the file pass.test_sm_count_is_read_outside_the_traceneeds CUDA and fails on main too.GPU (Colab L4, bf16, same cells,
UNSLOTH_BLOCK_CUDAGRAPHS=1on every arm except "graphs off"):grads0_cmp.json).This branch and
dh/fsdp2-opt-cgmoe(MoE layers, sameplainpath) edit the same condition in_wrap.run. Whichever lands second needs a one-line rebase.Combined
Both checks sit in one condition in
_wrap.run.tests/test_block_cudagraphs_clone.py: main 3 failed, 14 passed; this branch 17 passed (CPU, torch 2.13).