Repository navigation
Pipeline parallel x native FSDP2 data parallel x tensor parallel for dense decoders - #15204
Conversation
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.
…A init on sharded_loading slices [skip ci]
…cheduler [skip ci]
…allel setup [skip ci]
… 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
|
@codex review |
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. |
There was a problem hiding this comment.
💡 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".
| count = count.to(device = device, dtype = torch.int64) | ||
| dist.all_reduce(count, group = dp_group) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
## 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.
|
Status of the reds on this branch (base
Merging main in clears the last two. |
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
Builds on #15175 (pipeline parallelism v1) and #15174 (tensor parallelism v2). Until now
apply_pipeline_parallelrefused a pp mesh smaller than the world, models already sharded by FSDP2 or TP, andshard_model/apply_tensor_parallelrefused 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.How it works
shard_modelshards the stage as usual, then makes the stage module thatPipelineStageruns the outer FSDP2 root (it has no parameters of its own). torch'sPipelineStagethen runs every micro-batch backward with gradient sync off (set_requires_gradient_sync,set_reshard_after_backward,set_is_last_backwardFalse) and reduces once per step inperform_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 asstage.submod.reshard_after_forwarddefaults to False for a pipeline stage. torchtitan does the same for PP: otherwise every micro-batch would all-gather the stage again. An explicitFSDP2Config.reshard_after_forwardstill overrides it.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.stepreturns the global batch loss on every rank.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.found_infis the MAX over the world, so every rank skips the same steps.save_adaptergathers 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 ownsave_pretrained.apply_tensor_parallelaccepts a split model when its tp mesh is orthogonal to the pp mesh. Pass-through layers are not regions.check_tp_dp_compositionaccepts pp * dp * tp == world.find_shard_unitsskips 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
step()before every other dimension of that mesh is applied (with the call to make).apply_pipeline_parallel(with the right order).shard_modelon 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_parallelaftershard_modelon a split model, or with a tp mesh that is not orthogonal to pp.for_inference,generate, MoE / MLA / hybrid stacks, trainable tied embeddings, trainable per-head norms with tp x dp,shard_frozen/cpu_offloadwith 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).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), andtest_tp_native_oracle.pyplustest_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.
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.