Repository navigation
Tensor parallel: support few KV heads, full finetuning, weight-only QAT, eval, MoE and dropout instead of refusing - #15722
Conversation
eval_strategy, Trainer.evaluate and Trainer.predict run on a tensor parallel model. The eval loader is already sharded over dp only; Accelerator.gather_for_metrics now gathers over the dp replicas only (the tp ranks of a replica hold identical results), with accelerate's remainder truncation, so eval_loss and predictions equal one process (tp) and the DDP semantics (dp x tp). load_best_model_at_end stays refused.
…ed forwards GRPO without vLLM under UNSLOTH_TP_SIZE died mid-run: the GRPO hidden states wrapper (models/rl.py) wraps the tensor parallel forward guard after apply_tensor_parallel, so tp_replica could not swap the guard out while the whole replica is gathered for generate, and the first cached decoding step was refused. The guard now lets a filled KV cache through while a replica is gathered (the regions pass through then) and still refuses it on the shards.
Instead of refusing MoE models, every MoE block (found by structure: an experts child or an experts / sparse-MoE class) stays unsharded and runs on every tp rank with the same input; attention and dense MLPs still shard. The block output is averaged over the tp group (one all-reduce per MoE layer) so non-deterministic CUDA scatter kernels cannot make the replicas diverge; its gradient is already the same on every rank. MLA stays refused.
lora_dropout, attention dropout (eager attention) and dropout modules in decoder layers no longer refuse tensor parallelism. Every tp rank draws from the same RNG state (synced from tp rank 0 at apply time) in the order one process draws: replicated activations draw the same mask as one process, sharded ones (attention probabilities over local heads, row projection inputs, the intermediate features) draw the whole mask and keep their own slice, so masks are bitwise one process's. Fused attention kernels that draw dropout inside (SDPA / flash) are refused with the eager attention as the fix; anything whose layout cannot be told is refused at runtime.
Trainable base weights shard like the LoRA factors: colwise / rowwise Shard DTensors whose local gradients are already complete, replicated row biases with whole gradients, and everything outside the regions (embeddings, norms, lm_head) replicated with identical gradients on every tp rank. UNSLOTH_TP_SIZE no longer refuses full_finetuning = True; the Trainer applies tensor parallel at init and Trainer.save_model gathers the whole 1-GPU model to rank 0 instead of writing an adapter.
Weight-only QAT (torchao FakeQuantizedLinear with a dynamic weight fake quantizer) runs on the local shard when its scales stay inside the shard: Int4 / Intx per-group with in_features / tp a multiple of the group size, and per-row scales on column parallel projections. That is exactly the 1-GPU fake quantization. Activation fake quantization (per-token scales over a row parallel input), per-row scales on row projections, learned ranges and forward-only QAT linears (NVFP4 / MX) stay refused with the reason. UNSLOTH_TP_SIZE no longer refuses qat_scheme; a QAT load reads the checkpoint in full and is sharded later.
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. |
…chemes older torchao cannot prepare At torch 2.6 / torchao 0.13 (the floor corner) test_trainer_evaluates_a_tensor_parallel_model_like_one_process[2-2] hit the intended torch 2.7+ refusal and the int8 QAT cases failed inside the one-process reference (QATConfig rejects IntxWeightOnlyConfig there). Skip those cells like test_tp2_x_fsdp2_dp2_matches_one_process does.
…er init save_model cannot gather the whole model on a tp x native FSDP2 model, so a full finetuning run trained and then died at its first Trainer checkpoint (or the final save_model), with a message pointing at an adapter that does not exist. Refuse before training and name the layouts that work (tp alone, tp x DDP-style dp, FSDP2 alone).
…ing, replicated KV and fused LoRA - The region dropout wrapper gated on torch.is_grad_enabled(), so a reentrant checkpoint's no-grad first forward drew local masks while the recompute drew sliced full masks. Gate on training / replica only. - lora_dropout on KV_REPLICATED projections treated the whole input as a row shard; handle it like COLWISE. - The fused LoRA Functions drew lora_dropout on a row projection's local input shard. Route tensor parallel row projections with lora_dropout > 0 to the projection forward, which draws the rank's slice. Each case is compared to one process with the same seed (fails before, passes after). [skip ci]
…ropout does _full_mask now returns a boolean keep mask and _apply_mask rounds like one process's F.dropout on that device: ATen's fused native_dropout on CUDA / XPU (x * mask * 1/(1-p) in fp32, rounded once; backward via native_dropout_backward with autograd's 1/(1-p)), and the bf16/fp16 noise tensor of _dropout_impl on CPU. Used by _tp_dropout and row-parallel _lora_dropout (also the fused LoRA fallback). [skip ci]
|
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". |
# Conflicts: # unsloth/models/tp_native.py
…e CUDA spoof cannot un-skip it
A sharded Params4bit's quant_state already holds the local shape, so dividing its in_features by tp again recorded intermediate_size / tp^2 and the MLP dropout between the column and row projections was refused on the first training forward. Read the width from the unsharded weight instead, and test MLP dropout parity for 16-bit and 4-bit weights. [skip ci]
…o shard stays under its 2100 s cap [skip ci]
…plicas cannot overflow before the divide [skip ci]
|
@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". |
… the gathered adapter save_lora_adapter handed save_pretrained a state dict of the sharded DTensors, which the tensor parallel save passes through untouched, so PEFT's safetensors storage pointer pass raised on every rank (the GRPO notebooks end with model.save_lora). Under tensor parallel the dict is now built inside tp_collective on the gathered adapter, as save_pretrained does.
Conflicts in .github/workflows/studio-backend-ci.yml and tests/studio/test_backend_ci_parallel_isolation.py: main already split the gloo shard (tensor parallel and pipeline parallel files moved into gloo-tp-pp), so main's version is kept. The new tensor parallel gloo files (eval, full finetune, KV replicated, MoE dropout) land in the gloo shard and add about 420 s of serial test time. [skip ci]
…uce order noise (#17896) ## Summary `tests/test_tp_eval_gloo.py::test_trainer_evaluates_a_tensor_parallel_model_like_one_process[2-2]` fails intermittently in the `Repo tests (CPU, gloo)` shard on unrelated PRs (seen on #17701 and #17840): ``` Mismatched elements: 1 / 2016000 (0.0%) Greatest absolute difference: 1.07e-05 at index ... (up to 1e-05 allowed) ``` The predictions are logits after three training steps. Under tensor parallelism the row-parallel all-reduce sums partial products in a different order than the single-process reference, so an element close to zero can land just past `atol = 1e-5` depending on the CPU and thread layout. The test was added in #15722 and the check itself is right, the absolute tolerance is just at the edge of float32 reduction noise. ## Change - Predictions `atol` goes from `1e-5` to `5e-5` (`rtol` unchanged at `1e-4`), with a comment saying why. - The training and eval losses are still compared at `rel = 1e-5`, and `label_ids` still has to match exactly, so a real sharding or gather bug (which moves logits and losses by orders of magnitude more) still fails the test. ## Testing - `pytest tests/test_tp_eval_gloo.py` on CPU (torch 2.10, transformers 5.17): 3 passed.
Tensor parallel: lift six refusals (KV heads below tp, full finetuning, QAT, evaluation, MoE, dropout) and fix cached generate inside GRPO
Unmodified notebook scripts run under
UNSLOTH_TP_SIZE=2 torchrun --nproc-per-node 2 script.py(and withUNSLOTH_FSDP2=1) unless they hit one of the tensor parallel v1 refusals. Seventeen notebook cells were refused for reasons that are not bugs, only missing support. This PR removes most of them. Each change keeps the one GPU numerics: the CPU gloo tests compare tp = 2 against one process over 3 optimizer steps.What changes
tp_replicarebuilds the whole weight for generate.num_key_value_groupsfollows the local heads and is restored on the gathered replica. Sharded 16-bit loading reads k / v whole. Still refused, with a message: kv heads that do not divide tp, and a fusedqkv_proj.modules_to_savealready does. The Trainer hook applies tensor parallel for models that never callget_peft_model.Trainer.save_modelgathers the whole model on rank 0 when there is no PEFT config.FakeQuantizedLinearweight fake quantizer runs on the local shard when it gives exactly the one GPU values there. That covers int4 / intx per-group (within_features / tpa multiple of the group size) and per-row scales on column projections. Activation fake quantization (int8-int4, per-token scales over the whole row), per-row scales on row projections, and learned or static ranges stay refused, each with the reason.evaluate,predict.Accelerator.gather_for_metricsgathers over the data parallel replicas only: the dp mesh of FSDP2 x TP, the DDP-style dp mesh, or nothing at dp = 1. It keeps accelerate's remainder truncation. The eval loaders were already sharded over dp only.load_best_model_at_endstays refused.expertschild, or a sparse MoE class). They run replicated on every tp rank while attention and dense MLPs still shard. One forward all-reduce mean per MoE layer keeps the copies equal under non-deterministic scatter kernels. Rank 0 prints how many blocks are replicated. MLA stays refused.attention_dropout, dropout modules in layers,lora_dropout). All tp ranks start from the same RNG state. In the regions, replicated activations draw the mask one process draws. Sharded activations draw the whole mask and keep their own slice, so the masks are bitwise the one process masks. Dropout fused into SDPA or flash attention cannot be sliced: it is refused at init and the message asks for the eager attention.Tests (CPU, gloo, 2 or 4 ranks against one process)
tests/test_tp_kv_replicated_gloo.pyUNSLOTH_TP_SIZE=2Trainer, the refusal for a kv head count that does not divide tptests/test_tp_full_finetune_gloo.pytests/test_tp_eval_gloo.pyevaluate/predictwith a dp remainder at tp2 and dp2 x tp2 (FSDP2), cached generate through the GRPO forward wrappertests/test_tp_moe_dropout_gloo.pyThe neighbour suites
test_tp_native_gloo.py,test_tp_env_gloo.py,test_tp_replica_gloo.py,test_tp_native_oracle.pyand the TP scaler / save-dir suites also pass. Their assertions that expected the removed refusals now expect acceptance.Still refused
attention.self/attention.outputlayout has no region rule yet. Dropout is no longer the blocker.int8-int4, used by the ExecuTorch notebook).qkv_projbelow tp, MLA,load_best_model_at_end.