Skip to content

Pipeline parallelism v1: apply_pipeline_parallel for dense decoders (GPipe, 1F1B) - #15175

Merged
danielhanchen merged 13 commits into
mainfrom
dh/s6-pp-v1
Oct 25, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
dh/s6-pp-v1

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Adds unsloth/models/pp_native.py, a pipeline parallel split built on torch.distributed.pipelining, in the
same style as native FSDP2 (shard_model) and tensor parallelism (apply_tensor_parallel): one call on an
Unsloth / PEFT model, no per-architecture code.

from torch.distributed.device_mesh import init_device_mesh
from unsloth.models.pp_native import apply_pipeline_parallel

model = FastLanguageModel.get_peft_model(model, ...)  # LoRA first, on every rank
pp = apply_pipeline_parallel(model, init_device_mesh("cuda", (2,), mesh_dim_names = ("pp",))["pp"],
                             n_microbatches = 2)       # schedule = "gpipe" (default) or "1f1b"
optimizer = torch.optim.AdamW(pp.parameters(), lr = 2e-4)
loss = pp.step(input_ids, labels)                      # the same batch on every rank
pp.clip_grad_norm_(1.0)
optimizer.step(); optimizer.zero_grad()
pp.save_adapter("out")                                 # the usual 1-GPU PEFT adapter

