diff --git a/docs/source/en/optimization/context_parallelism.md b/docs/source/en/optimization/context_parallelism.md index 5c285b2a870a..6513c70fbf6f 100644 --- a/docs/source/en/optimization/context_parallelism.md +++ b/docs/source/en/optimization/context_parallelism.md @@ -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 | diff --git a/docs/source/en/optimization/tensor_parallelism.md b/docs/source/en/optimization/tensor_parallelism.md index 870e27872f30..4933a0412540 100644 --- a/docs/source/en/optimization/tensor_parallelism.md +++ b/docs/source/en/optimization/tensor_parallelism.md @@ -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. diff --git a/docs/source/en/optimization/tpu.md b/docs/source/en/optimization/tpu.md index 0e20709c7e46..31aa87afe0b1 100644 --- a/docs/source/en/optimization/tpu.md +++ b/docs/source/en/optimization/tpu.md @@ -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 ``` diff --git a/docs/source/en/training/distributed_inference.md b/docs/source/en/training/distributed_inference.md index 123ed63d5e9b..664ad76dd92e 100644 --- a/docs/source/en/training/distributed_inference.md +++ b/docs/source/en/training/distributed_inference.md @@ -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. diff --git a/src/diffusers/hooks/context_parallel.py b/src/diffusers/hooks/context_parallel.py index 07e59624f39f..e59c035d3e41 100644 --- a/src/diffusers/hooks/context_parallel.py +++ b/src/diffusers/hooks/context_parallel.py @@ -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] diff --git a/src/diffusers/models/_modeling_parallel.py b/src/diffusers/models/_modeling_parallel.py index 35b8fe3e0950..494286b48dfb 100644 --- a/src/diffusers/models/_modeling_parallel.py +++ b/src/diffusers/models/_modeling_parallel.py @@ -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*): @@ -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`." ) + 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, @@ -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) diff --git a/src/diffusers/models/modeling_utils.py b/src/diffusers/models/modeling_utils.py index 858b967d774e..7cf7da591ab2 100644 --- a/src/diffusers/models/modeling_utils.py +++ b/src/diffusers/models/modeling_utils.py @@ -1539,6 +1539,8 @@ def from_pretrained(cls, pretrained_model_name_or_path: str | os.PathLike | None module = model.get_submodule(module_path) if module_path else model module._buffers[buffer_name] = buffer.to(tp_device) + # Install CP hooks before attaching TP hooks to the sharded weights. + model._apply_context_parallel(parallel_config) apply_tensor_parallel(model, tp_config, cls._tp_plan, weights_already_sharded=True) else: model.enable_parallelism(config=parallel_config) @@ -1702,15 +1704,25 @@ def _resolve_parallel_config( device = torch.device(device_type, rank % torch.accelerator.device_count()) mesh = None - if config.context_parallel_config is not None: - cp_config = config.context_parallel_config + cp_config, tp_config = config.context_parallel_config, config.tensor_parallel_config + if cp_config is not None and tp_config is not None: + # Keep Ulysses ranks contiguous for backends that require it for all-to-all. + mesh = ( + cp_config.mesh + or tp_config.mesh + or torch.distributed.device_mesh.init_device_mesh( + device_type=device_type, + mesh_shape=(tp_config.tp_degree, *cp_config.mesh_shape), + mesh_dim_names=("tp", *cp_config.mesh_dim_names), + ) + ) + elif cp_config is not None: mesh = cp_config.mesh or torch.distributed.device_mesh.init_device_mesh( device_type=device_type, mesh_shape=cp_config.mesh_shape, mesh_dim_names=cp_config.mesh_dim_names, ) - elif config.tensor_parallel_config is not None: - tp_config = config.tensor_parallel_config + elif tp_config is not None: mesh = tp_config.mesh or torch.distributed.device_mesh.init_device_mesh( device_type=device_type, mesh_shape=(tp_config.tp_degree,), @@ -1719,6 +1731,22 @@ def _resolve_parallel_config( # `config.setup()` records the mesh resolved above onto the config; see `ParallelConfig.setup`. config.setup(rank, world_size, device, mesh=mesh) + + # Validate before installing hooks so a failed setup leaves the model usable. + if cp_config is not None and tp_config is not None: + tp_degree = tp_config._tp_degree + num_heads = getattr(self.config, "num_attention_heads", None) + divisor = tp_degree * cp_config.ulysses_degree + if num_heads is not None and not cp_config.ulysses_anything and num_heads % divisor != 0: + # Ulysses splits the heads remaining after TP. + raise ValueError( + f"Combining tensor parallelism (`tp_degree`={tp_degree}) with Ulysses context parallelism " + f"(`ulysses_degree`={cp_config.ulysses_degree}) requires the number of attention heads " + f"({num_heads}) to be divisible by their product ({divisor}): TP shards the heads first, and " + f"Ulysses splits what is left on each rank. Pass `ulysses_anything=True` to pad the head " + f"dimension instead, or pick degrees whose product divides {num_heads}." + ) + self._parallel_config = config if mesh is not None: @@ -1737,11 +1765,6 @@ def enable_parallelism( "`enable_parallelism` is an experimental feature. The API may change in the future and breaking changes may be introduced at any time without warning." ) - from ..hooks.context_parallel import apply_context_parallel - from .attention import AttentionModuleMixin - from .attention_dispatch import AttentionBackendName, _AttentionBackendRegistry - from .attention_processor import Attention, MochiAttention - if self._parallel_config is not None: raise RuntimeError( f"Parallelism is already applied to this {self.__class__.__name__}. `enable_parallelism` cannot be " @@ -1773,59 +1796,73 @@ def enable_parallelism( config = self._resolve_parallel_config(config) + self._apply_context_parallel(config, cp_plan) + + if config.tensor_parallel_config is not None: + from ..hooks.tensor_parallel import apply_tensor_parallel + + apply_tensor_parallel(self, config.tensor_parallel_config, self._tp_plan) + + def _apply_context_parallel( + self, + config: ParallelConfig, + cp_plan: dict[str, ContextParallelModelPlan] | None = None, + ): + """Install CP hooks and configure attention processors for distributed attention.""" + from ..hooks.context_parallel import apply_context_parallel + from .attention import AttentionModuleMixin + from .attention_dispatch import AttentionBackendName, _AttentionBackendRegistry + from .attention_processor import Attention, MochiAttention + + if config.context_parallel_config is None: + return + attention_classes = (Attention, MochiAttention, AttentionModuleMixin) - if config.context_parallel_config is not None: - for module in self.modules(): - if not isinstance(module, attention_classes): - continue + for module in self.modules(): + if not isinstance(module, attention_classes): + continue - processor = module.processor - if processor is None or not hasattr(processor, "_attention_backend"): - continue + processor = module.processor + if processor is None or not hasattr(processor, "_attention_backend"): + continue - attention_backend = processor._attention_backend - if attention_backend is None: - attention_backend, _ = _AttentionBackendRegistry.get_active_backend() - else: - attention_backend = AttentionBackendName(attention_backend) + attention_backend = processor._attention_backend + if attention_backend is None: + attention_backend, _ = _AttentionBackendRegistry.get_active_backend() + else: + attention_backend = AttentionBackendName(attention_backend) - if not _AttentionBackendRegistry._is_context_parallel_available(attention_backend): - compatible_backends = sorted(_AttentionBackendRegistry._supports_context_parallel) - raise ValueError( - f"Context parallelism is enabled but the attention processor '{processor.__class__.__name__}' " - f"is using backend '{attention_backend.value}' which does not support context parallelism. " - f"Please set a compatible attention backend: {compatible_backends} using `model.set_attention_backend()` before " - f"calling `model.enable_parallelism()`." - ) + if not _AttentionBackendRegistry._is_context_parallel_available(attention_backend): + compatible_backends = sorted(_AttentionBackendRegistry._supports_context_parallel) + raise ValueError( + f"Context parallelism is enabled but the attention processor '{processor.__class__.__name__}' " + f"is using backend '{attention_backend.value}' which does not support context parallelism. " + f"Please set a compatible attention backend: {compatible_backends} using `model.set_attention_backend()` before " + f"calling `model.enable_parallelism()`." + ) - # All modules use the same attention processor and backend. We don't need to - # iterate over all modules after checking the first processor - break + # All modules use the same attention processor and backend. We don't need to + # iterate over all modules after checking the first processor + break # Only context parallelism needs the config inside attention: it replaces the attention computation itself # (Ulysses all-to-all / ring). Tensor parallelism only shards `Linear` weights, so each rank runs the ordinary # attention op over its own heads and the processors must stay unaware of it. - if config.context_parallel_config is not None: - for module in self.modules(): - if not isinstance(module, attention_classes): - continue - processor = module.processor - if processor is None or not hasattr(processor, "_parallel_config"): - continue - processor._parallel_config = config - - if cp_plan is None and self._cp_plan is None: - raise ValueError( - "`cp_plan` must be provided either as an argument or set in the model's `_cp_plan` attribute." - ) - cp_plan = cp_plan if cp_plan is not None else self._cp_plan - apply_context_parallel(self, config.context_parallel_config, cp_plan) - - if config.tensor_parallel_config is not None: - from ..hooks.tensor_parallel import apply_tensor_parallel + for module in self.modules(): + if not isinstance(module, attention_classes): + continue + processor = module.processor + if processor is None or not hasattr(processor, "_parallel_config"): + continue + processor._parallel_config = config - apply_tensor_parallel(self, config.tensor_parallel_config, self._tp_plan) + if cp_plan is None and self._cp_plan is None: + raise ValueError( + "`cp_plan` must be provided either as an argument or set in the model's `_cp_plan` attribute." + ) + cp_plan = cp_plan if cp_plan is not None else self._cp_plan + apply_context_parallel(self, config.context_parallel_config, cp_plan) @classmethod def _load_pretrained_model( diff --git a/tests/models/test_parallelism_combined.py b/tests/models/test_parallelism_combined.py new file mode 100644 index 000000000000..d870b3317a15 --- /dev/null +++ b/tests/models/test_parallelism_combined.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# Copyright 2026 HuggingFace Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import timedelta + +import pytest +import torch +import torch.distributed as dist +import torch.multiprocessing as mp + +from diffusers.models._modeling_parallel import ContextParallelConfig, ParallelConfig, TensorParallelConfig + + +def _check_combined_mesh(rank, world_size, rendezvous, include_tp): + dist.init_process_group( + "gloo", init_method=rendezvous, rank=rank, world_size=world_size, timeout=timedelta(seconds=30) + ) + try: + shape, names = ((2, 1, 2), ("tp", "ring", "ulysses")) if include_tp else ((1, 2), ("ring", "ulysses")) + mesh = torch.distributed.device_mesh.init_device_mesh("cpu", shape, mesh_dim_names=names) + if not include_tp: + with pytest.raises(ValueError, match=r"\['tp'\].*missing"): + ParallelConfig( + context_parallel_config=ContextParallelConfig(ulysses_degree=2, mesh=mesh), + tensor_parallel_config=TensorParallelConfig(tp_degree=2), + ) + with pytest.raises(ValueError, match="exceeds the world size"): + ParallelConfig( + context_parallel_config=ContextParallelConfig(ulysses_degree=2), + tensor_parallel_config=TensorParallelConfig(tp_degree=2), + ) + return + + config = ParallelConfig( + context_parallel_config=ContextParallelConfig(ulysses_degree=2), + tensor_parallel_config=TensorParallelConfig(tp_degree=2), + ) + config.setup(rank, world_size, torch.device("cpu"), mesh=mesh) + tp_mesh = config.tensor_parallel_config._mesh + cp_mesh = config.context_parallel_config._flattened_mesh + cp_start = rank // 2 * 2 + assert dist.get_process_group_ranks(tp_mesh.get_group()) == [rank % 2, rank % 2 + 2] + assert dist.get_process_group_ranks(cp_mesh.get_group()) == [cp_start, cp_start + 1] + assert tp_mesh.get_local_rank() == rank // 2 + assert config.context_parallel_config._ulysses_local_rank == rank % 2 + finally: + dist.destroy_process_group() + + +@pytest.mark.skipif(not dist.is_available() or not dist.is_gloo_available(), reason="test requires Gloo") +class TestCombinedParallelConfig: + @pytest.mark.parametrize( + ("include_tp", "world_size"), [(True, 4), (False, 2)], ids=["separate-groups", "missing-tp"] + ) + def test_combined_mesh(self, tmp_path, include_tp, world_size): + rendezvous = (tmp_path / "rendezvous").as_uri() + mp.spawn(_check_combined_mesh, args=(world_size, rendezvous, include_tp), nprocs=world_size) diff --git a/tests/models/testing_utils/__init__.py b/tests/models/testing_utils/__init__.py index 1694e6ed76f1..05fb09ac157a 100644 --- a/tests/models/testing_utils/__init__.py +++ b/tests/models/testing_utils/__init__.py @@ -21,6 +21,7 @@ from .lora import LoraHotSwappingForModelTesterMixin, LoraTesterMixin from .memory import CPUOffloadTesterMixin, GroupOffloadTesterMixin, LayerwiseCastingTesterMixin, MemoryTesterMixin from .parallelism import ( + ContextAndTensorParallelTesterMixin, ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, TensorParallelNeuronTesterMixin, @@ -79,6 +80,7 @@ "BitsAndBytesConfigMixin", "BitsAndBytesTesterMixin", "CacheTesterMixin", + "ContextAndTensorParallelTesterMixin", "ContextParallelTesterMixin", "EntroPackConfigMixin", "EntroPackTesterMixin", diff --git a/tests/models/testing_utils/parallelism.py b/tests/models/testing_utils/parallelism.py index 71df97f1a4a9..c1b86b973895 100644 --- a/tests/models/testing_utils/parallelism.py +++ b/tests/models/testing_utils/parallelism.py @@ -15,6 +15,8 @@ import os import socket +from datetime import timedelta +from unittest.mock import patch import pytest import torch @@ -28,9 +30,10 @@ ContextParallelConfig, ContextParallelInput, ContextParallelOutput, + ParallelConfig, TensorParallelConfig, ) -from diffusers.models.attention_dispatch import AttentionBackendName, _AttentionBackendRegistry +from diffusers.models.attention_dispatch import AttentionBackendName, _AttentionBackendRegistry, attention_backend from diffusers.utils import SAFE_WEIGHTS_INDEX_NAME from diffusers.utils.torch_utils import randn_tensor @@ -788,7 +791,7 @@ class TensorParallelTPUTesterMixin: tp_world_size = 4 def test_tensor_parallel_tpu_inference(self, atol=1e-3, rtol=1e-3): - from torch_tpu._internal.distributed.launchers.singlehost_wrapper import prepare_tpu_environment + from torch.tpu import distributed as tpu_distributed from torch_tpu._internal.utils import hardware if getattr(self.model_class, "_tp_plan", None) is None: @@ -811,7 +814,7 @@ def test_tensor_parallel_tpu_inference(self, atol=1e-3, rtol=1e-3): tpu_env = ("TORCH_TPU_TOPOLOGY", "TORCH_TPU_SLICEBUILDER_ADDRESSES") for key in tpu_env: os.environ.pop(key, None) - prepare_tpu_environment(world_size) + tpu_distributed.set_tpu_launch_env(nproc_per_node=world_size) return_dict = mp.Manager().dict() try: mp.spawn( @@ -843,7 +846,7 @@ def test_tensor_parallel_tpu_inference(self, atol=1e-3, rtol=1e-3): @pytest.mark.parametrize("parallelism", ["tensor_parallel", "tensor_parallel_submesh"], ids=["mesh", "submesh"]) def test_tensor_parallel_tpu_rng_sync(self, tmp_path, parallelism, loading, atol=2e-2, rtol=2e-2): """Loading with a TP config gives every rank of the TP mesh the same default RNG, and only those ranks.""" - from torch_tpu._internal.distributed.launchers.singlehost_wrapper import prepare_tpu_environment + from torch.tpu import distributed as tpu_distributed from torch_tpu._internal.utils import hardware world_size = self.tp_world_size @@ -853,7 +856,7 @@ def test_tensor_parallel_tpu_rng_sync(self, tmp_path, parallelism, loading, atol tpu_env = ("TORCH_TPU_TOPOLOGY", "TORCH_TPU_SLICEBUILDER_ADDRESSES") for key in tpu_env: os.environ.pop(key, None) - prepare_tpu_environment(world_size) + tpu_distributed.set_tpu_launch_env(nproc_per_node=world_size) try: # Inputs, and so the reference, stay on CPU: touching the TPU here would bind every chip to this process. _check_parallel_rng_sync( @@ -872,6 +875,148 @@ def test_tensor_parallel_tpu_rng_sync(self, tmp_path, parallelism, loading, atol os.environ.pop(key, None) +def _context_and_tensor_parallel_worker( + rank, world_size, master_port, device_type, model_class, checkpoint, inputs, reference, config, loading +): + from torch.distributed.tensor import DTensor + + os.environ.update( + MASTER_ADDR="localhost", + MASTER_PORT=str(master_port), + RANK=str(rank), + LOCAL_RANK=str(rank), + LOCAL_WORLD_SIZE=str(world_size), + WORLD_SIZE=str(world_size), + ) + if device_type in ("cuda", "xpu"): + DEVICE_CONFIG[device_type]["module"].set_device(rank) + + dist.init_process_group(backend=DEVICE_CONFIG[device_type]["backend"], timeout=timedelta(minutes=3)) + try: + if device_type == "tpu": + device = torch.device("tpu") + torch.set_float32_matmul_precision("highest") + elif device_type == "neuron": + device = torch.neuron.current_device() + else: + device = torch.device(device_type, rank) + + if loading == "from_pretrained": + model = model_class.from_pretrained(checkpoint, parallel_config=config) + else: + model = model_class.from_pretrained(checkpoint) + if device_type == "neuron": + model.enable_parallelism(config=config) + model.to(device) + else: + model.to(device) + model.enable_parallelism(config=config) + + assert any( + isinstance(param, DTensor) and any(placement.is_shard() for placement in param.placements) + for param in model.parameters() + ), "No model weights were sharded by tensor parallelism." + + assert any( + name.startswith(("cp_input", "cp_output")) + for module in model.modules() + for name in getattr(getattr(module, "_diffusers_hook", None), "hooks", {}) + ), "The combined config did not install context-parallel hooks." + processors = model.attn_processors.values() + assert processors and all(getattr(processor, "_parallel_config", None) is config for processor in processors) + + device_inputs = { + name: value.to(device) if isinstance(value, torch.Tensor) else value for name, value in inputs.items() + } + with torch.no_grad(): + output = model(**device_inputs, return_dict=False) + tolerance = 2e-2 if device_type in ("tpu", "neuron") else 1e-3 + torch.testing.assert_close( + tuple(item.float().cpu() for item in output), reference, atol=tolerance, rtol=tolerance + ) + finally: + dist.destroy_process_group() + + +@is_context_parallel +@is_tensor_parallel +class ContextAndTensorParallelTesterMixin: + """Run TPU and Neuron cases in a fresh pytest process so workers can acquire their devices.""" + + @pytest.mark.parametrize("cp_axis", ["ulysses", "ring"]) + @pytest.mark.parametrize( + ("loading", "batch_size"), + [("enable_parallelism", 1), ("enable_parallelism", 2), ("from_pretrained", 1)], + ids=["enable", "enable-batched", "load"], + ) + def test_context_and_tensor_parallel_inference(self, tmp_path, cp_axis, loading, batch_size): + if not dist.is_available(): + pytest.skip("torch.distributed is not available.") + for plan in ("_tp_plan", "_cp_plan"): + if not getattr(self.model_class, plan, None): + pytest.skip(f"Model does not define a `{plan}`.") + + device_type = torch.device(torch_device).type + if device_type == "cpu" and "DIFFUSERS_TEST_DEVICE" not in os.environ and hasattr(torch, "tpu"): + device_type = "tpu" + if device_type not in DEVICE_CONFIG: + pytest.skip("Combined context and tensor parallelism requires CUDA, XPU, TPU, or Neuron.") + + active_backend, _ = _AttentionBackendRegistry.get_active_backend() + if cp_axis == "ring" and active_backend == AttentionBackendName.NATIVE: + pytest.skip("Ring attention requires an attention backend that returns log-sum-exp.") + + tp_degree = 2 + # Neuron all-to-all requires at least four ranks in each Ulysses group. + cp_degree = 4 if device_type == "neuron" and cp_axis == "ulysses" else 2 + world_size = tp_degree * cp_degree + device_count = ( + torch.accelerator.device_count() + if device_type == "tpu" + else DEVICE_CONFIG[device_type]["module"].device_count() + ) + if device_count < world_size: + pytest.skip(f"Needs {world_size} {device_type} devices, found {device_count}.") + + init_dict = self.get_init_dict() + head_count = init_dict.get("num_attention_heads") + head_divisor = world_size if cp_axis == "ulysses" else tp_degree + if head_count is not None and head_count % head_divisor: + pytest.skip(f"Number of attention heads ({head_count}) must be divisible by {head_divisor}.") + + inputs = self.get_dummy_inputs(batch_size=batch_size, device="cpu") + with torch.random.fork_rng(devices=[]), torch.no_grad(), attention_backend(AttentionBackendName.NATIVE): + torch.random.default_generator.manual_seed(0) + model = self.model_class(**init_dict).eval() + reference = tuple(item.float() for item in model(**inputs, return_dict=False)) + + checkpoint = tmp_path / "checkpoint" + model.save_pretrained(checkpoint) + config = ParallelConfig( + context_parallel_config=ContextParallelConfig(**{f"{cp_axis}_degree": cp_degree}), + tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), + ) + with patch.dict(os.environ): + if device_type == "tpu": + torch.tpu.distributed.set_tpu_launch_env(nproc_per_node=world_size) + mp.spawn( + _context_and_tensor_parallel_worker, + args=( + world_size, + _find_free_port(), + device_type, + self.model_class, + checkpoint, + inputs, + reference, + config, + loading, + ), + nprocs=world_size, + join=True, + ) + + @is_tensor_parallel @require_torch_neuron class TensorParallelNeuronTesterMixin: diff --git a/tests/models/transformers/test_models_transformer_flux.py b/tests/models/transformers/test_models_transformer_flux.py index b8c9cd662d63..9373c995c73a 100644 --- a/tests/models/transformers/test_models_transformer_flux.py +++ b/tests/models/transformers/test_models_transformer_flux.py @@ -32,6 +32,7 @@ BaseModelTesterConfig, BitsAndBytesCompileTesterMixin, BitsAndBytesTesterMixin, + ContextAndTensorParallelTesterMixin, ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, EntroPackTesterMixin, @@ -285,6 +286,11 @@ def get_init_dict(self): return {**super().get_init_dict(), "num_attention_heads": self.tp_world_size} +class TestFluxTransformerContextAndTensorParallel(FluxTransformerTesterConfig, ContextAndTensorParallelTesterMixin): + def get_init_dict(self): + return {**super().get_init_dict(), "num_attention_heads": 8} + + class TestFluxTransformerTensorParallelNeuron(FluxTransformerTesterConfig, TensorParallelNeuronTesterMixin): """Tensor Parallel inference test for Flux Transformer on AWS Neuron.""" diff --git a/tests/models/transformers/test_models_transformer_flux2.py b/tests/models/transformers/test_models_transformer_flux2.py index ca1df9429409..6fb6f5371043 100644 --- a/tests/models/transformers/test_models_transformer_flux2.py +++ b/tests/models/transformers/test_models_transformer_flux2.py @@ -31,6 +31,7 @@ AttentionTesterMixin, BaseModelTesterConfig, BitsAndBytesTesterMixin, + ContextAndTensorParallelTesterMixin, ContextParallelTesterMixin, GGUFCompileTesterMixin, GGUFTesterMixin, @@ -160,6 +161,11 @@ class TestFlux2TransformerAttention(Flux2TransformerTesterConfig, AttentionTeste """Attention processor tests for Flux2 Transformer.""" +class TestFlux2TransformerContextAndTensorParallel(Flux2TransformerTesterConfig, ContextAndTensorParallelTesterMixin): + def get_init_dict(self): + return {**super().get_init_dict(), "num_attention_heads": 8} + + class TestFlux2TransformerContextParallel(Flux2TransformerTesterConfig, ContextParallelTesterMixin): """Context Parallel inference tests for Flux2 Transformer.""" diff --git a/tests/models/transformers/test_models_transformer_minimax_h3.py b/tests/models/transformers/test_models_transformer_minimax_h3.py index efd56bfad381..c84d17a37719 100644 --- a/tests/models/transformers/test_models_transformer_minimax_h3.py +++ b/tests/models/transformers/test_models_transformer_minimax_h3.py @@ -24,6 +24,7 @@ AttentionTesterMixin, BaseModelTesterConfig, ComfyTesterMixin, + ContextAndTensorParallelTesterMixin, ContextParallelTesterMixin, LoraTesterMixin, MemoryTesterMixin, @@ -194,6 +195,17 @@ class TestMiniMaxH3TransformerTorchCompile(MiniMaxH3TransformerTesterConfig, Tor """Torch compile tests for the MiniMax-H3 transformer.""" +class TestMiniMaxH3TransformerContextAndTensorParallel( + MiniMaxH3TransformerTesterConfig, ContextAndTensorParallelTesterMixin +): + def get_init_dict(self): + return {**super().get_init_dict(), "num_attention_heads": 8} + + def get_dummy_inputs(self, batch_size=1, device="cpu"): + # Four text, six audio, and ten video tokens split evenly across two or four CP ranks. + return super().get_dummy_inputs(num_video_tokens=10, batch_size=batch_size, device=device) + + class TestMiniMaxH3TransformerContextParallel(MiniMaxH3TransformerTesterConfig, ContextParallelTesterMixin): """Context parallel inference tests for the MiniMax-H3 transformer.""" diff --git a/tests/models/transformers/test_models_transformer_minimax_h3_image.py b/tests/models/transformers/test_models_transformer_minimax_h3_image.py index 522096124ce9..8967ca5b70e1 100644 --- a/tests/models/transformers/test_models_transformer_minimax_h3_image.py +++ b/tests/models/transformers/test_models_transformer_minimax_h3_image.py @@ -24,6 +24,7 @@ from ..testing_utils import ( AttentionTesterMixin, BaseModelTesterConfig, + ContextAndTensorParallelTesterMixin, ContextParallelTesterMixin, MemoryTesterMixin, ModelTesterMixin, @@ -196,5 +197,12 @@ class TestMiniMaxH3ImageTransformerTorchCompile(MiniMaxH3ImageTransformerTesterC """Torch compile tests for the MiniMax-H3-Image transformer.""" +class TestMiniMaxH3ImageTransformerContextAndTensorParallel( + MiniMaxH3ImageTransformerTesterConfig, ContextAndTensorParallelTesterMixin +): + def get_init_dict(self): + return {**super().get_init_dict(), "num_attention_heads": 8} + + class TestMiniMaxH3ImageTransformerContextParallel(MiniMaxH3ImageTransformerTesterConfig, ContextParallelTesterMixin): """Context parallel inference tests for the MiniMax-H3-Image transformer.""" diff --git a/tests/models/transformers/test_models_transformer_qwenimage.py b/tests/models/transformers/test_models_transformer_qwenimage.py index 0c4d3abe60c8..8508e3095317 100644 --- a/tests/models/transformers/test_models_transformer_qwenimage.py +++ b/tests/models/transformers/test_models_transformer_qwenimage.py @@ -25,6 +25,7 @@ AttentionTesterMixin, BaseModelTesterConfig, BitsAndBytesTesterMixin, + ContextAndTensorParallelTesterMixin, ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, LoraHotSwappingForModelTesterMixin, @@ -316,6 +317,20 @@ def test_tensor_parallel_tpu_inference(self): super().test_tensor_parallel_tpu_inference(atol=2e-2, rtol=2e-2) +class TestQwenImageTransformerContextAndTensorParallel( + QwenImageTransformerTesterConfig, ContextAndTensorParallelTesterMixin +): + def get_init_dict(self): + return {**super().get_init_dict(), "num_attention_heads": 8} + + def get_dummy_inputs(self, batch_size: int = 1, device=torch_device) -> dict[str, torch.Tensor]: + inputs = super().get_dummy_inputs(batch_size=batch_size, device=device) + mask = inputs["encoder_hidden_states_mask"] + mask[:, 1:4:2] = 0 + mask[:, 5:] = 0 + return inputs + + class TestQwenImageTransformerTensorParallelNeuron(QwenImageTransformerTesterConfig, TensorParallelNeuronTesterMixin): """Tensor Parallel inference test for QwenImage Transformer on AWS Neuron."""