Skip to content

Tensor parallel: support few KV heads, full finetuning, weight-only QAT, eval, MoE and dropout instead of refusing - #15722

Merged
danielhanchen merged 23 commits into
mainfrom
dh/tp-lift-refusals
Oct 31, 2026
Merged

danielhanchen merged 23 commits into
mainfrom
dh/tp-lift-refusals

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 with UNSLOTH_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

  1. num_key_value_heads < tp (Gemma3 270M / 1B, FunctionGemma). When tp is a multiple of the KV head count, rank r computes the one KV head j = r // (tp / kv_heads) that its query heads read. For 16-bit models, the k / v weights, biases and LoRA factors stay whole as Replicate DTensors and the forward narrows them to head j. The partial gradients summed over tp then equal the one GPU gradient. For 4-bit models, the Params4bit rows of head j are sliced bitwise, and tp_replica rebuilds the whole weight for generate. num_key_value_groups follows 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 fused qkv_proj.
  2. Full finetuning. Trainable base weights become Shard DTensors whose local gradients are already complete. Everything outside the attention / MLP regions stays replicated, as modules_to_save already does. The Trainer hook applies tensor parallel for models that never call get_peft_model. Trainer.save_model gathers the whole model on rank 0 when there is no PEFT config.
  3. QAT (weight-only). The torchao FakeQuantizedLinear weight fake quantizer runs on the local shard when it gives exactly the one GPU values there. That covers int4 / intx per-group (with in_features / tp a 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.
  4. Evaluation during training, evaluate, predict. Accelerator.gather_for_metrics gathers 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_end stays refused.
  5. Cached generate inside GRPO without vLLM (LFM2.5). Generate already gathered a whole replica. The GRPO hidden states forward wrapper sits on top of the TP cache guard, so the guard stayed in place and refused the first cached decode step. The guard now lets a filled cache through while a replica is gathered, and still refuses on the shards.
  6. Mixture-of-experts. MoE blocks are found from their structure (an experts child, 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.
  7. Dropout (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)

File Cases origin/main This branch
tests/test_tp_kv_replicated_gloo.py 11: Gemma3 / Llama / Qwen3, tp 2 and 4, LoRA biases, NF4 QLoRA, sharded loading, the UNSLOTH_TP_SIZE=2 Trainer, the refusal for a kv head count that does not divide tp 11 fail (refusal) 11 pass
tests/test_tp_full_finetune_gloo.py 13: full finetuning on 4 architectures, the env Trainer with save and checkpoint, QAT int4 / int8 per-group with and without LoRA, QAT with replicated KV heads, inexact schemes refused fail (refusal) 13 pass
tests/test_tp_eval_gloo.py 3: eval every step plus evaluate / predict with a dp remainder at tp2 and dp2 x tp2 (FSDP2), cached generate through the GRPO forward wrapper 3 fail (refusal) 3 pass
tests/test_tp_moe_dropout_gloo.py 4: Qwen3-MoE with expert LoRA, lora_dropout and attention dropout with exact masks, fused-kernel dropout refused fail (refusal) 4 pass

The neighbour suites test_tp_native_gloo.py, test_tp_env_gloo.py, test_tp_replica_gloo.py, test_tp_native_oracle.py and the TP scaler / save-dir suites also pass. Their assertions that expected the removed refusals now expect acceptance.

Still refused

  • BERT-style encoders (MiniLM, bert_classification). Their nested attention.self / attention.output layout has no region rule yet. Dropout is no longer the blocker.
  • Activation fake-quant QAT (int8-int4, used by the ExecuTorch notebook).
  • kv heads that do not divide tp, fused qkv_proj below tp, MLA, load_best_model_at_end.

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.
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-29T08:07:31.785097Z f827c59 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[bot]

This comment was marked as resolved.

danielhanchen and others added 4 commits October 28, 2026 03:01
…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]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits October 28, 2026 05:05
…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]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 9b94c62c11

ℹ️ 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".

# Conflicts:
#	unsloth/models/tp_native.py
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…plicas cannot overflow before the divide

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 29, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: f827c596c5

ℹ️ 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 and others added 4 commits October 29, 2026 01:34
… 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]
@danielhanchen
danielhanchen merged commit c06ae15 into main Oct 31, 2026
@danielhanchen
danielhanchen deleted the dh/tp-lift-refusals branch October 31, 2026 05:23
danielhanchen added a commit that referenced this pull request Nov 16, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant