Skip to content

Tensor parallelism v1: apply_tensor_parallel for dense decoders (LoRA / QLoRA) - #15137

Merged
danielhanchen merged 15 commits into
mainfrom
dh/s6-tp-native
Oct 24, 2026
Merged

danielhanchen merged 15 commits into
mainfrom
dh/s6-tp-native

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds opt-in tensor parallelism for dense decoders: apply_tensor_parallel(model, tp_mesh) in the new unsloth/models/tp_native.py, called after get_peft_model. Like shard_model for FSDP2, it is not tied to one architecture. The plan comes from plan=, else the model's transformers TP plan (_tp_plan / text config base_model_tp_plan), else structural discovery of the attention and MLP projections. Nothing changes unless it is called.

model = FastLanguageModel.get_peft_model(model, ...)  # LoRA first: same init as 1 GPU
mesh = init_device_mesh("cuda", (tp,), mesh_dim_names = ("tp",))
apply_tensor_parallel(model, mesh["tp"])
# custom loop under torchrun --nproc_per_node tp, same batch on every rank
loss = model(input_ids = ids, labels = ids).loss
loss.backward()
tp_clip_grad_norm_(params, 1.0)
optimizer.step(); optimizer.zero_grad()
save_tp_adapter(model, "out")  # standard 1-GPU PEFT adapter

How it works

  • q / k / v and gate / up are column sharded, o / down row sharded. Each attention and MLP region gets an identity-forward / all-reduce-backward op at its input and an all-reduce at its output; the row bias is added once after the reduce.
  • Weights are stored as DTensors on the tp mesh, but every kernel computes on local shards. Unsloth's fused LoRA kernels read weights through 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.
  • Attention modules get per-module local head counts (_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.
  • LoRA is applied before sharding, so adapters start exactly as on 1 GPU. Colwise base: A replicated, B sharded. Rowwise base: A sharded, B replicated.
  • QLoRA (bitsandbytes 4-bit): each rank slices the packed codes and their absmax, so its shard dequantizes to exactly the 1-GPU weight (0 error). Double-quantized scales are kept in fp32 (about 0.047 extra bytes per param).
  • Embeddings, lm_head and norms stay replicated (the fused cross entropy reads 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 fused LoRA_QKV / LoRA_W path 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.
  • Removing any one gradient sum or collective, or adding the row bias on every rank, makes a test fail (6 of 6).
  • 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.
  • The __dict__.get lookups added to the attention forwards and get_lora_parameters trace under torch.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:

run logits rel err step-0 grad rel err (1-GPU A/A) final loss 1 GPU / TP
Qwen3-0.6B LoRA fp16 2.9e-3 3.3e-2 (1.2e-2) 0.0014 / 0.0014
Qwen3-0.6B QLoRA fp16 2.8e-3 3.7e-2 (9.9e-3) 0.0030 / 0.0030
Llama-3.2-1B LoRA fp16 2.6e-3 4.2e-3 (0) 0.0025 / 0.0025
Llama-3.2-1B QLoRA fp16 2.8e-3 6.2e-3 (0) 0.0085 / 0.0084
Qwen3-0.6B LoRA fp32 1.9e-6 9.4e-6 0.0013 / 0.0013
Llama-3.2-1B LoRA fp32 1.8e-6 6.2e-5 0.0053 / 0.0053

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)

  • Each rank still loads the full model before sharding, so load-time peak memory is the whole model; fitting a 16-bit 8B model on 2x T4 needs sharded loading.
  • TP x data parallel (FSDP2 on a dp mesh) and the Trainer hook are refused for now; training is a custom loop.
  • Not run on GPU: the compiled FastModel / VLM path, torch.compile of the whole model, GradScaler, merged save, resume / optimizer-state save, bf16 GPUs, AMD, multi-node. fp32 runs use the plain path, so the fused kernels were proven at fp16 only.
  • Mixing DTensor and plain trainable params in one foreach optimizer group fails; plain ones need their own group.
  • The head-count edits in the mistral, gemma2 and cohere fast forwards are exercised only through their shared code shape; the Llama / Qwen3 (Kaggle T4x2) and Granite (CPU gloo) forwards ran under TP.

Review follow-up

  • Phi3's fused qkv_proj keeps its (q, kv, kv) split even when a plan names it packed_colwise; GQA Phi3 under such a plan previously sharded it as two halves.
  • save_tp_adapter now saves exactly what PEFT's get_peft_model_state_dict selects on the 1-GPU model: bias = "all" / "lora_only" biases (trainable or frozen), modules_to_save and requested embeddings. It gathers only the selected tensors, and refuses a tp mesh smaller than the world.
  • The TP marker, the generate refusal and a new 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 reached from any level.
  • The Gemma2 softcapping helpers read this rank's head counts; the non-TP path is bitwise unchanged and still compiles with fullgraph.
  • Forward-based QAT (torchao NVFP4 / MX linears, activation or LoRA fake quantizers) and modules_to_save on a sharded projection are refused.
  • Smaller fixes: active-adapter lookup follows get_lora_parameters, region inputs passed by keyword are handled, a norm weight shared by two regions gets one tp sum, and tp_clip_grad_norm_ takes a single tensor and honours mesh.
  • Each fix has a test against the same model in one process (gloo, 2 ranks), and each new test fails on the previous head. Gemma2-2B and Qwen3-0.6B LoRA train under TP=2 on 2x T4: 20-step losses follow the 1-GPU runs, and step-0 logits match to 2.9e-3 relative L2 in fp16.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T18:47:01.874168Z 34ef440 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/tp_native.py Outdated
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread unsloth/models/tp_native.py Outdated
Comment on lines +1083 to +1084
if adapters_only and "lora_" not in key and not getattr(value, "requires_grad", False):
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6d5ac8220d

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

… sharded, gate StableLM on transformers 5

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: d9131ad932

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

…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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +1133 to +1135
tp_plan = derive_tp_plan(model, tp, plan)
for region in tp_plan.regions:
for proj in region.projs:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 34ef4400be

ℹ️ 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
danielhanchen merged commit d2ca651 into main Oct 24, 2026
33 of 37 checks passed
@danielhanchen
danielhanchen deleted the dh/s6-tp-native branch October 24, 2026 20:04
danielhanchen added a commit that referenced this pull request Oct 24, 2026
#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.
Fahad090NP pushed a commit to Fahad090NP/unsloth that referenced this pull request Oct 25, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant