Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
9c81ac6
Allow tensor parallelism and context parallelism in one ParallelConfig
whn09 Sep 7, 2026
2e6afea
Merge branch 'main' into tp-cp-compose
JingyaHuang Sep 16, 2026
12058ee
Merge branch 'main' into tp-cp-compose
JingyaHuang Sep 22, 2026
2eff547
Merge branch 'main' into tp-cp-compose
JingyaHuang Sep 30, 2026
7077cf2
Merge branch 'main' into tp-cp-compose
JingyaHuang Oct 14, 2026
3f55884
Apply the context-parallel hooks on the sharded-load path too
whn09 Sep 7, 2026
8a1c4d7
fix: pad uneven all-gathers on Neuron and TPU in _all_gather_anything
JingyaHuang Oct 13, 2026
ce1581f
Validate TP+CP degrees up front and add tests for the combined mesh
JingyaHuang Oct 14, 2026
74f0f50
Merge main into tp-cp-compose
whn09 Oct 22, 2026
0c7b4aa
docs: combining context and tensor parallelism
whn09 Oct 22, 2026
9358a46
Merge branch 'main' into tp-cp-compose
whn09 Oct 23, 2026
fbacc81
Merge remote-tracking branch 'upstream/main' into pr-14725
JingyaHuang Nov 6, 2026
fa39102
Merge branch 'main' into tp-cp-compose
whn09 Nov 7, 2026
4d7858d
Merge remote-tracking branch 'upstream/main' into tp-cp-compose
JingyaHuang Nov 20, 2026
7b9aaba
Merge branch 'main' into tp-cp-compose
JingyaHuang Nov 23, 2026
146e891
Document and test TP+CP loading via from_pretrained; fix distributed …
JingyaHuang Nov 23, 2026
09ecf62
Refactor TP+CP tests to share coverage across CUDA, TPU, and Neuron
JingyaHuang Nov 23, 2026
5ef4ef6
Test TP+CP inference on all transformers that define both plans
JingyaHuang Nov 23, 2026
0c01d36
Merge branch 'main' into tp-cp-compose
JingyaHuang Nov 24, 2026
6b11188
Merge branch 'main' into tp-cp-compose
JingyaHuang Nov 26, 2026
8b1445d
docs: address Steven's review on combining TP and CP
JingyaHuang Nov 26, 2026
08ca471
refactor(parallel): check combined mesh dims in __post_init__
JingyaHuang Nov 30, 2026
25b0b8d
refactor(parallel): check combined world size in __post_init__
JingyaHuang Nov 30, 2026
b4e9ac0
refactor(parallel): drop redundant guards in _apply_context_parallel
JingyaHuang Nov 30, 2026
e682cc7
Merge branch 'main' into tp-cp-compose
JingyaHuang Nov 30, 2026
22374a4
docs: address Steven's review on combining TP and CP
JingyaHuang Nov 26, 2026
39b27ca
Merge branch 'main' into tp-cp-compose
JingyaHuang Dec 1, 2026
7185021
tests: launch TPU workers with set_tpu_launch_env from torch_tpu 0.3
JingyaHuang Dec 1, 2026
5902568
docs: add CUDA benchmarks for combining TP and CP
JingyaHuang Dec 1, 2026
c48eb2d
docs: update the TorchTPU launch command for torch_tpu 0.3
JingyaHuang Dec 1, 2026
3f5eebf
Merge branch 'main' into tp-cp-compose
JingyaHuang Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/en/optimization/context_parallelism.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ Context parallelism runs inside the attention backend, and only some backends su
> [!NOTE]
> [`~ModelMixin.enable_parallelism`] only applies to the model you call it on. If a pipeline has more than one transformer, such as `transformer` and `transformer_2`, call it on each one. Otherwise, the denoising steps that use the other transformers aren't split across GPUs.

To combine context parallelism with [tensor parallelism](./tensor_parallelism) when the weights don't fit on one device either, see [Combine with context parallelism](./tensor_parallelism#combine-with-context-parallelism).

Configure every variant below with [`ContextParallelConfig`].

| Variant | Config | Requirements | Use when |
Expand Down
81 changes: 81 additions & 0 deletions docs/source/en/optimization/tensor_parallelism.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,87 @@ Loading with `parallel_config` is faster and uses less CPU memory per rank than
| 4 | `from_pretrained(parallel_config=...)` | 12.5s | 6.8GB |
| 4 | `from_pretrained` + `enable_parallelism` | 30.4s | 64.1GB |

## Combine with context parallelism

Tensor parallelism shards the weights, and context parallelism splits the sequence. When a model's weights don't fit on one device and its sequence is too long for one device's attention, you need both, because neither one splits what the other does.

Set both in one [`ParallelConfig`]. [`~ModelMixin.enable_parallelism`] (or `from_pretrained(..., parallel_config=...)`) builds a single device mesh with a dimension for each, `("tp", "ring", "ulysses")`, so the communication for each strategy stays inside its own process group. The model must define both a `_tp_plan` and a `_cp_plan`. Both [Ring Attention](./context_parallelism#ring-attention) (`ring_degree`) and [Ulysses Attention](./context_parallelism#ulysses-attention) (`ulysses_degree`) work with tensor parallelism.

The example below needs 8 GPUs: `tp_degree` × `ulysses_degree` = 4 × 2.

```py
import os
import torch
from torch import distributed as dist
from diffusers import (
ContextParallelConfig,
DiffusionPipeline,
Flux2Transformer2DModel,
ParallelConfig,
TensorParallelConfig,
)

def main():
dist.init_process_group(backend="nccl")
rank = dist.get_rank()
# torchrun sets LOCAL_RANK to this process's GPU index on its node
device = torch.device(f"cuda:{int(os.environ['LOCAL_RANK'])}")
torch.cuda.set_device(device)

# Each weight is sharded 4 ways, and each shard's sequence is split 2 ways with Ulysses.
transformer = Flux2Transformer2DModel.from_pretrained(
"black-forest-labs/FLUX.2-dev",
subfolder="transformer",
dtype=torch.bfloat16,
parallel_config=ParallelConfig(
tensor_parallel_config=TensorParallelConfig(tp_degree=4),
context_parallel_config=ContextParallelConfig(ulysses_degree=2),
),
)

pipe = DiffusionPipeline.from_pretrained(
"black-forest-labs/FLUX.2-dev", transformer=transformer, dtype=torch.bfloat16
)
# As with tensor parallelism alone, move the other components individually, not with `pipe.to(device)`.
pipe.text_encoder.to(device)
pipe.vae.to(device)

generator = torch.Generator().manual_seed(42)
image = pipe(prompt="a cat holding a sign that says hello", generator=generator).images[0]
if rank == 0:
image.save("output.png")
dist.destroy_process_group()

if __name__ == "__main__":
main()
```

Save the script as `tp_cp_flux2.py` and launch it with `torchrun`.

```shell
torchrun --nproc-per-node 8 tp_cp_flux2.py
```

`from_pretrained` and `enable_parallelism` check the degrees before sharding any weights. [`ParallelConfig`] also checks the world size when you create it, if `torch.distributed` is already initialized.

- `tp_degree` × `ring_degree` × `ulysses_degree` must not exceed the world size.
- Ulysses splits the heads that TP left on each rank, so `num_attention_heads` must be divisible by `tp_degree` × `ulysses_degree`. Ring attention doesn't touch the head dimension, so with `ring_degree` only `tp_degree` has to divide the head count. If the heads don't divide evenly and `ring_degree` is 1, pass `ulysses_anything=True` to pad the head dimension instead. `tp_degree` still has to divide the head count.

The default mesh puts `"tp"` outermost, so each Ulysses group is a run of consecutive ranks. To use a different layout, for example to keep TP inside one NVLink domain on multi-node CUDA, build a mesh with `"tp"`, `"ring"`, and `"ulysses"` dimensions and pass it as `mesh=` on either config. The default layout suits runtimes like AWS Neuron, which only accept contiguous replica groups for all-to-all but tolerate strided groups for the all-reduce that TP needs. Only one axis of the mesh can be contiguous.

Which degree to raise first depends on what you are short of. Tensor parallelism lowers weight memory. Context parallelism lowers activation memory and latency, but leaves each device's share of the weights unchanged. For example, [MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3) (a 33B audio-video DiT, 56 heads) was loaded in bf16 with `from_pretrained(..., parallel_config=...)` and denoised at 1344×768 and 124 frames, on 8 H200 GPUs connected with NVLink and on 8 RTX PRO 6000 GPUs connected over PCIe. Memory is the same on both, and was measured with `torch.cuda.max_memory_allocated` during denoising:

| GPUs | config | weights / GPU | peak memory / GPU | s / step (H200) | s / step (RTX PRO 6000) |
|---|---|---|---|---|---|
| 4 | TP=4 | 15.59 GiB | 19.1 GiB | 2.02 | 5.08 |
| 8 | TP=8 | 7.87 GiB | 11.3 GiB | 1.18 | 4.18 |
| 8 | TP=4 × Ulysses=2 | 15.59 GiB | 17.9 GiB | 1.07 | 3.51 |
| 8 | TP=2 × Ulysses=4\* | 31.03 GiB | 33.0 GiB | 1.01 | 2.58 |

\* 56 heads split over TP=2 leaves 28 per rank, which Ulysses=4 does not divide evenly, so this row sets `ulysses_anything=True`.

On the same 8 GPUs, moving degree from TP to context parallelism makes each step faster but raises the memory per GPU. The difference is larger over PCIe, where TP's per-layer all-reduce costs more: TP=2 × Ulysses=4 is 1.6× faster than TP=8 on the RTX PRO 6000 GPUs, and 1.2× faster on the H200 GPUs. Use the smallest `tp_degree` that fits the weights in memory, and the remaining devices for context parallelism. Once the head count caps `tp_degree`, raise the context parallel degree to use more devices.

## Limitations

Tensor parallelism doesn't work with some loading options and features, and you can't save a sharded model.
Expand Down
2 changes: 1 addition & 1 deletion docs/source/en/optimization/tpu.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ if dist.get_rank() == 0:
Launch one process per chip. Set `--nproc_per_node` to use all the number of TPU chips on your host.

```bash
eval $(python -m torch_tpu._internal.distributed.launchers.singlehost_wrapper | sed 's/^/export /')
eval $(python -m torch_tpu._internal.distributed.distributed | sed 's/^/export /')
torchrun --nproc_per_node=8 flux2_tp.py
```

Expand Down
2 changes: 1 addition & 1 deletion docs/source/en/training/distributed_inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ Some practical guidance:
- If the model already fits and you have many prompts, use data parallelism. It scales throughput with the number of GPUs without touching the model, and it leaves single-prompt latency alone. Set it up with [Accelerate](../optimization/data_parallelism#accelerate) or [PyTorch Distributed](../optimization/data_parallelism#pytorch-distributed).
- If a single component's weights don't fit, try tensor parallelism first, since it lowers both memory and latency. Tensor parallelism communicates at every block boundary, so it needs a fast interconnect like NVLink. On PCIe, the per-layer traffic can outweigh the compute it saves, and `device_map` becomes the better choice. `device_map` also handles the case where the components are individually fine but collectively too large.
- If activations, not weights, are the problem, use context parallelism. This helps with long sequences, like large images and videos with many frames. Pick a backend from the benchmarks in the [Context parallelism](../optimization/context_parallelism) guide.
- If both the weights and the sequence are too large, Diffusers can't apply tensor and context parallelism to the same model. `ParallelConfig` raises an error if you pass both configs, and `enable_parallelism` can't be called a second time on a model that's already parallelized.
- If both the weights and the sequence are too large, [combine tensor and context parallelism](../optimization/tensor_parallelism#combine-with-context-parallelism) in one [`ParallelConfig`]. Raise `tp_degree` until the weights fit, then add context parallelism to split the sequence.

The [xDiT](../optimization/xdit) and [ParaAttention](../optimization/para_attn) community integrations offer their own context parallelism implementations.
10 changes: 10 additions & 0 deletions src/diffusers/hooks/context_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,16 @@ def _all_gather_anything(tensor: torch.Tensor, dim: int, group: dist.device_mesh
rank_dim = shape[dim]
gather_dims = gather_size_by_comm(rank_dim, group)

max_dim = max(gather_dims)
if any(d != max_dim for d in gather_dims) and tensor.device.type in ("neuron", "tpu"):
# TPU and Neuron all-gathers require equal-sized chunks.
pad_shape = list(shape)
pad_shape[dim] = max_dim - rank_dim
padded = torch.cat([tensor, tensor.new_zeros(pad_shape)], dim=dim)
gathered_tensors = [torch.empty_like(padded) for _ in range(world_size)]
dist.all_gather(gathered_tensors, padded, group=group)
return torch.cat([t.narrow(dim, 0, d) for t, d in zip(gathered_tensors, gather_dims)], dim=dim)

gather_shapes = _fill_gather_shapes(tuple(shape), tuple(gather_dims), dim, world_size)

gathered_tensors = [torch.empty(shape, device=tensor.device, dtype=tensor.dtype) for shape in gather_shapes]
Expand Down
48 changes: 42 additions & 6 deletions src/diffusers/models/_modeling_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,8 @@ def setup(self, rank: int, world_size: int, device: torch.device, mesh: torch.di
@dataclass
class ParallelConfig:
"""
Configuration for applying different parallelisms.
Both `enable_parallelism` and `from_pretrained(..., parallel_config=...)` can combine tensor and context
parallelism. Each uses its own process groups on a shared `("tp", "ring", "ulysses")` device mesh.

Args:
context_parallel_config (`ContextParallelConfig`, *optional*):
Expand All @@ -216,12 +217,41 @@ class ParallelConfig:
_mesh: torch.distributed.device_mesh.DeviceMesh = None

def __post_init__(self):
if self.context_parallel_config is not None and self.tensor_parallel_config is not None:
if self.context_parallel_config is None and self.tensor_parallel_config is None:
raise ValueError(
"Combining context parallelism and tensor parallelism in a single `ParallelConfig` is not supported. "
"Please specify only one of `context_parallel_config` or `tensor_parallel_config`."
"A `ParallelConfig` must specify at least one of `context_parallel_config` or "
"`tensor_parallel_config`."
)
Comment on lines +220 to 224

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🔥


if self._is_combined:
cp_config, tp_config = self.context_parallel_config, self.tensor_parallel_config
mesh = cp_config.mesh or tp_config.mesh
if mesh is not None:
dim_names = mesh.mesh_dim_names
missing = [d for d in ("ring", "ulysses", "tp") if dim_names is None or d not in dim_names]
if missing:
raise ValueError(
f"Combining context and tensor parallelism requires a device mesh with 'ring', 'ulysses' and "
f"'tp' dimensions, but {missing} {'is' if len(missing) == 1 else 'are'} missing (got "
f"{dim_names}). Leave `mesh` unset to have it built from `ring_degree`/`ulysses_degree`/"
f"`tp_degree`."
)
elif dist.is_available() and dist.is_initialized():
# Without a process group the world size is unknown, and `init_device_mesh` raises later instead.
world_size = dist.get_world_size()
requested = cp_config.ring_degree * cp_config.ulysses_degree * tp_config.tp_degree
if requested > world_size:
raise ValueError(
f"Combining context and tensor parallelism needs `ring_degree` ({cp_config.ring_degree}) * "
f"`ulysses_degree` ({cp_config.ulysses_degree}) * `tp_degree` ({tp_config.tp_degree}) = "
f"{requested} devices, which exceeds the world size ({world_size})."
)

@property
def _is_combined(self) -> bool:
"""Whether both context and tensor parallelism are requested, i.e. they must share one mesh."""
return self.context_parallel_config is not None and self.tensor_parallel_config is not None

def setup(
self,
rank: int,
Expand All @@ -234,10 +264,16 @@ def setup(
self._world_size = world_size
self._device = device
self._mesh = mesh

cp_mesh = tp_mesh = mesh
if self._is_combined:
# CP selects its axes in setup. TP takes a one-dimensional submesh.
tp_mesh = mesh["tp"]

if self.context_parallel_config is not None:
self.context_parallel_config.setup(rank, world_size, device, mesh)
self.context_parallel_config.setup(rank, world_size, device, cp_mesh)
if self.tensor_parallel_config is not None:
self.tensor_parallel_config.setup(rank, world_size, device, mesh)
self.tensor_parallel_config.setup(rank, world_size, device, tp_mesh)


@dataclass(frozen=True)
Expand Down
Loading