Repository navigation
Tensor parallelism v1: apply_tensor_parallel for dense decoders (LoRA / QLoRA) - #15137
Conversation
… document the loop
|
@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: 88f6679c57
ℹ️ 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".
| for proj in module._unsloth_tp_row_projs: | ||
| bias = _weight(proj)[1].bias | ||
| if bias is not None: | ||
| y = y + _local(bias).to(y.dtype) |
There was a problem hiding this comment.
Avoid summing replicated row-bias gradients across TP ranks
When a LoRA configuration trains base biases (bias="all" or bias="lora_only") and TP size is greater than one, the row bias is added after the output all-reduce, so every rank already computes its complete gradient. However, _local(bias) marks that gradient as Partial, and the hook installed by _set_dtensor sums it across ranks again. This multiplies row-bias gradients by the TP size, changing training updates and the norm computed by tp_clip_grad_norm_. Use a replicated-gradient local view for biases added after the reduction, rather than the partial-gradient view needed by replicated LoRA factors.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, fixed in 6d5ac82. The row bias is added after the all-reduce, so it now takes a local view with a Replicate gradient (_local_complete) instead of the Partial view used for replicated LoRA factors, and the tp sum hook leaves it alone. Added test_tp2_trainable_biases_match_one_process (LoRA bias="all", 2 gloo ranks): grads, grad norms and losses match one process; it fails with the previous view (bias grads doubled).
| if adapters_only and "lora_" not in key and not getattr(value, "requires_grad", False): | ||
| continue |
There was a problem hiding this comment.
Preserve embedding weights requested by adapter saves
When saving an adapter after resizing the vocabulary, or explicitly passing save_embedding_layers=True, this filter removes frozen embedding and lm-head weights before save_pretrained can select them. PEFT's embedding-saving logic filters the supplied state dictionary; it does not fetch missing weights from the model, so the save silently omits these tensors despite the requested option. For resized vocabularies, reloading can therefore lose the newly initialized token embeddings. Preserve the embedding entries required by the save options instead of filtering solely by lora_ and requires_grad.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6d5ac82. tp_full_state_dict(adapters_only=True) now also passes the input / output embedding weights, so PEFT's own filter decides whether to save them (save_embedding_layers=True, resized vocab); with the default auto on an unresized vocab the saved adapter is unchanged. Added test_tp2_adapter_save_keeps_requested_embeddings, which compares the TP save against a 1-process save_pretrained(save_embedding_layers=True) and fails without the change.
…o the PEFT save filter [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
… sharded, gate StableLM on transformers 5 [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…y points - A fused qkv_proj keeps its [q, kv, kv] split under a packed plan style (GQA Phi3 under a user plan sharded it as two halves); packed styles on other attention projections are refused. - save_tp_adapter saves what PEFT's get_peft_model_state_dict selects on the 1 GPU model (bias = "all" / "lora_only" biases, frozen or not, modules_to_save, embeddings), gathering only the selected DTensors; refused when the tp mesh is not the whole world. - The TP marker, the generate refusal and a KV cache refusal sit on every wrapper level (PeftModel, LoraModel, CausalLM, decoder); FastLanguageModel / FastModel.for_inference, the Trainer (including model_init) and native FSDP2 refuse a TP model from any level. - Gemma2 softcapping helpers read this rank's head counts (non TP path unchanged). - Forward based QAT (torchao NVFP4 / MX linears, activation or LoRA fake quantizers) and modules_to_save on a projection are refused. - Active adapter lookup matches get_lora_parameters; an empty selection or an adapter the layer lacks gives the base projection. - Region inputs passed by the forward's argument name, tied per head norm weights summed once, tp_clip_grad_norm_ takes a single tensor and honours mesh. - Tests for each, against the same model in one process. [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: b7ef29c9f5
ℹ️ 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".
| B = _local(self.lora_B[adapter].weight) | ||
| scaling = self.scaling[adapter] | ||
| x_lora = x if torch.is_autocast_enabled() else x.to(A.dtype) | ||
| x_lora = self.lora_dropout[adapter](x_lora) |
There was a problem hiding this comment.
Use rank-distinct dropout masks for row-sharded inputs
When lora_dropout > 0 and TP ranks start with the same seed (as get_peft_model(random_state=...) normally ensures), every rank executes equal-shaped dropout calls with identical RNG states. For rowwise projections, however, x_lora contains different input features on each rank, so this repeats the same mask across feature shards instead of independently masking those features. This changes the dropout distribution and consequently training results, rather than merely choosing a different random realization. Use TP-aware RNG handling that keeps masks synchronized for replicated inputs but distinct for sharded inputs, or refuse nonzero LoRA dropout until that is supported.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. Keeping masks equal for replicated inputs and distinct per feature shard needs TP-aware RNG that v1 does not have, so apply_tensor_parallel now refuses lora_dropout > 0 in its validation pass (before anything is sharded), with a message to use lora_dropout = 0. Covered in test_refuses_dora_and_lora_bias. Fixed in 35534cf.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 35534cf27a
ℹ️ 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".
| tp_plan = derive_tp_plan(model, tp, plan) | ||
| for region in tp_plan.regions: | ||
| for proj in region.projs: |
There was a problem hiding this comment.
Guard attention dropout until TP-aware RNG is supported
When TP ranks start with the same seed and attention dropout is nonzero, attention heads on different ranks receive identical dropout masks because the local attention calls have equal shapes and identical RNG states. This remains possible despite the new LoRA-dropout refusal: GraniteAttention_fast_forward reads config.attention_dropout during training and passes it to SDPA/FlashAttention in unsloth/models/granite.py. Repeating masks across distinct head shards changes their joint dropout distribution and therefore training results. Validate attention dropout before sharding and refuse unsupported nonzero values, or introduce rank-distinct RNG handling inside sharded attention while preserving synchronized RNG for replicated computation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, same reasoning as the LoRA dropout case. The validation pass now refuses a nonzero attention_dropout / attn_pdrop in the text config and any nn.Dropout with p > 0 inside the decoder layers (LoRA dropout keeps its own message), before anything is sharded. Test: test_refuses_attention_and_layer_dropout. Fixed in 34ef440.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
#15162) ## Summary `tests/test_return_logits_survives_for_training.py` fails on main (8 of 9 tests) since #15137: ``` unsloth/models/vision.py:5506: in for_inference _refuse_tensor_parallel_for_inference(model) E TypeError: 'NoneType' object is not callable ``` The test pulls `FastBaseModel.for_inference` / `for_training` out of `vision.py` with `ast` and runs them in a namespace where unknown names resolve to `None`. It only lifts a hand-kept list of `_utils.py` helpers. #15137 added the tensor parallel refusal at the top of `for_inference` (`_refuse_tensor_parallel_for_inference`, which calls `_is_unsloth_tensor_parallel`). Neither helper is on that list, so the call hits `None`. The product code is correct: the refusal is intended, and the real import in `vision.py` resolves fine. This shows up on any PR whose `Repo tests (CPU, rest)` shard runs on current main, for example #15159. ## Change - Keep the explicit list. Then follow the lifted functions into any other top-level `_utils.py` function they name, transitively. Today that adds exactly the two tensor parallel helpers. The next helper either method gains gets lifted automatically instead of turning into the same `NoneType` error. - `test_lifted_for_inference_runs_its_real_helpers`: a model carrying `_unsloth_tp` must make the lifted `for_inference` raise the real tensor parallel `RuntimeError`. This proves the harness runs the real guard, not a stand-in. ## Verification - On main: `8 failed, 1 passed`. With this change: `10 passed`. - Sabotage 1: turning off the helper walk makes 9 tests fail again, including the new one. - Sabotage 2: reverting the #3071 fix in `for_training` (`os.environ.setdefault(...)` back to a forced `"0"`) fails 3 tests. The file still guards what it was written for.
…el, and the Trainer (unslothai#15174) Follow-up to unslothai#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 ```python mesh = init_device_mesh("cuda", (2,), mesh_dim_names = ("tp",)) model, tokenizer = load_tensor_parallel("unsloth/Qwen3-8B", mesh["tp"], dtype = torch.float16, max_seq_length = 1024) model = FastLanguageModel.get_peft_model(model, r = 16, ...) apply_tensor_parallel(model, mesh["tp"]) ``` `sharded_loading(tp_mesh)` (wrapped by `load_tensor_parallel`) makes `from_pretrained` build the model on meta. Each rank then reads from the safetensors checkpoint: - the replicated tensors in full; - only its own slices of the attention / MLP projections (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 initialisation as one GPU. `apply_tensor_parallel` then wraps them into the same DTensors as before. A forward before `apply_tensor_parallel` is 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+) ```python mesh = init_device_mesh("cuda", (dp, tp), mesh_dim_names = ("dp", "tp")) apply_tensor_parallel(model, mesh["tp"]) shard_model(model, FSDP2Config(mesh = mesh["dp"])) ``` 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: - a mesh that is not the dp dimension of the same mesh; - `shard_frozen`, `cpu_offload`, torch < 2.7; - trainable per-head norms (their tp sum is a parameter hook, and FSDP2 replaces the parameters). `tp_clip_grad_norm_` and `save_tp_adapter` handle the 2-D layout. This also fixes `native_clip_grad_norm_` for FSDP2's `_StridedShard` placement. Newer torch does not report it as `is_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 and `SFTTrainer`: - accelerate does not wrap the tp ranks in DDP; - the dataloader is sharded over dp only, so every tp rank of a replica reads the same batches; - clipping uses `tp_clip_grad_norm_`; - float16 uses a sharded grad scaler, so all ranks make the same skip decision; - `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: - Trainer checkpoints / resume, evaluation; - bitsandbytes / paged / GaLore optimizers; - DeepSpeed, accelerate FSDP, iterable datasets, `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): | run | loss max abs diff vs 1 GPU | grad norm max rel diff vs 1 GPU | peak GB per rank | |---|---|---|---| | second 1 GPU run (noise floor) | 4.2e-4 | 2.6e-3 | 1.71 | | TP = 2, full load | 1.0e-3 | 3.1e-3 | 1.25 | | TP = 2, sharded load | 5.6e-4 | 3.1e-3 | 1.25 | 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): - sharded loading for Llama, Llama with biases, Phi3 (fused qkv, packed gate_up), Gemma2 (tied embeddings) at tp = 2 and Qwen3 GQA at tp = 4. Every local tensor is bitwise equal to the full-load shards, training matches, and only this rank's slices are read; - dp 2 x tp 2 for Llama (two layouts), Phi3 and trainable biases: gradients, losses, both clip functions and the saved adapter; - the Trainer at tp 2 and dp 2 x tp 2: losses, grad norms, final weights and the saved adapter match a one-process Trainer with the same global batches. tp peers read the same batches, data parallel replicas different ones. 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. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Adds opt-in tensor parallelism for dense decoders:
apply_tensor_parallel(model, tp_mesh)in the newunsloth/models/tp_native.py, called afterget_peft_model. Likeshard_modelfor FSDP2, it is not tied to one architecture. The plan comes fromplan=, else the model's transformers TP plan (_tp_plan/ text configbase_model_tp_plan), else structural discovery of the attention and MLP projections. Nothing changes unless it is called.How it works
get_lora_parameters/get_lora_parameters_bias, which now return local views when a projection is tensor parallel (one dict lookup otherwise). Replicated LoRA factors get Partial gradients summed over tp._unsloth_tp_heads/_unsloth_tp_kv_heads) read by the Unsloth forwards in llama, qwen3, mistral, gemma2, cohere and granite; the shared config is never changed. HF forwards that read head counts from the config get a per-module config copy.lm_head.weight).All refusals run in a validation pass before any parameter is sharded, so a refused model is left untouched. Refused with a reason: lora_dropout > 0, attention or in-layer dropout > 0, MoE, MLA, heads / kv heads / intermediate size not divisible by tp, kv heads < tp, per-layer norms over all heads (Olmo2), DoRA, lora_bias, several adapters, trainable base weights, 8-bit / GPTQ / AWQ / fp8 / MXFP4 / QAT bases, misaligned 4-bit blocks,
generate(), the HF Trainer and native FSDP2 on a TP model (both raise a clear error instead of wrapping the tp ranks in DDP).Tests
tests/test_tp_native_oracle.py(37, single process, CPU): a simulated 2-shard oracle matches the unsharded model's logits and LoRA grads in fp32 for Llama (with and without bias), Qwen3, Qwen2, Gemma2, Gemma3, Mistral, Phi3 (fused qkv, packed gate_up) and StableLM (no transformers plan); plan derivation and every refusal; QLoRA shards dequantize with 0 error; the fusedLoRA_QKV/LoRA_Wpath on CPU matches the plain path, with calls counted.tests/test_tp_native_gloo.py(11, 2 and 4 gloo ranks): logits, step-0 grads, grad norms, 3-step losses and the saved adapter (keys and values) match one process.pytest tests/test_tp_native_oracle.py tests/test_tp_native_gloo.py: 48 passed. 22 nearby test files: 406 passed, 99 skipped, 0 failed.__dict__.getlookups added to the attention forwards andget_lora_parameterstrace undertorch.compile(fullgraph=True)on torch 2.6, 2.10 and 2.13.Kaggle T4x2, TP=2 vs 1 GPU, 50 steps, fused kernels engaged on every layer and step in fp16:
The Qwen3 fp16 grad gap is fp16 rounding, not the sharding: in fp32 TP matches to about 1e-5, and against an fp32 reference TP fp16 is exactly as far off as 1-GPU fp16 (0.206 vs 0.206).
Training memory per rank: Llama LoRA 2.15 GB with TP vs 3.09 GB on 1 GPU, Llama QLoRA 1.53 vs 1.82 GB, Qwen3 LoRA 1.60 vs 2.04 GB.
Not covered (v2)
Review follow-up