Skip to content

Pipeline parallel x native FSDP2 data parallel x tensor parallel for dense decoders - #15204

Merged
danielhanchen merged 25 commits into
mainfrom
dh/s6-pp-fsdp2
Oct 25, 2026
Merged

danielhanchen merged 25 commits into
mainfrom
dh/s6-pp-fsdp2

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Builds on #15175 (pipeline parallelism v1) and #15174 (tensor parallelism v2). Until now apply_pipeline_parallel refused a pp mesh smaller than the world, models already sharded by FSDP2 or TP, and shard_model / apply_tensor_parallel refused a pipeline parallel model. This composes them the way torchtitan does: pp outermost, then dp, then tp. The model is split first, then each stage is made tensor parallel over the tp submesh and sharded with FSDP2 over the dp submesh.

mesh = init_device_mesh("cuda", (pp, dp, tp), mesh_dim_names = ("pp", "dp", "tp"))  # any two, or all three
model = FastLanguageModel.get_peft_model(model, ...)
stage = apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 4)   # 1. keep this rank's stage
apply_tensor_parallel(model, mesh["tp"])                                  # 2. optional
shard_model(model, FSDP2Config(mesh = mesh["dp"]))                        # 3. optional
loss = stage.step(input_ids, labels)  # this dp replica's rows; pp and tp peers pass the same rows
stage.clip_grad_norm_(1.0); optimizer.step(); optimizer.zero_grad()
stage.save_adapter("out")             # the standard 1-GPU adapter, written by global rank 0

