Skip to content

Pipeline parallel: every torch.distributed.pipelining schedule (Interleaved1F1B, LoopedBFS, zero bubble, ZBV, DualPipeV) - #15655

Merged
danielhanchen merged 21 commits into
mainfrom
dh/s9-par-interleaved
Oct 31, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
dh/s9-par-interleaved

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

apply_pipeline_parallel ran one stage per rank with GPipe or 1F1B. torchtitan and NeMo Automodel run several
stages per rank (virtual stages), which cuts the pipeline bubble from (p - 1) / m to (p - 1) / (m v), and the
zero-bubble family on top. This adds all of them for any dense decoder Unsloth can already split:

pp = apply_pipeline_parallel(
    model, mesh["pp"], n_microbatches = 8,
    schedule = "interleaved1f1b",              # or "loopedbfs", "interleavedzerobubble", "zbvzerobubble", "dualpipev"
    config = PPConfig(stages_per_rank = 2),    # default 2 for multi-stage schedules
)

How

  • The decoder is cut into pp x stages_per_rank stages (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).
  • Every local stage runs the same model object: one _PPStageModule per stage that, while it runs, swaps this
    rank's layers of its other stages for pass-throughs and the embedding for its stub. Parameter names, adapter
    keys, save_adapter and the 1-GPU LoRA initialization are unchanged; each owned layer runs exactly once per
    micro-batch.
  • Before the model is cut, the torch schedule is built on parameter-free placeholder stages (no communication), so
    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).
  • Zero-bubble schedules turn off AOTAutograd donated buffers (compiled blocks) and are refused over Unsloth's fused
    LoRA kernels (their backward runs once).
  • The step's token count reaches each stage forward from the stage context instead of a schedule kwarg: torch 2.10
    / 2.11 split backward treats every kwarg as a stage input and crashes on the int (seen on Kaggle, torch 2.11).
  • V schedules need PipelineStage._is_same_rank (torch 2.12+); older torch is refused before the cut.
  • Several stages per rank on a pp x dp (native FSDP2) mesh is refused before the cut (one FSDP2 root per stage
    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.py changes are confined to the stage context, the stage
module, PipelineParallel construction / _schedule_for / step, and apply_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-0
gradients 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.

origin/main this branch
torch 2.13.0 17 / 17 fail 18 passed
torch 2.14.1 18 passed
torch 2.10.0 13 passed, 5 skipped (V schedules refused, asserted)

Mutants (no layer swaps, loss broadcast from the wrong rank, no split-backward gate, no dry-run schedule,
is_last by rank, no fused-LoRA gate): 6 / 6 killed. Existing suites unchanged: test_pp_native_gloo 22, test_pp_fsdp2_gloo 12,
test_parallel_general_gloo 27 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:

arm (pp 2, 4 micro-batches) layers per stage vs 1-GPU GA: step-0 grads rel L2 / 20-step loss max abs step ms (single run)
1 GPU, gradient accumulation 4 (smart checkpointing) 16 A/A 0 / 0 1576
GPipe 10 / 6 0 / 5.96e-8 1157
1F1B 10 / 6 0 / 5.96e-8 1001
Interleaved1F1B, 2 stages per rank 5 / 5 / 5 / 1 0 / 5.96e-8 960
LoopedBFS, 2 stages per rank 5 / 5 / 5 / 1 0 / 5.96e-8 (against the 1-GPU run on the same numerical path) 1062
1F1B, no checkpointing 10 / 6 loss trajectory identical to 1-GPU GA 712
Interleaved1F1B, no checkpointing 5 / 5 / 5 / 1 loss trajectory identical to 1-GPU GA; each owned layer runs 4 times per step 648

(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

  • 4 / 8 GPU cells on NCCL (CPU gloo only); timing numbers are single runs, indicative of the bubble only.
  • Multi-stage with native FSDP2 over dp (refused); Trainer integration is separate work.
  • Conflicts expected with the env-driven PP Trainer work in _schedule_for / step (per-call micro-batch count
    and an eval schedule): keep both, the eval schedule over several local stages must use the multi-stage class.

… 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.
… 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).
…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.
@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-29T07:02:37.107083Z ec46cb3 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

1 similar comment
@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: 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".

Comment thread unsloth/models/pp_schedules.py Outdated
Comment on lines +248 to +249
fn = getattr(value, "__func__", value)
if callable(fn) and getattr(fn, "__module__", None) in _SINGLE_BACKWARD_MODULES:

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 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 👍 / 👎.

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 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()

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 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 👍 / 👎.

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.

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.

pre-commit-ci Bot and others added 2 commits October 28, 2026 06:05
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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 2bcc616b21

ℹ️ 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

Copy link
Copy Markdown
Member Author

pre-commit.ci run

danielhanchen and others added 5 commits October 28, 2026 00:43
…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]
@danielhanchen

Copy link
Copy Markdown
Member Author

The staging Repo tests (CPU, gloo) shard passed every test and was then stopped by its step cap:

172 passed, 7 skipped, 79 warnings in 2095.83s (0:34:55)
##[error]Process completed with exit code 124.

The shard runs under timeout --signal=INT --kill-after=60 2100. On recent runs without this PR it takes about 24 minutes of pytest. The new tests/test_pp_schedules_gloo.py lands in it (it matches tests/test_[!f]*gloo*.py) and adds roughly ten more minutes of multi-rank runs. Trimming the schedule matrix to what each schedule needs to prove (one model shape per schedule, the smallest stage count that exercises it) would bring it back under. Otherwise the gloo shard needs splitting the way #15851 split fsdp2; that can be done with the PR.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: ec46cb38ee

ℹ️ 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".

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]
@danielhanchen
danielhanchen merged commit 323696d into main Oct 31, 2026
@danielhanchen
danielhanchen deleted the dh/s9-par-interleaved branch October 31, 2026 02:57
danielhanchen added a commit that referenced this pull request Nov 4, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant