Repository navigation
Block CUDA graphs under DDP: opt-in rank agreement (UNSLOTH_BLOCK_CUDAGRAPHS_DDP=1, -20% to -27% step on 2xT4) - #18873
Conversation
…cision for every rank Auto mode kept graphs off whenever a process group had more than one rank. Under plain DDP over every rank (block weights replicated, no collective inside a block) each rank now probes as on one GPU and publishes its verdict to the process group's store; graphs start only once every rank said on, and any off verdict (GPU-bound, a batch shape change, a static rule) or no full set within UNSLOTH_BLOCK_CUDAGRAPHS_AGREE_TIMEOUT seconds keeps them off on every rank. No collective is issued, so a rank that went off early cannot hang the others. FSDP2 / tensor parallel (DTensor weights), DDP over a sub-group, context parallel and process groups without a DDP forward keep the old behaviour.
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7154108fc0
ℹ️ 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".
…OCm still exercise the agreement [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
…oint Replace the store-polling votes (probe, fast path, stock / packed fallbacks, deadlines, round keys) with one agreement. The first eager block call inside a DDP forward enrolls the run and attaches a forward pre-hook to that wrapper. At the start of grad-synced DDP forwards (the ones DDP already needs every rank to run) the hook takes one all_reduce(MIN) of each rank's local verdict, eagerly and never under Dynamo: graphs go on in the forward where every rank is ready, and any rank's veto turns them off everywhere in that same forward. After graphs are on the hook asks again (1, 2, 4, ... up to 64 synced forwards), so a later rank-local fallback (packed rows, the shape cap, a failed graph compile, a block outside the DDP module, context parallel) turns graphs off on that rank at once and on the others at the next check. Ownership, DTensor and context parallel (Unsloth's manager and torch's native context_parallel) apply on every block call, graphs on or not. FSDP2 modules, DTensor weights and sub-group DDP are read at enrollment. DDP.join(), torch.compile around the DDP model, a probe that never finishes and graphs that went on in one process before the process group came up keep graphs off on every rank. The graph variant's own compile failure falls back to plain blocks in auto mode. Traced stock calls no longer change graph state or print. UNSLOTH_BLOCK_CUDAGRAPHS_DDP=0 keeps graphs off under DDP. Tests: the gloo workers start from a clean UNSLOTH_* environment, take their port from tests._rendezvous_port, skip without gloo or on Windows, and cover ranks ready at different passes under no_sync(), late vetoes after graphs are on, a block outside the DDP module, context parallel, a probe before the process group, DDP.join() with uneven inputs, and a rank that never finishes probing. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
…e the vote under join Default under DDP is back to graphs off with no added hook or collective, as on main. UNSLOTH_BLOCK_CUDAGRAPHS_DDP=1 turns the agreement on. - Every DDP wrapper is enrolled when it is built, on every rank, and the hook sits on ddp.module so it runs after DDP's own pre-forward collectives. A rank-local first forward (eval, an extra no_sync() microbatch) no longer shifts the vote. - Under DDP.join() no vote is taken and the count stands still on every rank; a rank that forwards there turns graphs off, and the next vote after the window turns them off everywhere. - Local refusals (mode, block compile disabled, no compiled blocks, device, platform, compiled inner module, FSDP2 / DTensor layout) are votes of 0, never a skipped vote. - The vote tensor uses the module's own device for NCCL, CPU for gloo / cpu:gloo. - A superseded session (new model or re-wrap) votes 0 without touching the new state; a DDP veto is cleared for the next model once its pool is released. - Graph pool release on every veto path, stock blocks checked for ownership, DTensor revalidated when a block's parameter list changes, recompute graphs only after an owned forward, BackendCompilerFailed subclasses caught, the Dynamo False callback counted as compiled, late grad side inputs and an unprobed shape at the switch veto. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
…er torch.compile With UNSLOTH_BLOCK_CUDAGRAPHS_DDP=1 the pre-hook on ddp.module called the compiler-disabled vote step even while Dynamo traced it, so a user torch.compile(..., fullgraph=True) of the DDP model or ddp.module raised Unsupported on every rank, and fullgraph=False gained a graph break. The hook now returns while compiling, and an eager run under the compiler callback (recompile or cache-limit fallback, which can differ by rank) only vetoes locally without counting or voting, so no compiled forward takes part in the all_reduce schedule on any rank.
|
@codex review |
|
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". |
…e vote buffer The agreement hook sat on ddp.module, so a rank that compiled ddp.module traced it away while an eager rank voted, and the ranks entered different collectives. The hook now sits on the DDP wrapper, whose call stays eager under any compile of the module it wraps; a compiled module is a vote of 0. The vote tensor was built inside the same try as the all_reduce, so a rank-local allocation failure retired that rank's session and skipped the collective the others were waiting in. The buffer is now allocated at enrollment and filled in place, outside the swallowed region. Adds a gloo test for both rank-local cases. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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
Auto mode for block CUDA graphs (#15768) never turns graphs on when a process group has more than one rank.
_auto_static_reasonreturns"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 #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, oroff:<why>) to the process group's store.A rank switches graphs on, at a forward-pass boundary, only once every rank published
on. Anyoffkeeps graphs off on every rank, with the reason naming the rank, for examplerank 1: batch shape changed. So does no full set of verdicts withinUNSLOTH_BLOCK_CUDAGRAPHS_AGREE_TIMEOUTseconds (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:
get_cp_manager()is active),DistributedDataParallel._get_active_ddp_module()is None),Full finetuning, ROCm and torch < 2.13 keep their existing rules.
UNSLOTH_BLOCK_CUDAGRAPHS=0/=1keep 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
.gradclone (_param_grads_out_of_pool) runs as a tensor hook, before DDP's post-accumulate bucket hook, so buckets never read graph pool memory. Underno_sync, gradients accumulate into the cloned.gradas on one GPU.Kaggle 2x T4 A/B (2 ranks, torch 2.14.1, fp16)
Setup:
use_gradient_checkpointing = "unsloth", 1 row per rank,max_length512,padding_free = False, adamw_8bit.main(f5dfe68) as installed. Head = the same install with this branch's_block_compile.py. Every arm checks which tree it imported.torchrunwith a fresh compile cache, so each side has its own A/A pair.batch shape changedbatch shape changedbatch shape changedbatch shape changedBase reported
distributedon 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:
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:
The per-step saving pays this back after roughly 60 to 150 steps on these shapes. Block CUDA graphs: turn on automatically for fixed-shape, launch-bound LoRA runs #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 intest_block_cudagraphs_auto.py):distributed, not DDP).rank 1: GPU-bound ...).rank 1: batch shape changed).All 5 fail on
main: every case reportsdistributed, and in the timeout case rank 0 turns graphs on alone. All 5 pass here.test_block_compile*.py,test_block_cudagraphs*.pyandtest_fsdp2_native_block_cudagraphs_gloo.py: 191 passed, 29 skipped on this branch. Onmainthe only failures are the 5 new tests.Not covered
onset (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.GPU-boundon 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.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.compilearound 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.UNSLOTH_BLOCK_CUDAGRAPHS_AGREE_TIMEOUTare gone.UNSLOTH_BLOCK_CUDAGRAPHS_DDP=0turns the DDP path off.UNSLOTH_*settings and usetests._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:
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,
DistributedDataParallelis not touched, no hook is registered and no collective is added. SetUNSLOTH_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:
no_sync()microbatch) made one rank vote a forward earlier than the other and aborted the collective.ddp.module, so it runs inside the DDP forward after DDP's own pre-forward collectives (bucket rebuild, buffer broadcast, join notification).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.torch.compileinside or around the DDP wrapper, FSDP2 / DTensor) are sent as votes of 0. A rank never skips a vote.device_ids=None) and on the CPU for gloo.BackendCompilerFailedsubclasses (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.pyhas 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-localno_sync()microbatch first abort with a gloo collective mismatch (SIGABRT); an unevenjoin()window after graphs are on aborts the same way; a persistent context-parallel veto never releases the graph pool. All 15 pass now, also withUNSLOTH_COMPILE_DISABLE=1 UNSLOTH_BLOCK_CUDAGRAPHS=1in 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:
UNSLOTH_BLOCK_CUDAGRAPHS_DDP=1Session 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 unpatchedDistributedDataParallel.__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 withUNSLOTH_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.