Repository navigation
Pipeline parallel: every torch.distributed.pipelining schedule (Interleaved1F1B, LoopedBFS, zero bubble, ZBV, DualPipeV) - #15655
Conversation
… zero bubble, ZBV, DualPipeV) apply_pipeline_parallel accepts every torch.distributed.pipelining schedule. Multi-stage schedules cut pp x PPConfig.stages_per_rank stages (default 2) and keep several per rank, looped (r, r + pp, ...) or V (r, 2 pp - 1 - r). Every local stage runs the same model with only its own layers active, so parameter names, adapter keys and the 1-GPU LoRA initialization do not change. The torch schedule is built on parameter-free placeholder stages before the model is cut, so its micro-batch checks run first, and its compute order decides the gradient checkpointing gates: a rank running a forward after a backward needs zoo host slot leases (as 1F1B), and zero-bubble input / weight backward splits need non-reentrant checkpointing or none. Several stages per rank with native FSDP2 over a dp mesh is refused before the cut; pp x tp composes.
…under multi-stage schedules
… gated on torch support num_items_in_batch reaches every stage forward from the stage context instead of a schedule kwarg: torch 2.10's split backward (zero bubble) treats every kwarg as a stage input and fails on the int. V schedules (ZBVZeroBubble, DualPipeV) need PipelineStage's same-rank adjacent stage handling (torch 2.13+); older torch is refused before the model is cut. The compute-order check reads action kinds by name (int values on torch 2.10).
…eStage gained same-rank stages
…hout donated buffers Split-backward schedules (InterleavedZeroBubble, ZBVZeroBubble, DualPipeV) run the input pass as torch.autograd.grad(..., retain_graph = True). Unsloth compiles every decoder block, and AOTAutograd's compiled backward with donated buffers refuses retain_graph (Kaggle T4, torch 2.14.1: 'compiled with non-empty donated buffers'), so apply_pipeline_parallel turns torch._functorch.config.donated_buffer off for those schedules before the first forward. Tests: the setting per schedule, and zero bubble over torch.compile'd decoder layers on CPU.
…LoRA kernels A split backward runs the graph twice (input pass, then weight pass); the fused LoRA_QKV / LoRA_O / LoRA_MLP backward reuses saved activations in place, so the weight pass fails on a modified saved tensor (Kaggle T4, torch 2.14.1). Refused before the model is cut with a pointer to interleaved1f1b; full-backward schedules keep the fused kernels.
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 |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e1ee9e5193
ℹ️ 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".
| fn = getattr(value, "__func__", value) | ||
| if callable(fn) and getattr(fn, "__module__", None) in _SINGLE_BACKWARD_MODULES: |
There was a problem hiding this comment.
Unwrap partials when detecting fused LoRA kernels
For a Cohere model with LoRA targeting only the MLP projections, patch_peft_model installs the fused MLP forward as a bound functools.partial(apply_lora_mlp, inplace=False) (unsloth/models/llama.py). Unwrapping __func__ leaves that partial, whose __module__ is functools, so this detector returns no fused kernels and permits zero-bubble schedules. The inplace=False option only prevents overwriting the input; the eager SwiGLU backward still overwrites its saved e and g tensors, making the second backward pass unsafe and potentially corrupting gradients. Unwrap partials through .func before checking the kernel module, as the existing _fused_lora_modules helper does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. For Cohere, patch_peft_model binds the MLP kernel as MethodType(partial(apply_lora_mlp, inplace=False), mlp), and unwrapping only __func__ left the partial (module functools), so zero-bubble schedules were wrongly allowed. Fixed in 887b072: single_backward_kernels now peels bound methods and functools.partial layers at any nesting depth before checking the kernel module, matching the unwrapping in _fused_lora_modules. test_single_backward_kernels_unwraps_partials covers forward and _unsloth_forward installed as bound methods, bound partials, nested partials and bare partials; it fails on the previous head.
…ubble schedules [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 887b072bc1
ℹ️ 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".
| if config.sync_trainable and pp > 1: | ||
| _sync_trainable(model, pp_mesh.get_group(), dist.get_global_rank(pp_mesh.get_group(), 0)) | ||
|
|
||
| donated_off = props["split_backward"] and allow_split_backward() |
There was a problem hiding this comment.
Reject split backward over compiled blocks on older torch
On torch 2.10/2.11, selecting interleavedzerobubble for a model with compiled decoder blocks passes validation and cuts the model, but the first training step fails because torch's split backward accesses Function._input_metadata, which AOTAutograd nodes reject. The new compiled-block test explicitly skips this combination in tests/test_pp_schedules_gloo.py:478–483, but production validation has no corresponding guard: disabling donated buffers only addresses the separate retain-graph restriction. Reject this unsupported combination before modifying the model, or provide a compatible backward path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed, and the range is wider than the test comment said: split backward over compiled blocks also fails on torch 2.12. stage_backward_weight builds GradientEdges on intermediate nodes after stage_backward_input has detached the stage outputs, and autograd.grad then reads node._input_metadata. Up to torch 2.12, THPFunction holds its node through a std::weak_ptr, so the CompiledFunctionBackward node has already expired; torch 2.13 made it an owning intrusive_ptr. Fixed in 2bcc616: validation runs a cheap CPU probe of that behaviour and, when it fails, refuses InterleavedZeroBubble, ZBVZeroBubble and DualPipeV on a model with compiled blocks before anything is cut, pointing to interleaved1f1b / loopedbfs or UNSLOTH_BLOCK_COMPILE=0. The compiled-block gloo test now asserts the refusal on affected torch instead of skipping (checked on 2.10 and 2.12; 2.13 still runs and matches one process), and a unit test covers every split-backward schedule with the probe mocked.
torch's split backward (stage_backward_weight) builds GradientEdges on the intermediate autograd nodes after stage_backward_input released the graph root; autograd.grad then reads node._input_metadata. Up to torch 2.12 THPFunction holds its node through a std::weak_ptr, so an AOTAutograd CompiledFunctionBackward node is already gone and the first step fails. torch 2.13 made THPFunction own its node. Probe that capability directly (cheap CPU autograd.Function check) and refuse InterleavedZeroBubble / ZBVZeroBubble / DualPipeV over compiled blocks before the model is cut. The compiled-block test now asserts the refusal on affected torch instead of skipping. [skip ci]
|
@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". |
|
pre-commit.ci run |
…tions on torch <= 2.12
unsloth_zoo's compiled modules keep each class forward eager and call a module-level
torch.compile'd function from it (Gemma3MLP.forward -> Gemma3MLP_forward). compiled_blocks
missed that shape, so a zero-bubble / V schedule on torch <= 2.12 cut the model and then failed
in torch's weight pass ('_input_metadata' is invalid). Detect compiled callables a forward
reaches by global name or closure, and name UNSLOTH_COMPILE_DISABLE=1 in the refusal.
# Conflicts: # unsloth/models/pp_native.py [skip ci]
|
The staging The shard runs under |
…loo shard stays under its 2100 s cap
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
Conflicts in .github/workflows/studio-backend-ci.yml and tests/studio/test_backend_ci_parallel_isolation.py: main already moved the pipeline parallel gloo files (test_pp*) into their own gloo-tp-pp shard, which also picks up tests/test_pp_schedules_gloo.py, so main's version is kept for both. [skip ci]
…shards (#16634) ## Summary `Repo tests (CPU, gloo-tp-pp)` is at its 2100 s cap. On #16618, which only touches the Studio MLX worker, it was interrupted with the suite almost done: ``` !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! KeyboardInterrupt !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 174 passed, 7 skipped, 79 warnings, 320 subtests passed in 2088.59s (0:34:48) ##[error]Process completed with exit code 124. ``` The other recent runs of that job, across the last 20 PRs, took 30.5 to 36.2 minutes end to end, setup included, so a slightly slower runner is enough to tip it over. When this shard was created (#15951 split, #16447 comment) tensor plus pipeline parallel were about 1397 s. Pipeline parallel has grown a lot since then: every `torch.distributed.pipelining` schedule (#15655), per-stage sharded loading (#15656), no graph break on a non-last stage (#16167), and explicit-unscale overflow agreement (#16417). Nothing is wrong with those tests. The shard just outgrew its slot, the same way `gloo` did in #15951 and #16447. ## Change - `.github/workflows/studio-backend-ci.yml`: `gloo-tp-pp` becomes two shards with the same settings (`-n 4`, the 2100 s cap, the marker filter): - `gloo-tp`: `tests/test_tp_n*gloo*.py` (2 files); - `gloo-pp`: `tests/test_pp*gloo*.py` (8 files). - `tests/studio/test_backend_ci_parallel_isolation.py`: `test_the_command_scan_sees_the_parallel_run_and_the_serial_steps` pins the number of parallel pytest runs. It asks to be told when a shard is added, so its counts go from 12 to 13 parallel runs and from 9 to 10 repo-root shards. The selections are the old one split in two, so every file still runs exactly once. ## Testing - `tests/test_ci_repo_cpu_shards.py`: 15 passed. With `test_pp*gloo*` narrowed to `test_pp_[!n]*gloo*` as a sabotage, `test_no_file_is_dropped_or_run_twice` fails, so a dropped file is still caught. - `tests/studio/test_backend_ci_parallel_isolation.py`, `tests/test_ci_repo_cpu_shards.py` and the workflow and cache-budget guards under `tests/studio`: 164 passed. - The two new shards' run times on this PR's own CI are the real check. Both should finish well under the cap.
apply_pipeline_parallelran one stage per rank with GPipe or 1F1B. torchtitan and NeMo Automodel run severalstages per rank (virtual stages), which cuts the pipeline bubble from
(p - 1) / mto(p - 1) / (m v), and thezero-bubble family on top. This adds all of them for any dense decoder Unsloth can already split:
How
pp x stages_per_rankstages (same FLOP-balanced split, lm_head + loss on the last).Rank r keeps r, r + pp, ... (looped) or r and 2 pp - 1 - r (V: ZBVZeroBubble, DualPipeV, first and last stage on
rank 0), matching torch's own stage to rank map (asserted).
_PPStageModuleper stage that, while it runs, swaps thisrank's layers of its other stages for pass-throughs and the embedding for its stub. Parameter names, adapter
keys,
save_adapterand the 1-GPU LoRA initialization are unchanged; each owned layer runs exactly once permicro-batch.
torch's micro-batch checks run first, and its compute order decides the gates: a rank that runs a forward after a
backward needs zoo smart checkpointing slot leases (as 1F1B does today); a split input / weight backward (zero
bubble) needs no or non-reentrant checkpointing (torch.autograd.grad cannot run through reentrant checkpoints).
LoRA kernels (their backward runs once).
/ 2.11 split backward treats every kwarg as a stage input and crashes on the int (seen on Kaggle, torch 2.11).
PipelineStage._is_same_rank(torch 2.12+); older torch is refused before the cut.over a shared model is not supported); pp x tp composes; single-stage pp x dp x tp is unchanged.
New file
unsloth/models/pp_schedules.py;pp_native.pychanges are confined to the stage context, the stagemodule,
PipelineParallelconstruction /_schedule_for/step, andapply_pipeline_parallel.Tests
tests/test_pp_schedules_gloo.py(CPU gloo, 2 and 4 ranks, fp32) vs the same model in one process: losses, step-0gradients per parameter, grad norms, each local stage's output against the one-process hidden state at its
boundary, layer forward counts, saved adapter keys and values; Llama, Mistral, Qwen3, Gemma3 (tied, V placement),
reentrant checkpointing (interleaved, LoopedBFS), zero bubble with non-reentrant checkpointing, pp 2 x tp 2
interleaved, refusals that leave the model uncut.
Mutants (no layer swaps, loss broadcast from the wrong rank, no split-backward gate, no dry-run schedule,
is_lastby rank, no fused-LoRA gate): 6 / 6 killed. Existing suites unchanged:test_pp_native_gloo22,test_pp_fsdp2_gloo12,test_parallel_general_gloo27 passed.GPU, Kaggle T4x2, Llama-3.2-1B LoRA fp16, 4 micro-batches, 20 steps, vs 1-GPU gradient accumulation of the same
micro-batches:
(5.96e-8 is the float32 print resolution of the summed loss. One of the four 1-GPU references took a second
numerical path, 2.7e-4 rel L2 from the others; LoopedBFS matches that one exactly.) The same schedules on the
final head with per-stage loading (stacked PR): 1F1B and Interleaved1F1B again 5.96e-8 from 1-GPU GA.
Zero-bubble arms on Kaggle's default torch 2.11 crashed in torch's split backward on the int token-count kwarg
(fixed here). On torch 2.14.1 they next hit AOTAutograd donated buffers in Unsloth's compiled blocks (fixed
here: donated buffers off for split-backward schedules), then Unsloth's fused LoRA backward, which reuses saved
activations in place and so cannot run the second (weight) pass: zero bubble / ZBV / DualPipeV are refused before
the cut when those kernels are attached. They run for models without the fused path (CPU tests only).
Control on torch 2.14.1 without checkpointing: this branch's 1F1B is bitwise equal to main's 1F1B (both 1.5e-2
rel L2 from 1-GPU, pre-existing); Interleaved1F1B is 8.6e-3 / 5.0e-3 from main's 1F1B there, and bitwise to 1-GPU
with smart checkpointing on torch 2.11 and 2.14.
Not covered
_schedule_for/step(per-call micro-batch countand an eval schedule): keep both, the eval schedule over several local stages must use the multi-stage class.