Repository navigation
Tensor parallelism v2: sharded loading, data parallel x tensor parallel, and the Trainer - #15174
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.
|
@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: c958357649
ℹ️ 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".
| self.__class__ = type( | ||
| "UnslothTensorParallelDataAccelerator", | ||
| (cls,), | ||
| {"num_processes": property(lambda s: dp_size), "process_index": property(lambda s: dp_rank)}, | ||
| ) |
There was a problem hiding this comment.
Seed dataloader workers by data-parallel rank
With dataloader_num_workers > 0 and a stochastic dataset transform or collator, TP peers can still receive different inputs despite selecting the same rows. In the inspected Transformers implementation, Trainer._get_dataloader binds worker_init_fn to seed_worker(..., rank=self.args.process_index), and seed_worker adds num_workers * rank to the seed. Accelerate preserves that callback, so temporarily overriding only the accelerator's process_index here leaves workers seeded by global rank. The TP reductions then combine projections computed from different examples or augmentations, silently corrupting training. Rebind the worker initializer to the DP rank as well, or explicitly reject this configuration.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ad11ceb. When the Trainer's worker_init_fn is its partial(seed_worker, ..., rank = ...), the tensor parallel data loader hook rebinds rank to the data parallel rank before accelerate copies it, so every tp peer of a replica seeds its workers the same way. Covered by test_trainer_dataloader_workers_are_seeded_by_dp_rank (fails before the change).
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2a2267750b
ℹ️ 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 mesh.size() != world: | ||
| raise ValueError( | ||
| f"Unsloth: tp_clip_grad_norm_ got a gradient on {mesh.size()} of {world} ranks; a 2-D " | ||
| "mesh must span the world." | ||
| ) |
There was a problem hiding this comment.
Handle DP-only gradients in tensor-parallel clipping
With DP × TP and a trainable parameter outside the TP regions, such as modules_to_save=["lm_head"], FSDP2 shards that initially plain parameter over the 1-D DP mesh, while the projection LoRA gradients use the full 2-D mesh. Consequently, tp_clip_grad_norm_ selects _clip_over_world and this check raises on the head gradient because its mesh contains only the DP ranks. This breaks the first clipping step for an otherwise permitted configuration, including through the Trainer hook. Handle DP-submesh gradients and account for their replication across TP ranks instead of requiring every gradient mesh to span the world.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 64be3f6. A gradient on a submesh of the world (the dp mesh, for a trainable parameter outside the tensor parallel regions such as a modules_to_save lm_head) is the same on every tp rank, so it now counts world / mesh.size() more copies instead of raising. New case in test_tp2_x_fsdp2_dp2_matches_one_process with modules_to_save = ["lm_head"]: the clip norm matches the one-process fp64 norm to 1e-5 and training matches.
| # A plain local tensor tagged with its full shape: nn.Linear keeps the full in / out features, so | ||
| # get_peft_model builds full-size LoRA factors with the 1-GPU init (a DTensor would make PEFT size | ||
| # them from the shard). apply_tensor_parallel wraps it into the DTensor. | ||
| new = nn.Parameter(local.contiguous(), requires_grad = old.requires_grad) |
There was a problem hiding this comment.
Reject weight-dependent LoRA initialization on preloaded slices
When sharded loading is followed by get_peft_model(..., init_lora_weights="pissa") with TP greater than one, retaining nn.Linear's full feature counts does not preserve full-size factors: lora_init._pissa_init decomposes the actual sliced weight and replaces the LoRA factor data with shard-sized tensors. apply_tensor_parallel subsequently shards those factors again using the full projection dimensions, producing incompatible local shapes; it also synchronizes factors calculated from different residual decompositions. Reject weight-dependent initializers on preloaded slices, or implement an initialization path that produces factors and residuals consistent with the full checkpoint.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 64be3f6. apply_tensor_parallel now refuses a sharded_loading model whose LoRA config uses a weight-dependent init_lora_weights (anything other than True / False / "gaussian": PiSSA, OLoRA, CorDA, EVA, LoftQ), before any module is changed, and points to the full load path. Covered by test_sharded_loading_refuses_weight_dependent_lora_init (PiSSA refused, gaussian accepted).
…A init on sharded_loading slices [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 64be3f62c8
ℹ️ 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".
| _install_tp_accelerate_hooks() | ||
| return True |
There was a problem hiding this comment.
Split mixed optimizer parameter groups for TP-only training
For TP-only training with a trainable parameter outside the TP regions, such as a float32 modules_to_save=["lm_head"], the Trainer places plain tensors and LoRA DTensors in the same weight-decay group. With adamw_torch_fused or CUDA foreach AdamW, the optimizer then passes both tensor kinds to one kernel and fails on the first update. The group-splitting logic in fsdp2_native.py does not cover this path because it requires native-FSDP2 models or parameters. Add equivalent optimizer preparation for TP-only Trainers, splitting mixed groups before the scheduler is constructed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest push. For a tensor parallel model the Trainer's create_optimizer is wrapped so mixed DTensor / plain groups are split (the same split_param_groups the native FSDP2 path uses) right after the optimizer is built and before create_scheduler records the groups. Covered by test_trainer_splits_mixed_optimizer_groups_for_tp_only (tp 2 with modules_to_save = ["lm_head"]: no mixed group, losses match one process; fails before the change).
…cheduler [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
|
The latest
The |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e296bae9cc
ℹ️ 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".
| optimizer = create_optimizer(*args, **kwargs) | ||
| from .fsdp2_native import _inner_optimizer, _split_mixed_param_groups | ||
|
|
||
| _split_mixed_param_groups(_inner_optimizer(optimizer)) |
There was a problem hiding this comment.
Reject prebuilt schedulers before splitting optimizer groups
For TP-only training with mixed DTensor/plain parameters (for example, modules_to_save=["lm_head"]), passing Trainer(optimizers=(optimizer, scheduler)) reaches this split after the supplied scheduler has already recorded the original parameter groups. A LambdaLR-based scheduler retains one base LR and lambda per original group, so newly added groups are left unscheduled, silently applying the wrong learning rate during training. Unlike the native FSDP2 setup, this path does not reject that configuration. Refuse a prebuilt scheduler when splitting is necessary, or explicitly rebuild its per-group state.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest push. When the Trainer was given optimizers = (optimizer, scheduler) and the optimizer mixes tensor parallel DTensors with plain trainable parameters, the TP create_optimizer hook now raises before splitting, pointing to split_param_groups(...) (build the optimizer from it before the scheduler, or pass only the optimizer). Without a prebuilt scheduler it still splits before create_scheduler. Covered in test_trainer_splits_mixed_optimizer_groups_for_tp_only (LambdaLR pair refused; fails before the change).
|
@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". |
…wrap test _decode_graphs (#15209) ## Summary Two merges left `Repo tests (CPU, rest)` red on main (for example on #15199, base `0705fa58`): 1. **#15174 (tensor parallelism v2)** reads `model.safetensors.index.json` with a bare `open()` at `unsloth/models/tp_native.py:1636` and `:1660`, and its new test does the same at `tests/test_tp_native_oracle.py:697`. #15185 (padded batches vs padding-free) added `tests/test_padding_choice.py:267` with a bare `read_text()`. The two encoding guards flag all four: ``` tests/test_runtime_text_encoding.py::test_shipping_code_names_an_encoding ['unsloth/models/tp_native.py:1660: open()', 'unsloth/models/tp_native.py:1636: open()'] tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding ['tests/test_padding_choice.py:267: read_text()', 'tests/test_tp_native_oracle.py:697: open()'] ``` The two `tp_native.py` sites are product code, and the guard is right about them: a checkpoint index read under a non-UTF-8 Windows locale can fail or mis-decode. 2. **#15188 (decode graphs on by default for RL)** wrapped `unsloth_unwrap_model_for_generation`'s generate in `_decode_graphs.rl_generation()` and calls `_decode_graphs.release_for_training(model)` on the way back to training. `tests/test_ppo_trainer_patches.py` lifts that function out of `rl.py` with `ast` and never gave it `_decode_graphs`, so both unwrap tests stop with `NameError: name '_decode_graphs' is not defined`. ## Change - `tp_native.py`, `test_tp_native_oracle.py`, `test_padding_choice.py`: `encoding = "utf-8"` on the four reads. - `test_ppo_trainer_patches.py`: the lifted function gets a `_decode_graphs` whose `rl_generation` is the real scope from `unsloth/models/_decode_graphs.py` (loaded by file path), with entering it and `release_for_training` recorded in the existing `calls` list. The PPO-policy test now asserts the full order: `for_inference`, `rl_generation`, `release_for_training`, `for_training`. The plain-model test asserts generation happens inside the scope before the release. ## Verification - On main: the two encoding guards fail and both unwrap tests raise `NameError`. With this change the encoding guards give `25 passed`, and `test_ppo_trainer_patches.py`, `test_padding_choice.py` and `test_tp_native_oracle.py` give `114 passed, 4 skipped`. - Sabotage, each against `rl.py`: 1. generate outside `_decode_graphs.rl_generation()`: both unwrap tests fail 2. no `release_for_training` before training: both unwrap tests fail - `tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process` (5 cases) passes on main locally.
…dense decoders (unslothai#15204) Builds on unslothai#15175 (pipeline parallelism v1) and unslothai#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. ```python 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. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…d copy (#15264) `tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process[llama-True-lora_kwargs4]` fails now and then in `Repo tests (CPU, rest)` on unrelated PRs (#15159, #15174, #15217, #15218, #15222, #15225) with only `AssertionError: base_model.model.lm_head.weight`. Gradients, losses and norms all match in those runs. Only the saved `lm_head` copy differs. ## Cause The test, not the product. That case trains a full `lm_head` copy (`modules_to_save`, 512000 entries) with AdamW at lr 1e-2 and the default eps of 1e-8. At g = 0, Adam's `g / (sqrt(v) + eps)` has slope lr / eps = 1e6. Measured on main on this host: | | value | | --- | --- | | median step-0 lm_head grad | 5.7e-6 | | entries with step-0 grad below 1e-8 | 313 | | step-0 grad of the 10 worst saved-weight entries | 4e-11 to 7e-9 | | worst saved-weight diff / tolerance | 0.46 | So reduction-order noise of about 1e-12 on a near-zero gradient becomes about 5e-6 of weight. That is already half the `atol = 1e-5` here. A runner whose CPU kernels sum in a different order goes over it. ## Fix - Both arms use `AdamW(eps = 1e-6)`. The optimizer is still identical on both sides, and 1e-6 is small next to the typical gradient, so the head still trains. The worst entry drops to 0.0075 of the tolerance (60x headroom). - The saved-weight assert now keeps `assert_close`'s mismatch detail. It used to print only the key, which is why the CI logs never showed how far off the weight was. ## Verification - `tests/test_tp_native_gloo.py`: 38 passed. - Sabotage on the last step, after the norms are taken, so only the saved weight can catch it: - TP arm skips the lm_head update: fails, 511627 / 512000 mismatched, max abs diff 1.0e-2. - Each dp half's lm_head gradient scaled by +/-15% (a stand-in for a missing dp reduction): fails, 493693 / 512000 mismatched, max abs diff 8.1e-4. - No sabotage: passes.
…efused up front (unslothai#15230) Follow-up to unslothai#15174 (tensor parallelism v2) and unslothai#15175 (pipeline parallelism v1). It runs TP and PP over every causal LM architecture transformers 5.17 knows (178 in `MODEL_FOR_CAUSAL_LM_MAPPING`). The goal: every architecture either trains like one process or is refused before the model is touched, never a crash halfway through, silently wrong numbers or a partly mutated model. ### Sweep result Tiny random-weight copies of each architecture's default config, CPU gloo, 2 ranks, fp32, LoRA r=4, compared against one process (rtol 1e-4). A refusal only counts as clean if parameters, buffers, module tree, hooks, markers and `requires_grad` are unchanged. | mode | match one process (before / after) | refused cleanly (before / after) | broken (before / after) | |---|---|---|---| | TP | 51 / 55 | 103 / 103 | 4 / 0 | | TP + sharded loading | 48 / 52 | 106 / 106 | 4 / 0 | | PP GPipe | 53 / 60 | 105 / 98 | 0 / 0 | | PP 1F1B + gradient checkpointing | 53 / 60 | 105 / 98 | 0 / 0 | 20 model types had no buildable tiny model. Four deliberately broken variants of the code (no all-reduce, mutate-then-refuse for TP and PP, a 1% PP loss scale) were all caught. ### Fixes - **Gemma 3n under TP (silent wrong gradients).** Its MLP's activation sparsity takes mean / std over the intermediate dimension, which TP splits across ranks: loss 6.3461 vs 6.3424, LoRA gradients off by about 70%. The real model uses sparsity on its first 10 layers. MLP forwards that reduce over the feature dimension or read the global intermediate size are now refused. - **XGLM, MVP, TrOCR under TP (crash in the first forward).** They reshape with `self.embed_dim` or with the width read from `hidden_states.size()`. Both patterns are now refused up front. - **A decoder block shared by several layers (Zamba2 style).** TP crashed halfway through sharding and left a partly mutated model: shared blocks are now sharded once, and a weight shared by two projections is refused. Under PP, each stage trained its own copy of the shared LoRA: refused before the split. - **BART / Whisper / Pegasus / MBart / PLBart / TrOCR / MVP decoders under PP (2x loss).** Their forwards ignore `num_items_in_batch`, so the summed micro-batch loss was n_microbatches times too large. A forward that neither names `num_items_in_batch` nor passes `**kwargs` to `loss_function` is refused. - **CodeGen under TP.** Its fused `qkv_proj` would have been split as [q, k, v] blocks; a structural `qkv_proj` must now be sliced by `num_key_value_heads * head_dim` in its forward. - **Merged / GGUF / torchao / OpenVINO exports under TP or PP.** Before, TP wrote shard-sized weights (or raised after writing files) and PP wrote all-zero placeholder embeddings / lm_head. All 19 export entry points now refuse on every rank before anything is written, pointing to `save_tp_adapter` / `pp.save_adapter` and a single-process export. - **TP gradient clipping host sync.** `tp_clip_grad_norm_` used `float(total)` and a Python branch, one host sync per clip. It now scales with a tensor clamp (as `torch.nn.utils.clip_grad_norm_` does) and returns a tensor; a coefficient of 1 leaves gradients bitwise unchanged. - **PP checkpointing tests on transformers 4.57.6.** The one-process reference used reentrant checkpointing without input gradients; the test now enables them, as transformers 5.x does for PEFT models. ### Newly supported - TP: GPT-J (`fc_in` / `fc_out`, `dense_h_to_4h` / `dense_4h_to_h`), HunYuan dense and LFM2 (per-head q / k layernorms), Apertus (scalar xIELU parameters replicated). - PP: GPT-2, GPT-SW3, GPT-Neo, GPT-BigCode, OPT, BioGPT (learned position tables kept on the first stage). ### Still refused (and what support would need) MoE (expert sharding or expert parallelism, plus the router aux loss across PP stages), MLA (shard `q_b_proj` / `kv_b_proj` by heads), hybrid linear-attention stacks under PP (mixed layer classes; TP already passes with those layers replicated), fused-qkv layouts such as Bloom / Falcon / MPT / GPT-2 `c_attn` (layout rules from the forward's view shape, ALiBi slopes per local head), full-width q / k norms such as OLMo2 / 3 (a distributed RMSNorm). ### Tests New `tests/test_parallel_general_gloo.py`, 26 tests, parametrised over the swept architectures (about 20 s). All fail on main and pass here. Existing suites: `test_tp_native_gloo.py` + `test_tp_native_oracle.py` 86 passed, 1 skipped; `test_pp_native_gloo.py` 22 passed. The PP checkpointing tests also pass on transformers 4.57.6 / PEFT 0.18 / torch 2.10. Not covered: GPU (NCCL, bf16 / fp16, 4-bit QLoRA sharding, Unsloth's fast forwards and fused kernels, torch.compile), sizes beyond tp=2 / pp=2, multi-node. The export refusal is exercised on CPU with HF + PEFT models; GGUF / torchao / OpenVINO are covered by a check that every entry point carries the guard. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…s shard), and the fp16 start scale on sub-meshes (unslothai#15225) Builds on unslothai#15174 (tensor parallel v2, merged): it reuses and generalises its safetensors slice reader. ### Why Under native FSDP2 (`UNSLOTH_FSDP2=1`) every rank loads the whole model before `shard_model`, so a model that does not fit one GPU cannot be loaded at all, even though FSDP2 would only keep 1 / world of it per rank afterwards. Qwen3-8B in 16-bit (16.4 GB) on 2x T4: every rank runs out of memory at load. ### What **Sharded loading (opt-in).** ```python from unsloth.models.fsdp2_load import fsdp2_sharded_loading, load_fsdp2_sharded with fsdp2_sharded_loading(): # any loader that ends in transformers from_pretrained model, tokenizer = FastLanguageModel.from_pretrained(name, load_in_4bit = False, ...) model = FastLanguageModel.get_peft_model(model, ...) trainer = SFTTrainer(model = model, ...) # UNSLOTH_FSDP2=1: shard_model installs the shards ``` or `UNSLOTH_FSDP2_SHARDED_LOAD=1` next to `UNSLOTH_FSDP2=1`, which runs FastLanguageModel / FastModel / FastVisionModel `from_pretrained` inside the context (outermost call only). Nothing changes without either. - The model is built on meta. Every `nn.Linear` weight except the output head is read from safetensors as this rank's FSDP2 dim-0 chunk (the rows `fully_shard` keeps, `torch.chunk` semantics, so uneven and empty chunks match), via `get_slice`, so only those bytes are read. Everything else (embeddings, norms, biases, buffers) is read whole, as the full load does. - A chunk stays a plain tensor tagged with its full shape: `nn.Linear` keeps its full features, so `get_peft_model` builds full-size LoRA with the same init as one GPU. A forward before `shard_model` is refused. - `shard_model` swaps each chunk for a full-shape meta placeholder (so the layout planner sees the whole model), runs `fully_shard`, and installs the chunk as the FSDPParam local shard (padded as `fully_shard` pads it). The full weight never exists on any rank. A chunk the layout keeps replicated (fit layout frozen weights, minority-dtype parameters) is all-gathered back, which is exactly what the full load holds. - The reader in `tp_native.py` is now shared (`_fill_from_checkpoint`, `_SliceReader.rows`, `_sharded_from_pretrained`) and maps checkpoint keys through transformers' conversion renames, so VLMs whose checkpoints use the legacy names (`model.layers.*` for `model.language_model.layers.*`) load; tensors a `WeightConverter` builds from several checkpoint tensors are refused with a clear message. - Refused with a clear message: 4-bit / 8-bit / pre-quantized loads (QLoRA still loads the full quantized model; rank-0 CPU quantize + scatter is a follow-up), 2-D (HSDP) meshes, `cpu_offload`, `shard_placement_fn`, a mesh other than the one loaded over, and weight-dependent LoRA inits (PiSSA, OLoRA, ...). **fp16 start scale.** The Trainer multiplies every rank's loss by `num_processes` (over the tensor parallel size), so the fp16 start scale must be divided by that, not by the FSDP2 mesh size. They differ on a sub-mesh smaller than the world: two 2-rank meshes of 4 ranks started 2x too high and the first step overflowed. CP = 2, DP = 1 shards over the world, where both agree (now pinned by a test). ### Tests (CPU gloo, 2 and 4 ranks; every new test fails before except the CP = 2 pin) `tests/test_fsdp2_native_sharded_load_gloo.py` against the full load + `shard_model` on the same checkpoint (tiny models saved as multi-file safetensors): | case | local shards (incl. padding) | 3 steps (losses, clip norms, final shards) | bytes read | |---|---|---|---| | Llama, `intermediate_size = 37` (uneven chunks), LoRA, sharded layout | bitwise | bitwise | own rows only | | same, fit layout (frozen chunks gathered back) | bitwise | bitwise | own rows only | | same, full finetune | bitwise | bitwise | own rows only | | Qwen3 LoRA / full finetune | bitwise | bitwise | own rows only | | Qwen2.5-VL (vision tower + projector linears sliced) LoRA | bitwise | bitwise | own rows only | Byte counters: each rank's sliced bytes equal its own chunk sizes, the two ranks together read every sharded tensor exactly once, and whole reads equal the replicated parameters. Plus refusals, `_chunk_rows` against `torch.chunk` for many shapes, and the env flag being inert without `UNSLOTH_FSDP2`. `tests/test_fsdp2_native_fp16_scale_mesh_gloo.py`: CP = 2, DP = 1 (passes before and after: no bug there) and two 2-rank sub-meshes of 4 ranks (before: start scale 32768 instead of 16384). Existing suites unchanged: `test_tp_native_gloo.py` + `test_tp_native_oracle.py` 86 passed, 1 skipped; `test_fsdp2_native_*` + `test_fsdp2_perf_layout_gloo.py` + `test_context_parallel_fsdp2_gloo.py` 268 passed, 2 skipped. ### GPU (Kaggle 2x T4, torch 2.14.1, transformers 5.17.0, PEFT 0.21.2) Qwen3-0.6B, LoRA r16 on all 7 projections, fp16 autocast, AdamW 2e-4, seq 512, bs 2 per rank, 20 steps, sharded layout, custom loop: | arm | load peak GiB / rank | after shard_model | train peak | loss step 0 / step 20 | |---|---|---|---|---| | full load A | 1.118 / 1.110 | 0.582 / 0.574 | 1.638 | 0.952910 / 0.3927 | | full load B (A/A) | 1.118 / 1.110 | 0.582 / 0.574 | 1.638 | 0.952910 / 0.3845 | | sharded load | **0.708 / 0.700** | 0.582 / 0.574 | 1.638 | 0.952910 / 0.3833 | - The FSDP2 local shards right after `shard_model` hash identically (sha256 over every local tensor) on both ranks for the full and the sharded load. - Step-0 loss is bitwise identical in all arms. Later steps differ by GPU nondeterminism: sharded vs full max abs loss diff 0.0094 (mean 0.0021) over 20 steps, inside the A/A pair's 0.0082 (mean 0.0018). - Trainer path (`UNSLOTH_FSDP2=1`, `SFTTrainer`, fp16 GradScaler, 10 steps) with `UNSLOTH_FSDP2_SHARDED_LOAD=1` vs without: the sharded path engaged on both ranks (byte counters recorded), load peak 0.708 vs 1.118 GiB, max abs loss diff 2.5e-4. Qwen3-8B 16-bit (16.4 GB, does not fit one T4): | arm | load peak GiB / rank | after shard_model | train peak (5 steps) | losses | |---|---|---|---|---| | full load per rank (today) | out of memory at load (14.18 of 14.56 GiB) | | | | | sharded load, seq 512, bs 1 | **8.80 / 8.79** | 7.72 / 7.71 | 13.29 | 0.845, 0.805, 0.776, 0.751, 0.730 | | sharded load, seq 256, bs 1 | 8.80 / 8.79 | 7.72 / 7.71 | 13.27 | 1.676, 1.590, 1.525, 1.474, 1.431 | Each rank read 6.95 GB of linear-weight rows (exactly half of all linear weights) and 2.49 GB whole (embeddings, head, norms). Load took 26 to 40 s per rank. ### Not covered - QLoRA (4-bit) sharded loading: refused for now. - HSDP / 2-D meshes, `cpu_offload`: refused for now. - Tested on CUDA (T4) and CPU only. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
_refuse_weight_dependent_lora_init (unslothai#15174) refuses every init_lora_weights outside True / False / "gaussian" as "depends on the base weight". PEFT's orthogonal init does not: it draws the factors from torch.randn sized by the layer's in_features / out_features, which sharded loading keeps at the full sizes, and reads only the weight's dtype. So the factors come out full-size, the same shape as gaussian's, and _sync_trainable gives every rank rank 0's draw. Add it to the allowlist; MiCA, which takes lora_B from the base weight's singular vectors, stays refused. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…l" (#15218) ## What `_refuse_weight_dependent_lora_init` in `unsloth/models/tp_native.py` (from #15174) rejects any `init_lora_weights` outside `True` / `False` / `"gaussian"` once `load_tensor_parallel(...)` has put sharded slices on the model, with the message "depends on the base weight". For `"orthogonal"` that is not true, so `get_peft_model(model, LoraConfig(init_lora_weights = "orthogonal"))` followed by `apply_tensor_parallel` at tp > 1 raises for no reason. ## Why it is safe to allow PEFT's `LoraLayer.orthogonal_init` (peft 0.21, `tuners/lora/layer.py`) builds both factors from `torch.randn` sized by `self.in_features` / `self.out_features` and reads only `weight.dtype`. Sharded loading keeps the `nn.Linear` at the full in / out features (the slice carries `_unsloth_tp_full_shape`), so the factors come out full-size, exactly the shape gaussian produces, and `_sync_trainable` then gives every rank rank 0's draw. PiSSA / OLoRA / CorDA / EVA / LoftQ / MiCA do read the weight (MiCA takes `lora_B` from the base weight's singular vectors) and stay refused. ## How Add `"orthogonal"` to the allowlist tuple; name it in the message and the docstring (which now also lists MiCA). Nothing else changes. ## Verification `tests/test_tp_native_gloo.py::test_sharded_loading_refuses_weight_dependent_lora_init` now also runs the orthogonal case on the 2-rank gloo mesh (tp = 2, r = 4, `target_modules = "all-linear"`) and asserts it is allowed and the model ends up tensor parallel, next to the existing pissa (refused) and gaussian (allowed) cases. | | pissa | gaussian | orthogonal | |---|---|---|---| | main (62fdd8f) | refused | allowed | **refused** (extended test fails here) | | this branch | refused | allowed | allowed (1 passed) | CPU only, torch 2.13 + peft 0.21.2. `ruff check`, `enforce_kwargs_spacing.py` and the `ruff-format-with-kwargs` hook pass. ## Follow-up - Merged current main. - PEFT's orthogonal init is identical in PEFT 0.18.0 and 0.21.2. It reads only `r`, `in_features`, `out_features` and the base weight's dtype, and draws from `torch.randn`, so the factors are full-size and never read weight values. It guarantees `B @ A == 0` with both factors non-zero; the rows of `A` are not orthonormal. - New `test_sharded_loading_random_lora_init_matches_one_process[orthogonal|gaussian|True]` (2 gloo ranks, ranks seeded differently on purpose): - After the tp rank 0 broadcast, the LoRA factors are bit-identical to a one-process init from rank 0's seed, and identical on both ranks. - For orthogonal, `B @ A == 0`. - One forward / backward / AdamW step matches the unsharded run: logits, grads, loss, grad norm and the updated params. - With `TPConfig(sync_trainable = False)` the broadcast is skipped by design. The ranks agree when they are seeded alike and diverge otherwise, so the field's comment now says the caller then owns identical starting factors. | | main | this branch | |---|---|---| | orthogonal refused under sharded_loading | refused | allowed | | `..._random_lora_init_matches_one_process[orthogonal]` | fails | passes | | `[gaussian]`, `[True]` | pass | pass | | `tests/test_tp_native_gloo.py` | | 51 passed | | floor (transformers 4.57.6, PEFT 0.18.0), `-k sharded` | | 10 passed | --------- Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Daniel Han <[email protected]>
Follow-up to #15137. With this PR, a 16-bit 8B LoRA model now loads and trains with tensor parallelism on two 16 GB GPUs. Three opt-in additions, one commit each. Nothing changes for models that do not use
apply_tensor_parallel.1. Sharded loading
sharded_loading(tp_mesh)(wrapped byload_tensor_parallel) makesfrom_pretrainedbuild the model on meta. Each rank then reads from the safetensors checkpoint:The slices stay plain tensors tagged with their full shape, so
get_peft_modelcreates full-size LoRA factors with the same initialisation as one GPU.apply_tensor_parallelthen wraps them into the same DTensors as before. A forward beforeapply_tensor_parallelis refused. 16-bit checkpoints only; quantized loads are refused (QLoRA fits with the existing full load).On 2x T4, Qwen3-8B 16-bit loads at 8.8 GB per rank and trains with a 9.9 GB peak at seq 1024. One GPU and the previous full-load-then-shard path both run out of memory while loading. On Qwen3-0.6B the sharded load gives step-0 logits bitwise identical to the full load, and its load peak drops from 1.12 GB to 0.71 GB.
2. Data parallel x tensor parallel (native FSDP2, torch 2.7+)
The frozen tp shards stay replicated over dp. FSDP2 shards the trainable LoRA DTensors over dp and reduces their tensor parallel partial gradients itself.
Refused:
shard_frozen,cpu_offload, torch < 2.7;tp_clip_grad_norm_andsave_tp_adapterhandle the 2-D layout.This also fixes
native_clip_grad_norm_for FSDP2's_StridedShardplacement. Newer torch does not report it asis_shard(), so those gradient norms were not reduced over the data parallel ranks.3. The HF / TRL Trainer
A tensor parallel model (tp only, or dp x tp after
shard_model) can now be passed to the Trainer andSFTTrainer:tp_clip_grad_norm_;trainer.save_model()writes the standard one-GPU adapter.The loss needs no change. The token count gathered over all ranks counts each replica's tokens tp times, and the Trainer's loss scale multiplies by dp x tp. Averaging over dp only then gives the token mean over the data parallel replicas.
Refused with a reason:
model_init.The generated TRL trainers now skip their trailing
model.for_inference()for a tensor parallel model, which would switch the decoder layers to the decode paths.On 2x T4 (Unsloth + TRL SFTTrainer, Qwen3-0.6B LoRA, fp16, 20 steps):
Qwen3-8B 16-bit also trains through SFTTrainer at TP = 2, with a 9.5 GB peak per rank.
Tests
CPU, gloo, against the same model in one process (fp32):
Each new test fails on the commit before it. The TP suite passes on torch 2.13 / transformers 5.17 / PEFT 0.21; the new loading tests also pass on torch 2.6 / transformers 4.57.6 / PEFT 0.18, where dp x tp is refused as expected.
Not covered: dp x tp on GPU (needs four GPUs), bf16 GPUs, multi-node, AMD / Mac / Windows.