How it works

  • Each rank keeps a contiguous slice of decoder layers. The split balances weight elements per stage and
    counts the lm_head on the last stage (Qwen3-0.6B: 19 / 9 layers, Llama-3.2-1B: 10 / 6). PPConfig(layers_per_stage = [...])
    overrides it.
  • Layers owned by other stages are replaced by parameter-free pass-through modules, so the layer list keeps
    its length, layer indices, layer_types and every parameter name. Adapters saved from a pipeline run have
    the same keys as a 1-GPU run. The input embedding on later stages and the lm_head on earlier stages become
    parameter-free stubs; frozen tied embeddings stay on the first and the last stage.
  • Every stage runs the model's own forward, so model-specific code (Gemma embedding scale, masks, rotary,
    logit softcapping, Unsloth's fast forwards and fused cross entropy) is unchanged. Later stages feed the
    received hidden states into their first layer, earlier stages stop after their last layer, and the last
    stage returns the model's loss. Logits are never sent between stages.
  • Each micro-batch's loss is its token loss sum over the token count of the whole batch, so the gradients
    match gradient accumulation on one GPU. Grad clipping sums squares over all stages, and the GradScaler
    found_inf is the max over all stages (pp.unscale_(scaler, optimizer)).
  • Schedules: GPipe by default. 1F1B interleaves forwards and backwards, so it is only allowed when Unsloth's
    smart gradient checkpointing leases its host offload slots per checkpoint (Smart gradient checkpointing: lease host offload slots per checkpoint; offloader keepalive instead of record_stream unsloth-zoo#2071), or when
    gradient checkpointing is off. Otherwise it is refused with a message naming the zoo change.
  • Stage shapes are declared statically for each (micro-batch size, sequence length), as reentrant gradient
    checkpointing cannot run the dynamic shape inference.

Refused in v1 (clear errors)

Mixture of experts (the router auxiliary loss would be dropped), MLA, cross-layer state (KV sharing, altup,
per-layer inputs), hybrid layer stacks, mixed layer classes, multimodal models, models already split by TP /
FSDP2, pipeline x data parallel, packed-sequence kwargs, trainable tied embeddings. On a pipeline parallel
model the Trainer, for_inference, generate, native FSDP2 and apply_tensor_parallel raise and point to the
custom loop or to saving the adapter.

Tests

tests/test_pp_native_gloo.py (19 tests, CPU, gloo, fp32) runs 2 and 4 stage pipelines and compares them with
one process for Llama, Qwen3, Gemma2, Gemma3 (tied embeddings) and Mistral, under GPipe and 1F1B, with and
without reentrant gradient checkpointing. The tests compare hidden states at stage boundaries, losses over 3
AdamW steps, step-0 LoRA gradients, grad norms and saved adapters. They also check micro-batches against
gradient accumulation, the GradScaler skip on all stages, the refusals, and the entry points through the real
package. Removing any of the following makes a test fail (9 of 9 checked): scale_grads = False, the clip
all-reduce, the found_inf max, the label shift in the token count, the activation substitution, a stage's
last layer, the 1F1B refusal, the tied embedding refusal, or the lm_head cost.

GPU check on 2x T4 (fp16, Unsloth gradient checkpointing, LoRA r16, seq 512, batch 4, 50 steps). The control
is one GPU running gradient accumulation over the same micro-batches:

model PP=2 vs 1 GPU accumulation: step-0 grads rel L2 / max loss diff over 50 steps 1 GPU A/A
Llama-3.2-1B LoRA 0 / 0 (bitwise) 0 / 0
Llama-3.2-1B QLoRA 0 / 1.0e-5 0 / 0
Qwen3-0.6B LoRA 1.1e-2 / 6.0e-3 1.3e-2 / 1.4e-3
Qwen3-0.6B LoRA, 4 micro-batches, 1F1B (with unslothai/unsloth-zoo#2071) 9.6e-3 / 8.8e-3 1.3e-2 / 1.4e-3
Qwen3-0.6B QLoRA 1.2e-2 / 1.2e-3 1.0e-2 / 2.7e-3

Memory per stage after the split (GB allocated): Llama-3.2-1B LoRA 1.66 / 1.19 against 2.35 on one GPU, with
training peaks of 1.91 / 1.77 against 3.50.

Not in this PR

Pipeline x data parallel, interleaved or zero-bubble schedules, Trainer integration, loading only a stage's
weights (each rank still loads the full model before the split), evaluation and generation on a split model.

…GPipe, 1F1B with slot-leased smart GC)

Each rank keeps a FLOP-balanced slice of decoder layers; the other layers become
parameter-free pass-throughs so layer indices and adapter keys stay the same. Every stage
runs the model's own forward: later stages substitute the received hidden states before
their first layer, earlier stages stop after their last layer, and the last stage returns
the model's own loss (fused CE, no logits sent). Micro-batch losses are normalized by the
token count of the whole batch like gradient accumulation; clip norm sums over stages,
GradScaler found_inf is the max over stages, adapters are saved in the 1-GPU PEFT format.
Trainer, for_inference, generate, native FSDP2 and TP refuse a pipeline parallel model.
@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-25T01:16:12.906254Z c31cca6 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: 36bc251e4b

ℹ️ 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.n_microbatches = n_microbatches
self.schedule = schedule
self.config = config
self.parts = parts

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 Release references to embeddings and heads owned by other stages

For multi-stage pipelines, retaining parts here keeps the original parts.embed and parts.lm_head modules alive even after apply_pipeline_parallel replaces them with parameter-free stubs. Consequently, every rank still holds both full vocabulary-sized weight matrices, including intermediate ranks that use neither; gc.collect() and empty_cache() cannot reclaim these live tensors. This undermines the memory savings of the split and can cause avoidable CUDA OOMs on large-vocabulary models. Clear or replace the references to non-owned modules after constructing the stubs, or retain only non-owning metadata in the pipeline object.

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 d45faf1. The stage object now keeps the post-split view: on a stage that does not own them, parts.embed / parts.lm_head point at the stubs, so the original vocabulary-sized modules are freed at split time. _case_parity checks with weak references that a stage keeps the embedding only on the first stage and the lm_head only on the last (fails before the change, for 2 and 4 stages).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 412b02ef07

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

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: cad1e22a9f

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

hidden = args[0] if args else kwargs.get("hidden_states")
if not self.is_last:
raise _StageOutput(hidden)
return (hidden,) if self.tuple_format else hidden

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 Handle attention outputs in tuple-format pass-through layers

When a model using Unsloth's tuple-format decoder forward has config.output_attentions = True, every non-first stage fails on its first pass-through layer: this returns only (hidden,), but LlamaModel_fast_forward unconditionally reads layer_outputs[1] when collecting attentions (unsloth/models/llama.py:1591–1592). Consequently, pp.step() raises IndexError on those ranks while other ranks can remain blocked in pipeline communication. Either preserve the expected tuple slots in the pass-through or explicitly disable/refuse attention outputs before splitting.

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 2010100. The stage forward now passes output_attentions = False, output_hidden_states = False, so a config with output_attentions = True never asks the decoder for per-layer outputs that pass-through layers do not produce. Unsloth's fast decoder forward resolves None from the config (and asserts False), so the explicit False is what it needs. Covered by test_pp2_stage_forward_turns_off_attention_outputs (fails before the change).

@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: 201010097d

ℹ️ 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/pp_native.py Outdated
Comment on lines +1094 to +1096
for _, norm in parts.norms:
for p in norm.parameters():
p.requires_grad_(False) # used by the last stage only

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 ownership of trainable pre-stack normalization

For a decoder with trainable normalization before its layer stack, such as Bloom's word_embeddings_layernorm, _find_parts includes that module in parts.norms alongside the final normalization. This loop then freezes it on the first stage, where its output actually feeds the owned layers. On later stages, its output is discarded when the pass-through substitutes stage_input, so the remaining trainable copy receives no gradient either. Consequently, training silently stops updating that normalization, including when it is selected through PEFT modules_to_save. Distinguish input-side from final normalization ownership, or reject this topology before modifying the model.

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 c31cca6. Norm ownership now follows registration order around the layer list: a norm registered before it (Bloom's word_embeddings_layernorm) stays trainable only on the first stage, the final norm only on the last, and every other stage keeps its copy frozen and leaves it out of its adapter selection, so save_adapter writes the owner's trained values. The modules_to_save wrapper is also unwrapped when classifying a norm (a wrapped ln_f was refused before). Covered by test_pp2_trainable_input_and_final_norms_train_on_their_owner (Bloom with modules_to_save = ["word_embeddings_layernorm", "ln_f"], matches one process and the saved adapter; fails before 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. Keep it up!

Reviewed commit: c31cca6711

ℹ️ 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 f6e690e into main Oct 25, 2026
23 of 37 checks passed
@danielhanchen
danielhanchen deleted the dh/s6-pp-v1 branch October 25, 2026 01:38
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Oct 25, 2026
…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>
meefs pushed a commit to meefs/unsloth that referenced this pull request Oct 26, 2026
…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>
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