How it works

  • FSDP2 and the schedule: shard_model shards the stage as usual, then makes the stage module that PipelineStage runs the outer FSDP2 root (it has no parameters of its own). torch's PipelineStage then runs every micro-batch backward with gradient sync off (set_requires_gradient_sync, set_reshard_after_backward, set_is_last_backward False) and reduces once per step in perform_reduce_grad, for GPipe and 1F1B alike. The code is the same in torch 2.10 to 2.14. This is the pattern torchtitan uses: after parallelizing a model part, it sets that part as stage.submod.
  • reshard_after_forward defaults to False for a pipeline stage. torchtitan does the same for PP: otherwise every micro-batch would all-gather the stage again. An explicit FSDP2Config.reshard_after_forward still overrides it.
  • Loss: each micro-batch loss is the summed token loss divided by the token count of the whole global batch. By default that count is this replica's shifted, non-ignored labels summed over dp. The backward runs on dp * loss, so FSDP2's average over dp gives the global gradient. torchtitan divides by the global token count and sets the FSDP gradient divide factor to 1. Both give the same gradient; scaling the loss also keeps Unsloth's DDP-averaged replicated parameters right. step returns the global batch loss on every rank.
  • Trainable parameters that FSDP2 leaves replicated are averaged once after the step. The schedule reduces outside autograd, so the per-backward callback is always deferred.
  • clip_grad_norm_ counts every element once over the world: each rank takes the square sum of its local gradient, divides it by the number of ranks holding a copy (the stage's world / pp ranks, over the DTensor shard dimensions), and the results are summed over every rank in fp64. torchtitan does the equivalent: a DTensor norm, then a sum over pp.
  • GradScaler: found_inf is the MAX over the world, so every rank skips the same steps.
  • save_adapter gathers FSDP2 and tensor parallel DTensors (fused tp layouts are put back in their 1-GPU order), merges the stages, and global rank 0 writes the file through PEFT's own save_pretrained.
  • pp x tp: apply_tensor_parallel accepts a split model when its tp mesh is orthogonal to the pp mesh. Pass-through layers are not regions. check_tp_dp_composition accepts pp * dp * tp == world.
  • find_shard_units skips pass-through layers. Without that, a split decoder list was not seen as a block list.

Nothing changes for code that does not compose: the 1-D pp path, TP alone and FSDP2 alone run the same code as before. The new branches only run when the model carries the pipeline marker.

Refused before any change

  • A pp mesh smaller than the world unless it is one dimension of a mesh covering every rank. A 2-D mesh passed directly is still refused.
  • step() before every other dimension of that mesh is applied (with the call to make).
  • TP or FSDP2 applied before apply_pipeline_parallel (with the right order).
  • shard_model on a split model with no mesh, with a mesh that is not orthogonal to pp / tp, with sizes that do not cover the world, or on an inner wrapper level.
  • apply_tensor_parallel after shard_model on a split model, or with a tp mesh that is not orthogonal to pp.
  • Existing refusals stay: the Trainer, for_inference, generate, MoE / MLA / hybrid stacks, trainable tied embeddings, trainable per-head norms with tp x dp, shard_frozen / cpu_offload with TP.

Tests

New tests/test_pp_fsdp2_gloo.py, gloo on CPU, fp32, 6-layer tiny models with LoRA on all linears. Each case compares against one process on the global batch: step-0 gradients (gathered), 3-step losses (rel 1e-5), clip norms (step 0 rel 1e-5), and the saved adapter (same keys and shapes, values after 3 AdamW steps).

  • pp 2 x dp 2: Llama, Qwen3, Gemma3 (tied embeddings), GPipe. Each dp replica trains on its own rows, with uneven token counts per replica.
  • pp 2 x dp 2, 1F1B with 4 micro-batches, sharded layout (one FSDP2 unit per owned layer).
  • pp 2 x tp 2: Llama, Qwen3, Gemma3.
  • pp 2 x dp 2 x tp 2 on 8 ranks: Llama.
  • pp 2 x dp 1 and pp 2 x tp 1 on 2 ranks (the layout the 2-GPU check runs).
  • Engagement: the stage module is the FSDP2 root, trainable weights are dp shards, each FSDP2 param group reduces once per step (not once per micro-batch), and no unit reshards after forward.
  • GradScaler: an inf found on one rank skips the step on all 4 ranks.
  • Refusals: order (TP or FSDP2 first), meshes, inner level, step before all dimensions are applied. Each also checks the model was not changed.

All 12 fail on the base (the composition is refused there). 9 mutants are killed: no stage root, no dp loss scaling, local token count, local loss, clip without copy count, clip over pp only, GradScaler MAX over pp only, save without gathering, reshard default kept. Existing suites pass: test_pp_native_gloo.py (19), and test_tp_native_oracle.py plus test_tp_native_gloo.py (86 passed, 1 skipped, the existing transformers 4.x StableLM skip).

GPU (Kaggle 2x T4, torch 2.14.1, transformers 5.17.0, PEFT 0.21.2): Unsloth FastLanguageModel fp16 LoRA r16, smart gradient checkpointing, GPipe with 2 micro-batches, 30 steps.

arm Llama-3.2-1B vs 1-GPU grad accumulation Qwen3-0.6B vs 1-GPU grad accumulation
pp 2 (v1) bitwise (grads, losses) grads 1.3e-2 rel (1-GPU A/A floor ~1.3e-2)
pp 2 x tp 1 bitwise grads 1.5e-2 rel
pp 2 x dp 1 (FSDP2) bitwise vs 1-GPU FSDP2 grad accumulation (grads, all 30 losses) grads 1.4e-2 rel

For the dp 1 arm the right control is native FSDP2 on one GPU with the same micro-batches. Against it, Llama pp 2 x dp 1 is bitwise equal. FSDP2 on one GPU is itself 1.4e-2 (step-0 grads) and 1.2e-5 (step-0 loss) away from plain 1 GPU, so that gap comes from FSDP2, not from the composition. In the dp 1 arm the stage module is the FSDP2 root and each stage does one FSDP2 reduce per step. The fused LoRA call counts match the pp-only arm.

What is not covered: pp x dp and pp x tp with more than one GPU per dimension on GPU (only CPU gloo here). The Trainer is still refused. No interleaved or zero-bubble schedules, and no bf16 or QLoRA composition runs.

danielhanchen and others added 18 commits October 24, 2026 15:19
sharded_loading(tp_mesh) / load_tensor_parallel(...) make from_pretrained build the model on meta and
stream the safetensors checkpoint: replicated tensors whole, attention / MLP projections as this rank's
slices (per-part slices for fused qkv and packed gate_up). The slices stay plain tensors tagged with
their full shape, so get_peft_model creates full-size LoRA factors with the same init as one GPU;
apply_tensor_parallel then wraps them into the DTensors v1 builds. A forward before
apply_tensor_parallel is refused. 16-bit safetensors checkpoints only; quantized loads are refused.
shard_model(model, FSDP2Config(mesh = mesh['dp'])) now accepts a model sharded by
apply_tensor_parallel(model, mesh['tp']) when the two meshes are the dimensions of one (dp, tp) mesh
covering the world. The frozen tp shards stay replicated over dp (fully_shard(ignored_params), torch
2.7+); FSDP2 shards the trainable LoRA DTensors over dp and reduces their tp Partial gradients itself.
Refused: no mesh / a mesh that is not the dp dimension, shard_frozen, cpu_offload, torch < 2.7, and
trainable per-head norms (their tp sum is a Parameter hook, and FSDP2 replaces the Parameters).

- The trainable-weight agreement compares and broadcasts the local tensors of DTensor parameters.
- Fused / packed layouts are also recorded on the owning module, so adapter saving and gathered grads
  keep the 1-GPU order after FSDP2 replaces the Parameter objects.
- tp_clip_grad_norm_ handles 2-D gradients (each element counted once over its replicas).
- native_clip_grad_norm_ counts FSDP2's _StridedShard as a shard dimension: newer torch does not report
  it as is_shard(), so those norms were not reduced over dp.
- save_tp_adapter accepts a tp mesh smaller than the world when the dp dimension covers the rest.
The Trainer no longer refuses a model sharded by apply_tensor_parallel (tp only, or dp x tp after
shard_model over mesh['dp']). tp_native.tp_trainer_setup runs around Trainer.__init__:
- accelerate does not wrap the tp ranks in DDP (prepare_model keeps only the autocast wrap; native FSDP2
  prepares a dp x tp model itself),
- the dataloader is sharded over dp only, so the tp ranks of a replica read the same batches,
- clip_grad_norm_ uses tp_clip_grad_norm_, and float16 gets a ShardedGradScaler (one inf decision for
  all ranks, initial scale divided by dp),
- trainer.save_model() writes the standard 1-GPU adapter (collective),
- the generated TRL trainers skip their trailing model.for_inference() (it would route the decoder
  layers onto decode paths outside the tensor parallel regions).
The loss needs no change: the token count gathered over the world counts each replica's tokens tp
times and the Trainer's loss scale multiplies by dp * tp, which FSDP2's mean over dp turns into the
token mean over the dp replicas.
Refused with a reason: Trainer checkpoints / resume, evaluation, bitsandbytes / paged / GaLore
optimizers, DeepSpeed, accelerate FSDP / ParallelismConfig, iterable datasets, model_init, and a tp
mesh that does not cover the world without shard_model over the dp dimension.
… parallel

apply_pipeline_parallel(model, mesh['pp']) accepts a pp mesh that is one dimension of a mesh covering every
rank; apply_tensor_parallel(model, mesh['tp']) and shard_model(model, FSDP2Config(mesh = mesh['dp'])) then
parallelize each stage (torchtitan order: pp, then tp inside the stage, then FSDP2 over dp). The stage module
becomes the outer FSDP2 root, so PipelineStage reduces gradients once per step. The loss averages over the
global batch tokens, clip_grad_norm_ counts every element once over the world, the GradScaler skip is global,
and save_adapter writes the 1-GPU adapter from global rank 0. Wrong order and non-composable meshes are refused
before any change.
# Conflicts:
#	unsloth/models/fsdp2_native.py
#	unsloth/models/tp_native.py
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T08:18:58.664802Z fe56a1b 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.

@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: 0bf4ad263c

ℹ️ 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 on lines +1056 to +1057
count = count.to(device = device, dtype = torch.int64)
dist.all_reduce(count, group = dp_group)

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 Use the compute device for offloaded pipeline stages

When composing PP with FSDP2Config(cpu_offload=True) on a CUDA/NCCL mesh, FSDP2 stores the sharded parameters on CPU, so PipelineParallel.device (which returns the first parameter's device) becomes CPU. This moves the token-count tensor to CPU and attempts an NCCL all-reduce on it, causing the first step() to fail. The same inferred device also feeds pipeline communication-buffer allocation. Preserve the stage's CUDA compute device independently of parameter storage, or reject CPU offload before sharding until this composition is supported.

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 the latest push: shard_model now refuses FSDP2Config(cpu_offload = True) on a pipeline parallel model before anything is sharded (the stage's device for token counts and pipeline buffers would otherwise follow the offloaded parameters to the CPU). Covered by the refusal checks in tests/test_pp_fsdp2_gloo.py.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a7a8d03b88

ℹ️ 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 added a commit that referenced this pull request Oct 25, 2026
## Summary

#15205 (FP8 block GEMM: route empty inputs to the Triton kernel) added a
CUDA case to `tests/test_fp8_torchao_import_route.py` that skips on
`torch.cuda.is_available()`.
`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
rejects that, so `Repo tests (CPU, studio)` is red on unrelated PRs (for
example #15204, base `3b2773c5`):

```
test_fp8_torchao_import_route.py:188: torch.cuda.is_available()
```

`tests/_zoo_aggressive_cuda_spoof.py` patches
`torch.cuda.is_available()` to True for the whole process, so on a
CPU-only runner this skip stops skipping whenever it shares a session
with `tests/version_compat` or `tests/vllm_compat`. The test is wrong
here, not the kernel. It is the same fix #15194 made for
`test_norm_arch_warps.py`.

## Change

- Skip on `has_real_cuda()` from `tests/_shared/real_accelerator.py`.
The `torchao_blockwise_gemm is None` half of the condition is unchanged.

## Verification

- `tests/python/test_accelerator_skip_guards.py`: `1 failed, 23 passed`
on main, `24 passed` with this change.
- `tests/test_fp8_torchao_import_route.py` on CPU: `28 passed, 1
skipped`. `has_real_cuda()` is True on a CUDA host (checked when #15194
landed), so the case still runs on GPU runners.
@danielhanchen

Copy link
Copy Markdown
Member Author

Status of the reds on this branch (base 3b2773c5):

  • test_pp2_x_tp2_matches_one_process[gemma3] (new in this PR) misses the one-process reference on the first step: loss 1.042721 vs 1.042614 against abs = 1e-5, then 1.43665 vs 1.43658 and 2.47556 vs 2.47442. The other architectures pass, so this looks specific to gemma3 under PP2 x TP2 (its embedding scale, softcapping or the tied head across the stage boundary are the usual suspects) rather than a tolerance that is merely tight. The gap grows over the three steps.
  • Repo tests (CPU, rest): the encoding guards and both test_ppo_trainer_patches.py unwrap tests are from main and are fixed by Name the encoding on the tensor parallel index reads; give the PPO unwrap test _decode_graphs #15209.
  • Repo tests (CPU, studio): test_no_skip_guard_reads_a_spoofable_accelerator_probe on test_fp8_torchao_import_route.py:188 is from main and is fixed by Skip the torchao blockwise GEMM CUDA case on a real CUDA probe #15211.

Merging main in clears the last two.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: fe56a1bfae

ℹ️ 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 85234fe into main Oct 25, 2026
@danielhanchen
danielhanchen deleted the dh/s6-pp-fsdp2 branch October 25, 2026 10:59
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