Skip to content

Block CUDA graphs: turn on automatically for fixed-shape, launch-bound LoRA runs - #15768

Merged
danielhanchen merged 10 commits into
mainfrom
block-cudagraphs-auto
Oct 28, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
block-cudagraphs-auto

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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.

@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-28T15:31:02.816461Z — 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

2 similar comments
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: fccaaba96d

ℹ️ 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 unsloth/models/_block_compile.py Outdated
Comment on lines +574 to +578
torch.cuda.synchronize(device)
start = torch.cuda.Event(enable_timing = True)
end = torch.cuda.Event(enable_timing = True)
torch.cuda._sleep(_AUTO_SLEEP_CYCLES)
start.record()

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 Record probe timings on the block's CUDA device

When a block runs on a GPU other than the current CUDA device (for example, a model loaded onto cuda:1 while the current device remains cuda:0, or a model sharded through device_map), the sleep and both events run on the current device rather than the supplied device. torch.cuda.synchronize(device) does not change that selection. Consequently, the events do not measure the block's kernels and can report an almost-zero GPU duration, causing auto mode to enable graphs for a GPU-bound workload and incur unnecessary recording and memory costs. Run the timing sequence inside torch.cuda.device(device) and record on that device's stream.

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 in d89b64d: the sleep and both events now run inside torch.cuda.device(device) for the block's device, and test_probe_times_on_the_blocks_device checks that a block on cuda:1 is timed there while cuda:0 stays current.

@danielhanchen

Copy link
Copy Markdown
Member Author

The Source lint job on the staging run fails in the import-hoist step:

=== unsloth/models/_block_compile.py: BLOCKERS ===
  [BLOCKER] unsloth/models/_block_compile.py: UNRESOLVED-NEW 'flex' in scope <module>._wrap.run

This is not the branch itself: against its own merge base (0512f4e7f9) the verifier passes and ruff reports no undefined names. It comes from #15756, which landed on main afterwards and reworked the flex BlockMask path in the same file (_note_block_mask_call / flex = _flex_block_mask_call(...)). Merging this branch onto current main conflicts in unsloth/models/_block_compile.py, and the staging branch's merge of the two left _wrap.run referring to a flex it no longer binds.

Rebasing onto main and resolving the _block_compile.py conflict by hand (keeping #15756's _note_block_mask_call bookkeeping alongside the new note = False probe) should clear it; tests/test_block_cudagraphs_auto.py plus #15756's tests are the ones to rerun after.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

ℹ️ 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 04d3788 into main Oct 28, 2026
34 of 38 checks passed
@danielhanchen
danielhanchen deleted the block-cudagraphs-auto branch October 28, 2026 16:47
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Nov 1, 2026
…al devices (unslothai#15931)

Follow-up to unslothai#15768. A recheck found that auto mode could turn block
CUDA graphs on for a `device_map` model split over several GPUs. One
reviewer reproduced it with the real policy and mocked timing; a second
flagged the same gap.

## Problem

The auto decision is process-wide, but it reads timing and free memory
on one device: the device of the call that completes the measurement.
With decoder blocks split over cuda:0 and cuda:1, the measured calls can
all land on cuda:0. Passing cuda:0's headroom check then enables graphs
on cuda:1 as well. In the mocked repro, cuda:0 reported 40 GiB free and
cuda:1 0.01 GiB, and the result was still `graphs` for every block on
both shards.

Before unslothai#15768 this setup got no block CUDA graphs unless
`UNSLOTH_BLOCK_CUDAGRAPHS=1` was set.

## Change

Auto mode records the block device at the first probed call. A call on
another device turns auto off with the reason "blocks on several
devices". The first forward pass visits every shard before any timing
starts, so the decision never reaches the timing or memory reads.
Explicit `UNSLOTH_BLOCK_CUDAGRAPHS=1` is unchanged.

## Tests

- New `test_auto_blocks_on_several_devices_keep_graphs_off`: two blocks
on two (simulated) devices. On main, graphs turn on; here auto stays off
and nothing is timed.
- `tests/test_block_cudagraphs_auto.py`: 25 passed.
- Block compile suites: 135 passed, 19 skipped (CUDA only), 1 failed.
The failure is `test_sm_count_is_read_outside_the_trace`, which needs
CUDA and fails on main too. All CPU, torch 2.14.1.


## GPU results (Colab A100, single GPU, torch 2.13.0 and 2.14.1)

`unsloth/Qwen3-0.6B` 16-bit LoRA, fixed length 512, 30 steps; head vs
merge base, each with `UNSLOTH_BLOCK_CUDAGRAPHS=0` and auto.
- Auto engaged in every auto run (84 graph recordings, 0 graph breaks).
- Loss vs `=0` is within run-to-run noise: max step diff 1.4e-3 -
3.5e-3, against an A/A spread of 0.8e-3 - 2.4e-3; step-1 loss is bitwise
identical.
- Same result with lora_dropout 0.05.
- Median step: 0.22 - 0.25 s off vs 0.11 s auto.
- `tests/test_block_cudagraphs_{auto,clone,gpu}.py`: 80 passed on both
versions.

On one GPU this PR changes nothing against its merge base, as intended.
The multi-device case only exists with several GPUs; it is covered by
the CPU test.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 23, 2026
…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.
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