From 9c81ac694d2d60914ce562e0a214717cb6d9425e Mon Sep 17 00:00:00 2001 From: whn09 Date: Mon, 7 Sep 2026 03:08:20 +0000 Subject: [PATCH 01/16] Allow tensor parallelism and context parallelism in one ParallelConfig `ParallelConfig.__post_init__` rejects a config carrying both a `context_parallel_config` and a `tensor_parallel_config`, so a model can only use one form of parallelism at a time. That caps some models well below the hardware they run on: MiniMax-H3 has 56 attention heads, so `tp_degree` cannot exceed 8, and on a 64-accelerator host tensor parallelism alone leaves 56 of them idle even though the model already ships a `_cp_plan`. Both configs already accept a caller-supplied `mesh`, documented as being for "combining CP with other parallelism strategies that share the same mesh", so the intent was there; what was missing was building that shared mesh and splitting it between the two. * `__post_init__` now only rejects a config that carries neither. * `ParallelConfig.setup` hands each config its own dimensions: CP keeps the whole mesh, since its own `setup` selects "ring" and "ulysses" out of it, while TP gets the "tp" dimension alone because it reads its degree from `mesh.size()`. * `enable_parallelism` builds one ("tp", "ring", "ulysses") mesh when both are requested, with the context-parallel dimensions varying fastest. That order is a default rather than a universal optimum, and the comment says so: pass `mesh=` on either config to choose the layout yourself. * The Neuron tensor-parallel backend used the global rank as its shard index. That equals the rank's coordinate on the TP mesh only while that mesh spans the whole world, so sharing a mesh made it index past the end of the weight; the generic backend beside it already reads the coordinate. Measured on a trn2.48xlarge (MiniMax-H3, 1344x768x124f, 30 steps): TP=8 alone is 9.285 s/step on 8 cores, TP=4 x ulysses=4 is 5.66 s/step on 16, and TP=8 x ulysses=4 is 3.941 s/step on 32 -- 2.36x faster than the widest configuration reachable before this change, with output that is visually equivalent to the tensor-parallel-only run. Tests: a `HybridParallelTesterMixin` next to the existing TP and CP mixins, wired into the Flux transformer tests, plus a Neuron `torchrun` worker following the `_neuron_tp_worker.py` convention already in the tree. The Neuron test runs at tp_degree=2 x ulysses_degree=4 and passes on a trn2.48xlarge (max_abs_diff 4.2e-05 against the single-device reference). Co-Authored-By: Claude Opus 5 --- src/diffusers/hooks/tensor_parallel_neuron.py | 7 +- src/diffusers/models/_modeling_parallel.py | 13 +- src/diffusers/models/modeling_utils.py | 26 +++- tests/models/testing_utils/__init__.py | 2 + tests/models/testing_utils/parallelism.py | 131 +++++++++++++++++- .../transformers/_neuron_hybrid_worker.py | 125 +++++++++++++++++ .../test_models_transformer_flux.py | 48 ++++++- 7 files changed, 340 insertions(+), 12 deletions(-) create mode 100644 tests/models/transformers/_neuron_hybrid_worker.py diff --git a/src/diffusers/hooks/tensor_parallel_neuron.py b/src/diffusers/hooks/tensor_parallel_neuron.py index 6b8f219a17ff..9c53afc0f623 100644 --- a/src/diffusers/hooks/tensor_parallel_neuron.py +++ b/src/diffusers/hooks/tensor_parallel_neuron.py @@ -22,7 +22,6 @@ """ import torch -import torch.distributed as dist import torch.nn as nn @@ -171,7 +170,11 @@ def _apply_tp_neuron( Model weights must be on CPU when this is called. """ - rank = dist.get_rank() + # The shard index is this rank's coordinate on the tensor-parallel mesh, which is the global rank only + # when that mesh spans the whole world. Sharing a mesh with another parallelism makes `tp_mesh` a sub-mesh, + # and a global rank then indexes past the end of the weight. The generic backend already reads the + # coordinate (`tensor_parallel.py`), as does `ContextParallelConfig.setup`. + rank = tp_mesh.get_local_rank() tp_size = tp_mesh.size() for block, relative_plan in groups: diff --git a/src/diffusers/models/_modeling_parallel.py b/src/diffusers/models/_modeling_parallel.py index 86627284e078..a98574cc49e8 100644 --- a/src/diffusers/models/_modeling_parallel.py +++ b/src/diffusers/models/_modeling_parallel.py @@ -214,10 +214,10 @@ 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`." ) def setup( @@ -233,9 +233,14 @@ def setup( self._device = device self._mesh = mesh if self.context_parallel_config is not None: + # `ContextParallelConfig.setup` selects its own "ring" and "ulysses" dimensions out of `mesh`. self.context_parallel_config.setup(rank, world_size, device, mesh) if self.tensor_parallel_config is not None: - self.tensor_parallel_config.setup(rank, world_size, device, mesh) + # `TensorParallelConfig.setup` reads `tp_degree` off `mesh.size()`, so when the mesh is shared with + # context parallelism it must be handed the "tp" dimension alone rather than the whole mesh. + dim_names = (mesh.mesh_dim_names or ()) if mesh is not None else () + tp_mesh = mesh["tp"] if "tp" in dim_names and len(dim_names) > 1 else 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 425f2f29235e..6926b6fa89d3 100644 --- a/src/diffusers/models/modeling_utils.py +++ b/src/diffusers/models/modeling_utils.py @@ -1669,15 +1669,33 @@ def enable_parallelism( break 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: + # A single mesh spanning both parallelisms, with the context parallel dimensions varying fastest: a + # CP group is then a contiguous run of ranks and a TP group takes one rank out of each run. + # + # That order is a default, not a universal optimum. Some accelerator runtimes only accept contiguous + # replica groups for all-to-all -- which Ulysses needs -- while tolerating strided groups for + # all-reduce, which is all TP needs; since only one axis of a 2-D mesh can be contiguous, Ulysses + # gets it. On multi-node CUDA the opposite order is usually preferable, because TP is the most + # bandwidth-hungry collective and wants to stay within one NVLink domain. Pass `mesh=` on either + # config to choose the layout yourself. + 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,), diff --git a/tests/models/testing_utils/__init__.py b/tests/models/testing_utils/__init__.py index 760a3fac04e0..4d70f3a1ae29 100644 --- a/tests/models/testing_utils/__init__.py +++ b/tests/models/testing_utils/__init__.py @@ -20,6 +20,7 @@ from .parallelism import ( ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, + HybridParallelTesterMixin, TensorParallelTesterMixin, ) from .quantization import ( @@ -64,6 +65,7 @@ "CacheTesterMixin", "ContextParallelTesterMixin", "ContextParallelAttentionBackendsTesterMixin", + "HybridParallelTesterMixin", "TensorParallelTesterMixin", "CPUOffloadTesterMixin", "FasterCacheConfigMixin", diff --git a/tests/models/testing_utils/parallelism.py b/tests/models/testing_utils/parallelism.py index 63575abf6b7b..49c7acda6531 100644 --- a/tests/models/testing_utils/parallelism.py +++ b/tests/models/testing_utils/parallelism.py @@ -21,7 +21,7 @@ import torch.distributed as dist import torch.multiprocessing as mp -from diffusers.models._modeling_parallel import ContextParallelConfig, TensorParallelConfig +from diffusers.models._modeling_parallel import ContextParallelConfig, ParallelConfig, TensorParallelConfig from diffusers.models.attention_dispatch import AttentionBackendName, _AttentionBackendRegistry from ...testing_utils import ( @@ -295,6 +295,63 @@ def _tensor_parallel_worker( dist.destroy_process_group() +def _hybrid_parallel_worker( + rank, world_size, master_port, model_class, init_dict, cp_dict, tp_degree, inputs_dict, return_dict, state_dict +): + """Worker function for combined tensor + context parallel inference testing. + + Both parallelisms are requested through a single `ParallelConfig`, which shares one device mesh between them, so + each rank holds `1 / tp_degree` of every sharded weight *and* `1 / (ring_degree * ulysses_degree)` of the + sequence. Rank 0 reports its output so the caller can compare it against a single-device reference: the + composition is mathematically equivalent to the unsharded model up to floating-point reduction order. + """ + try: + os.environ["MASTER_ADDR"] = "localhost" + os.environ["MASTER_PORT"] = str(master_port) + os.environ["RANK"] = str(rank) + os.environ["WORLD_SIZE"] = str(world_size) + + device_config = DEVICE_CONFIG.get(torch_device, DEVICE_CONFIG["cuda"]) + backend = device_config["backend"] + device_module = device_config["module"] + + dist.init_process_group(backend=backend, rank=rank, world_size=world_size) + + device_module.set_device(rank) + device = torch.device(f"{torch_device}:{rank}") + + model = model_class(**init_dict) + model.load_state_dict(state_dict) + model.to(device) + model.eval() + + inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} + + model.enable_parallelism( + config=ParallelConfig( + tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), + context_parallel_config=ContextParallelConfig(**cp_dict), + ) + ) + + with torch.no_grad(): + output = model(**inputs_on_device, return_dict=False)[0] + + if rank == 0: + return_dict["status"] = "success" + return_dict["output_shape"] = list(output.shape) + # Serialise via nested list so the manager dict can transport it across processes. + return_dict["output"] = output.float().cpu().tolist() + + except Exception as e: + if rank == 0: + return_dict["status"] = "error" + return_dict["error"] = str(e) + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + @is_tensor_parallel @require_torch_multi_accelerator class TensorParallelTesterMixin: @@ -345,6 +402,78 @@ def test_tensor_parallel_batch_inputs(self): self.test_tensor_parallel_inference(batch_size=2) +@is_context_parallel +@is_tensor_parallel +@require_torch_multi_accelerator +class HybridParallelTesterMixin: + """Tensor parallelism and context parallelism together, from one `ParallelConfig`. + + Needs `tp_degree * ulysses_degree` accelerators (4 at the degrees used here), so it skips on a 2-device runner. + """ + + def test_hybrid_parallel_inference(self, batch_size: int = 1): + if not torch.distributed.is_available(): + pytest.skip("torch.distributed is not available.") + + for plan in ("_tp_plan", "_cp_plan"): + if getattr(self.model_class, plan, None) is None: + pytest.skip(f"Model does not define a `{plan}`, which hybrid parallelism requires.") + + tp_degree, ulysses_degree = 2, 2 + world_size = tp_degree * ulysses_degree + device_count = DEVICE_CONFIG.get(torch_device, DEVICE_CONFIG["cuda"])["module"].device_count() + if device_count < world_size: + pytest.skip( + f"tp_degree={tp_degree} x ulysses_degree={ulysses_degree} needs {world_size} accelerators, " + f"found {device_count}." + ) + + init_dict = self.get_init_dict() + num_heads = init_dict.get("num_attention_heads") + # Each rank keeps `num_heads // tp_degree` heads, which Ulysses splits again. + if num_heads is not None and num_heads % world_size != 0: + pytest.skip(f"`num_attention_heads` ({num_heads}) is not divisible by {world_size}.") + + inputs_dict = self.get_dummy_inputs(batch_size=batch_size) + + # Single-device reference + model = self.model_class(**init_dict).eval().to(torch_device) + state_dict = {k: v.cpu() for k, v in model.state_dict().items()} + with torch.no_grad(): + ref_output = model(**inputs_dict, return_dict=False)[0].float().cpu() + + inputs_dict = {k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} + + master_port = _find_free_port() + manager = mp.Manager() + return_dict = manager.dict() + + mp.spawn( + _hybrid_parallel_worker, + args=( + world_size, + master_port, + self.model_class, + init_dict, + {"ulysses_degree": ulysses_degree}, + tp_degree, + inputs_dict, + return_dict, + state_dict, + ), + nprocs=world_size, + join=True, + ) + + assert return_dict.get("status") == "success", ( + f"Hybrid parallel inference failed: {return_dict.get('error', 'Unknown error')}" + ) + + output = torch.tensor(return_dict["output"]) + # Sharded matmuls plus the Ulysses all-to-all reorder the summation, hence the tolerance. + torch.testing.assert_close(ref_output, output, atol=1e-3, rtol=1e-3) + + @is_context_parallel @require_torch_multi_accelerator class ContextParallelTesterMixin: diff --git a/tests/models/transformers/_neuron_hybrid_worker.py b/tests/models/transformers/_neuron_hybrid_worker.py new file mode 100644 index 000000000000..1c054af44104 --- /dev/null +++ b/tests/models/transformers/_neuron_hybrid_worker.py @@ -0,0 +1,125 @@ +# 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. + +"""Generic torchrun worker: assert a model's Neuron tensor-parallel x context-parallel output matches its reference. + +The counterpart of `_neuron_tp_worker.py` for the two parallelisms composed in a single `ParallelConfig`. Same +contract: the model under test is supplied as a `module:function` spec reference on the command line, and the +referenced factory returns `(model_class, init_dict, inputs)` with CPU tensors. + + torchrun --nproc_per_node=8 _neuron_hybrid_worker.py \\ + tests.models.transformers.test_models_transformer_flux:make_neuron_hybrid_spec + +`tp_degree` and `ulysses_degree` are read from `TP_DEGREE` / `ULYSSES_DEGREE` (defaults 2 and 4, whose product is +the launched world size). `ulysses_degree` cannot be 2 on Neuron: its all-to-all only accepts group sizes of 4, 8, +16 or multiples of 32. + +No mesh is passed, so this also exercises the default mesh layout that `enable_parallelism` builds for the combined +case -- which matters on Neuron, where the all-to-all Ulysses depends on rejects strided replica groups and so the +context-parallel dimensions have to vary fastest. + +Exit code 0 means the composed path is numerically equivalent to the unsharded model; non-zero means failure. +""" + +import argparse +import importlib +import os +import sys +import traceback + + +# Make the in-repo `diffusers` and `tests` packages importable when run via torchrun from an arbitrary CWD. +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "src")) +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..")) + +import torch +import torch.distributed as dist +import torch_neuronx # noqa: F401 — registers torch.neuron + +from diffusers import ContextParallelConfig, ParallelConfig, TensorParallelConfig + + +def main(): + parser = argparse.ArgumentParser(description="Neuron tensor-parallel x context-parallel correctness worker.") + parser.add_argument( + "spec", + help="`module:function` reference returning (model_class, init_dict, cpu_inputs) for the model under test.", + ) + args = parser.parse_args() + module_name, _, fn_name = args.spec.partition(":") + model_class, init_dict, inputs = getattr(importlib.import_module(module_name), fn_name)() + + tp_degree = int(os.environ.get("TP_DEGREE", "2")) + ulysses_degree = int(os.environ.get("ULYSSES_DEGREE", "4")) + + dist.init_process_group(backend="neuron") + rank = dist.get_rank() + world_size = dist.get_world_size() + device = torch.neuron.current_device() + + if tp_degree * ulysses_degree != world_size: + raise ValueError( + f"tp_degree ({tp_degree}) x ulysses_degree ({ulysses_degree}) must equal the world size ({world_size})." + ) + + # Identical weights on every rank (same seed), kept on CPU as the Neuron pre-shard backend requires. + torch.manual_seed(0) + model = model_class(**init_dict).eval() + + # Single-device (unsharded) reference on CPU, computed before the shard plan mutates the weights in place. + with torch.no_grad(): + ref_output = model(**inputs, return_dict=False)[0].float().cpu() + + model.enable_parallelism( + config=ParallelConfig( + tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), + context_parallel_config=ContextParallelConfig(ulysses_degree=ulysses_degree), + ) + ) + model = model.to(device) + torch.neuron.synchronize() + + inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} + with torch.no_grad(): + output = model(**inputs_on_device, return_dict=False)[0] + torch.neuron.synchronize() + output = output.float().cpu() + + if rank == 0: + assert output.shape == ref_output.shape, f"shape mismatch: {output.shape} vs {ref_output.shape}" + assert torch.isfinite(output).all(), "output contains non-finite values" + max_abs = (output - ref_output).abs().max().item() + denom = ref_output.abs().max().item() + 1e-6 + print( + f"[rank0] tp_degree={tp_degree} ulysses_degree={ulysses_degree} " + f"output_shape={tuple(output.shape)} max_abs_diff={max_abs:.4e} max_rel_diff={max_abs / denom:.4e}" + ) + # Neuron runs matmuls in bf16 internally, so compare with a bf16-level tolerance, as `_neuron_tp_worker` + # does. A wrong shard plan or a mis-ordered mesh produces grossly different output and is caught well + # inside this bound. + torch.testing.assert_close(output, ref_output, atol=2e-2, rtol=2e-2) + print("[rank0] PASS: Neuron hybrid-parallel output matches single-device reference.") + + dist.barrier() + dist.destroy_process_group() + + +if __name__ == "__main__": + try: + main() + except Exception: + traceback.print_exc() + # Ensure a non-zero exit so the launching pytest sees the failure. + os._exit(1) diff --git a/tests/models/transformers/test_models_transformer_flux.py b/tests/models/transformers/test_models_transformer_flux.py index 53af9eedc50c..e4d7ce8b808e 100644 --- a/tests/models/transformers/test_models_transformer_flux.py +++ b/tests/models/transformers/test_models_transformer_flux.py @@ -27,7 +27,13 @@ from diffusers.models.transformers.transformer_flux import FluxIPAdapterAttnProcessor from diffusers.utils.torch_utils import randn_tensor -from ...testing_utils import enable_full_determinism, is_tensor_parallel, require_torch_neuron, torch_device +from ...testing_utils import ( + enable_full_determinism, + is_context_parallel, + is_tensor_parallel, + require_torch_neuron, + torch_device, +) from ..testing_utils import ( AttentionBackendTesterMixin, AttentionTesterMixin, @@ -40,6 +46,7 @@ FirstBlockCacheTesterMixin, GGUFCompileTesterMixin, GGUFTesterMixin, + HybridParallelTesterMixin, IPAdapterTesterMixin, LoraHotSwappingForModelTesterMixin, LoraTesterMixin, @@ -268,6 +275,23 @@ class TestFluxTransformerTensorParallel(FluxTransformerTesterConfig, TensorParal """Tensor Parallel inference tests for Flux Transformer (CUDA/XPU multi-accelerator).""" +class TestFluxTransformerHybridParallel(FluxTransformerTesterConfig, HybridParallelTesterMixin): + """Tensor Parallel x Context Parallel inference tests for Flux Transformer (needs 4 accelerators).""" + + +def make_neuron_hybrid_spec(): + """Model spec consumed by the generic Neuron hybrid worker (`_neuron_hybrid_worker.py`). + + Same contract as `make_neuron_tp_spec`, but `num_attention_heads` is raised to 8 so the head count survives + being divided twice: `tp_degree=2` leaves 4 heads per rank and `ulysses_degree=4` splits those into 1 each. + (`ulysses_degree` cannot be 2 on Neuron, whose all-to-all only accepts group sizes of 4, 8, 16 or multiples + of 32.) + """ + config = FluxTransformerTesterConfig() + init_dict = config.get_init_dict() | {"num_attention_heads": 8} + return FluxTransformer2DModel, init_dict, config.get_dummy_inputs(device="cpu") + + def make_neuron_tp_spec(): """Model spec consumed by the generic Neuron TP worker (`_neuron_tp_worker.py`). @@ -301,6 +325,28 @@ def test_tensor_parallel_neuron_inference(self): ) +@is_context_parallel +@is_tensor_parallel +@require_torch_neuron +class TestFluxTransformerHybridParallelNeuron: + """Tensor Parallel x Context Parallel inference test for Flux Transformer on AWS Neuron. + + Same launching pattern as `TestFluxTransformerTensorParallelNeuron`: Neuron needs `torchrun` with the + `"neuron"` distributed backend, so it cannot use the `torch.multiprocessing`/NCCL spawn path of + `HybridParallelTesterMixin`. Runs at `tp_degree=2 x ulysses_degree=4`, i.e. 8 ranks. + """ + + def test_hybrid_parallel_neuron_inference(self): + worker = os.path.join(os.path.dirname(__file__), "_neuron_hybrid_worker.py") + spec = "tests.models.transformers.test_models_transformer_flux:make_neuron_hybrid_spec" + cmd = [sys.executable, "-m", "torch.distributed.run", "--nproc_per_node=8", worker, spec] + result = subprocess.run(cmd, capture_output=True, text=True) + assert result.returncode == 0, ( + f"Neuron hybrid-parallel worker failed (exit {result.returncode}).\n" + f"--- stdout ---\n{result.stdout}\n--- stderr ---\n{result.stderr}" + ) + + class TestFluxTransformerIPAdapter(FluxTransformerTesterConfig, IPAdapterTesterMixin): """IP Adapter tests for Flux Transformer.""" From 3f558840ec1eb03bc98989fbf05e183edf9df42c Mon Sep 17 00:00:00 2001 From: whn09 Date: Mon, 7 Sep 2026 03:28:12 +0000 Subject: [PATCH 02/16] Apply the context-parallel hooks on the sharded-load path too `from_pretrained(..., parallel_config=...)` shards weights while reading the checkpoint, so `enable_parallelism` cannot be called afterwards -- it raises by design -- and the loader applies the parallelism itself. It applies tensor parallelism but never the context-parallel hooks, so a `ParallelConfig` that carries both is silently reduced to tensor parallelism alone: no error, correct numbers, and every rank redundantly computing the whole sequence. The context-parallel half of `enable_parallelism` moves into `_apply_context_parallel`, split out for the same reason `_resolve_parallel_config` was, and both sharded-load paths (safetensors and DCP) call it before applying tensor parallelism -- the same order `enable_parallelism` uses. This matters for models that need both: MiniMax-H3 has 56 attention heads, so `tp_degree` caps at 8, and at 33B parameters the `enable_parallelism` route is not an option because every rank would first have to hold the full checkpoint. The sharded-load path is the only way such a model can reach beyond 8 accelerators. Reachable once `ParallelConfig` accepts both configs (huggingface/diffusers#14725). Tests: a Neuron `torchrun` worker following the `_neuron_tp_worker.py` convention, run at tp_degree=2 x ulysses_degree=4 on a trn2.48xlarge. It asserts that the hooks are registered and that the attention processors received the config -- neither of which output values can detect, since a model that skips them still returns the right answer -- and that the output still matches a single-device reference read back from the same checkpoint. Co-Authored-By: Claude Opus 5 --- src/diffusers/models/modeling_utils.py | 39 ++-- .../_neuron_sharded_load_worker.py | 170 ++++++++++++++++++ .../test_models_transformer_flux.py | 35 ++++ 3 files changed, 234 insertions(+), 10 deletions(-) create mode 100644 tests/models/transformers/_neuron_sharded_load_worker.py diff --git a/src/diffusers/models/modeling_utils.py b/src/diffusers/models/modeling_utils.py index 6d7b3c5035cd..9ef9128e5013 100644 --- a/src/diffusers/models/modeling_utils.py +++ b/src/diffusers/models/modeling_utils.py @@ -1546,6 +1546,9 @@ def from_pretrained(cls, pretrained_model_name_or_path: str | os.PathLike | None # was recorded by `_resolve_parallel_config` before loading. from ..hooks.tensor_parallel import apply_tensor_parallel + # A config that also asks for context parallelism gets its hooks here, in the same order as + # `enable_parallelism`, which is no longer callable now that the weights are sharded. + 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) @@ -1768,11 +1771,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 " @@ -1799,6 +1797,32 @@ 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 the context-parallel hooks `config` asks for, if any, and hand it to the attention processors. + + Split out of `enable_parallelism` for the same reason as `_resolve_parallel_config`: `from_pretrained(..., + parallel_config=...)` shards the weights while reading them, so it cannot call `enable_parallelism` + afterwards, yet it still has to apply these hooks when the config asks for context parallelism. + """ + 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: @@ -1848,11 +1872,6 @@ def enable_parallelism( 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 - - apply_tensor_parallel(self, config.tensor_parallel_config, self._tp_plan) - @classmethod def _load_pretrained_model( cls, diff --git a/tests/models/transformers/_neuron_sharded_load_worker.py b/tests/models/transformers/_neuron_sharded_load_worker.py new file mode 100644 index 000000000000..dd25d33b35a9 --- /dev/null +++ b/tests/models/transformers/_neuron_sharded_load_worker.py @@ -0,0 +1,170 @@ +# 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. + +"""Generic torchrun worker: assert `from_pretrained(..., parallel_config=...)` installs the context-parallel hooks. + +The sharded-load path shards weights while reading the checkpoint, so it cannot call `enable_parallelism` afterwards +and applies the parallelism itself. Tensor parallelism it did apply; the context-parallel hooks it did not, which is +silent — the model still returns the right numbers, every rank just redundantly computes the whole sequence. So this +worker checks both halves: the hooks are registered *and* the output still matches a single-device reference. + +Same contract as `_neuron_tp_worker.py`: the model under test is supplied as a `module:function` spec reference on +the command line, and the referenced factory returns `(model_class, init_dict, inputs)` with CPU tensors. + + torchrun --nproc_per_node=8 _neuron_sharded_load_worker.py \\ + tests.models.transformers.test_models_transformer_flux:make_neuron_sharded_load_spec + +`tp_degree` and `ulysses_degree` are read from `TP_DEGREE` / `ULYSSES_DEGREE` (defaults 2 and 4, whose product is +the launched world size). `ulysses_degree` cannot be 2 on Neuron: its all-to-all only accepts group sizes of 4, 8, +16 or multiples of 32. + +Rank 0 writes the checkpoint that every rank then reads, so this is single-node only, as the rest of the Neuron +test workers are. + +Exit code 0 means the sharded-load path applied both parallelisms correctly; non-zero means failure. +""" + +import argparse +import importlib +import os +import shutil +import sys +import tempfile +import traceback + + +# Make the in-repo `diffusers` and `tests` packages importable when run via torchrun from an arbitrary CWD. +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "src")) +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..")) + +import torch +import torch.distributed as dist +import torch_neuronx # noqa: F401 — registers torch.neuron + +from diffusers import ContextParallelConfig, ParallelConfig, TensorParallelConfig + + +def _context_parallel_hook_names(model): + """Every `cp_input---*` / `cp_output---*` hook `apply_context_parallel` registered on `model`.""" + names = [] + for module in model.modules(): + registry = getattr(module, "_diffusers_hook", None) + if registry is not None: + names.extend(name for name in registry.hooks if name.startswith(("cp_input", "cp_output"))) + return names + + +def main(): + parser = argparse.ArgumentParser(description="Neuron sharded-load context-parallel hook worker.") + parser.add_argument( + "spec", + help="`module:function` reference returning (model_class, init_dict, cpu_inputs) for the model under test.", + ) + args = parser.parse_args() + module_name, _, fn_name = args.spec.partition(":") + model_class, init_dict, inputs = getattr(importlib.import_module(module_name), fn_name)() + + tp_degree = int(os.environ.get("TP_DEGREE", "2")) + ulysses_degree = int(os.environ.get("ULYSSES_DEGREE", "4")) + + dist.init_process_group(backend="neuron") + rank = dist.get_rank() + world_size = dist.get_world_size() + device = torch.neuron.current_device() + + if tp_degree * ulysses_degree != world_size: + raise ValueError( + f"tp_degree ({tp_degree}) x ulysses_degree ({ulysses_degree}) must equal the world size ({world_size})." + ) + + # Rank 0 writes the checkpoint the sharded loader then reads on every rank. Safetensors, because that is what + # the per-rank streaming loader requires. + checkpoint_dir = os.environ.get( + "SHARDED_LOAD_CHECKPOINT_DIR", os.path.join(tempfile.gettempdir(), "diffusers_neuron_sharded_load_ckpt") + ) + if rank == 0: + shutil.rmtree(checkpoint_dir, ignore_errors=True) + torch.manual_seed(0) + model_class(**init_dict).eval().save_pretrained(checkpoint_dir) + dist.barrier() + + # Single-device (unsharded) reference, read back from the same checkpoint so only the loading path differs. + ref_output = None + if rank == 0: + reference = model_class.from_pretrained(checkpoint_dir).eval() + with torch.no_grad(): + ref_output = reference(**inputs, return_dict=False)[0].float().cpu() + del reference + + model = model_class.from_pretrained( + checkpoint_dir, + parallel_config=ParallelConfig( + tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), + context_parallel_config=ContextParallelConfig(ulysses_degree=ulysses_degree), + ), + ).eval() + torch.neuron.synchronize() + + # The point of the test: the loader has to install these itself, since `enable_parallelism` is unavailable + # once the weights are sharded. + hook_names = _context_parallel_hook_names(model) + assert hook_names, ( + "`from_pretrained(..., parallel_config=...)` applied tensor parallelism but registered no context-parallel " + "hooks, so the `context_parallel_config` was silently ignored." + ) + processors = [getattr(module, "processor", None) for module in model.modules()] + processor_configs = [ + getattr(p, "_parallel_config", None) for p in processors if p is not None and hasattr(p, "_parallel_config") + ] + assert processor_configs and all(c is not None for c in processor_configs), ( + "Context-parallel hooks are registered but the attention processors did not receive the `ParallelConfig`, " + "so attention would run without the Ulysses all-to-all." + ) + + inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} + with torch.no_grad(): + output = model(**inputs_on_device, return_dict=False)[0] + torch.neuron.synchronize() + output = output.float().cpu() + + if rank == 0: + assert output.shape == ref_output.shape, f"shape mismatch: {output.shape} vs {ref_output.shape}" + assert torch.isfinite(output).all(), "output contains non-finite values" + max_abs = (output - ref_output).abs().max().item() + denom = ref_output.abs().max().item() + 1e-6 + print( + f"[rank0] tp_degree={tp_degree} ulysses_degree={ulysses_degree} " + f"context_parallel_hooks={len(hook_names)} output_shape={tuple(output.shape)} " + f"max_abs_diff={max_abs:.4e} max_rel_diff={max_abs / denom:.4e}" + ) + # Neuron runs matmuls in bf16 internally, so compare with a bf16-level tolerance, as `_neuron_tp_worker` + # does. A wrong shard plan or a mis-ordered mesh produces grossly different output and is caught well + # inside this bound. + torch.testing.assert_close(output, ref_output, atol=2e-2, rtol=2e-2) + print("[rank0] PASS: sharded load applied both parallelisms and matches the single-device reference.") + + dist.barrier() + if rank == 0: + shutil.rmtree(checkpoint_dir, ignore_errors=True) + dist.destroy_process_group() + + +if __name__ == "__main__": + try: + main() + except Exception: + traceback.print_exc() + # Ensure a non-zero exit so the launching pytest sees the failure. + os._exit(1) diff --git a/tests/models/transformers/test_models_transformer_flux.py b/tests/models/transformers/test_models_transformer_flux.py index 8b36e579d833..7942be68d323 100644 --- a/tests/models/transformers/test_models_transformer_flux.py +++ b/tests/models/transformers/test_models_transformer_flux.py @@ -320,6 +320,41 @@ def make_neuron_tp_spec(): return FluxTransformer2DModel, config.get_init_dict(), config.get_dummy_inputs(device="cpu") +def make_neuron_sharded_load_spec(): + """Model spec consumed by the sharded-load worker (`_neuron_sharded_load_worker.py`). + + Same contract as `make_neuron_tp_spec`, but `num_attention_heads` is raised to 8 so the head count survives + being divided twice: `tp_degree=2` leaves 4 heads per rank and `ulysses_degree=4` splits those into 1 each. + (`ulysses_degree` cannot be 2 on Neuron, whose all-to-all only accepts group sizes of 4, 8, 16 or multiples + of 32.) + """ + config = FluxTransformerTesterConfig() + init_dict = config.get_init_dict() | {"num_attention_heads": 8} + return FluxTransformer2DModel, init_dict, config.get_dummy_inputs(device="cpu") + + +@is_tensor_parallel +@require_torch_neuron +class TestFluxTransformerShardedLoadNeuron: + """`from_pretrained(..., parallel_config=...)` with both parallelisms, on AWS Neuron. + + Launched the same way as `TestFluxTransformerTensorParallelNeuron`, at `tp_degree=2 x ulysses_degree=4`, i.e. 8 + ranks. The worker asserts that the sharded-load path registered the context-parallel hooks — which numbers alone + cannot detect, since a model that silently skips them still returns the right answer — and that the output still + matches a single-device reference read back from the same checkpoint. + """ + + def test_sharded_load_context_parallel_neuron(self): + worker = os.path.join(os.path.dirname(__file__), "_neuron_sharded_load_worker.py") + spec = "tests.models.transformers.test_models_transformer_flux:make_neuron_sharded_load_spec" + cmd = [sys.executable, "-m", "torch.distributed.run", "--nproc_per_node=8", worker, spec] + result = subprocess.run(cmd, capture_output=True, text=True) + assert result.returncode == 0, ( + f"Neuron sharded-load worker failed (exit {result.returncode}).\n" + f"--- stdout ---\n{result.stdout}\n--- stderr ---\n{result.stderr}" + ) + + @is_tensor_parallel @require_torch_neuron class TestFluxTransformerTensorParallelNeuron: From 8a1c4d77ecf81026c1e639f5225197d9348b1106 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Tue, 13 Oct 2026 14:47:33 +0000 Subject: [PATCH 03/16] fix: pad uneven all-gathers on Neuron and TPU in _all_gather_anything --- src/diffusers/hooks/context_parallel.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/diffusers/hooks/context_parallel.py b/src/diffusers/hooks/context_parallel.py index 1310b20c5c11..4b0a90dac4c2 100644 --- a/src/diffusers/hooks/context_parallel.py +++ b/src/diffusers/hooks/context_parallel.py @@ -345,6 +345,17 @@ 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"): + # Neuron and TPU all-gathers require every rank to send the same size, so pad each chunk to the longest one, + # gather, and trim each chunk back to its real length. + 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] From ce1581f0f76586a06bee40991e15d6f743467ec9 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Wed, 14 Oct 2026 15:38:01 +0000 Subject: [PATCH 04/16] Validate TP+CP degrees up front and add tests for the combined mesh Before any hooks are applied, check that ring x ulysses x tp fits the world size, that the shared mesh has "tp", "ring" and "ulysses" dimensions, and that the attention heads divide tp x ulysses. Add ContextAndTensorParallelTesterMixin, CPU/gloo tests for the mesh layout, and a Qwen-Image TP+CP test. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/diffusers/models/_modeling_parallel.py | 40 ++++- src/diffusers/models/modeling_utils.py | 26 +++ tests/models/test_parallelism_combined.py | 164 ++++++++++++++++++ tests/models/testing_utils/__init__.py | 2 + tests/models/testing_utils/parallelism.py | 144 +++++++++++++++ .../test_models_transformer_qwenimage.py | 20 +++ 6 files changed, 390 insertions(+), 6 deletions(-) create mode 100644 tests/models/test_parallelism_combined.py diff --git a/src/diffusers/models/_modeling_parallel.py b/src/diffusers/models/_modeling_parallel.py index e18d551b24bc..cf576ab6bb77 100644 --- a/src/diffusers/models/_modeling_parallel.py +++ b/src/diffusers/models/_modeling_parallel.py @@ -200,6 +200,12 @@ class ParallelConfig: """ Configuration for applying different parallelisms. + Both may be set at once. The two are then applied over one device mesh with a dimension each — `("tp", "ring", + "ulysses")`, built by `enable_parallelism` — so their collectives stay in separate process groups. This is what + lets a model too large for one device (TP shards the weights) also run a sequence too long for one device's + attention scratchpad (CP splits the sequence): TP alone cannot divide the sequence, and CP alone cannot divide the + weights. + Args: context_parallel_config (`ContextParallelConfig`, *optional*): Configuration for context parallelism. @@ -222,6 +228,11 @@ def __post_init__(self): "`tensor_parallel_config`." ) + @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,14 +245,31 @@ def setup( self._world_size = world_size self._device = device self._mesh = mesh + + # Context and tensor parallelism compose because they cut the model along different axes: CP splits the + # sequence (and, under Ulysses, trades sequence for heads inside attention) while TP shards the Linear + # weights. Composing them means giving each its own mesh *dimension*, so that every collective one issues + # stays inside its own process group: TP's all-reduce must not reach a rank holding a different sequence + # chunk, and CP's sequence all-gather must not reach a rank holding a different weight shard. + cp_mesh = tp_mesh = mesh + if self._is_combined: + dim_names = mesh.mesh_dim_names if mesh is not None else None + 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}). `enable_parallelism` builds this mesh from `ring_degree`/`ulysses_degree`/" + f"`tp_degree`; if you build it yourself, set `mesh=` on one of the two configs." + ) + # `ContextParallelConfig.setup` slices ("ring", "ulysses") off whatever mesh it is handed, so it takes + # the full mesh. TP instead needs its own 1-D submesh: `parallelize_module` shards a weight over every + # rank of the mesh it is given, so handing it the 3-D mesh would shard over the CP ranks as well. + tp_mesh = mesh["tp"] + if self.context_parallel_config is not None: - # `ContextParallelConfig.setup` selects its own "ring" and "ulysses" dimensions out of `mesh`. - 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: - # `TensorParallelConfig.setup` reads `tp_degree` off `mesh.size()`, so when the mesh is shared with - # context parallelism it must be handed the "tp" dimension alone rather than the whole mesh. - dim_names = (mesh.mesh_dim_names or ()) if mesh is not None else () - tp_mesh = mesh["tp"] if "tp" in dim_names and len(dim_names) > 1 else mesh self.tensor_parallel_config.setup(rank, world_size, device, tp_mesh) diff --git a/src/diffusers/models/modeling_utils.py b/src/diffusers/models/modeling_utils.py index 9ef9128e5013..e6c1ef6f8266 100644 --- a/src/diffusers/models/modeling_utils.py +++ b/src/diffusers/models/modeling_utils.py @@ -1758,6 +1758,32 @@ 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 the combination up front — after `setup`, which resolves `_tp_degree` from the mesh, but before + # anything is recorded on the model or applied to it. CP hooks are applied before TP, so a check left to the + # TP branch would raise on a model already carrying CP hooks: half-parallelised, and not usable. + if cp_config is not None and tp_config is not None: + tp_degree = tp_config._tp_degree + requested = cp_config.ring_degree * cp_config.ulysses_degree * 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_degree}) = {requested} " + f"devices, which exceeds the world size ({world_size})." + ) + 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 trades sequence for heads inside attention (`SeqAllToAllDim` scatters over dim 2), and it + # only ever sees the heads TP left on this rank, so the count has to survive both splits. + 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 return config diff --git a/tests/models/test_parallelism_combined.py b/tests/models/test_parallelism_combined.py new file mode 100644 index 000000000000..4a404a06125e --- /dev/null +++ b/tests/models/test_parallelism_combined.py @@ -0,0 +1,164 @@ +# 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. + +"""Tests for combining context parallelism with tensor parallelism on one device mesh. + +These cover the wiring rather than the numerics: that `ParallelConfig` hands each parallelism its own submesh, and +that the resulting process groups are the intended factorisation of the world. They run on CPU over `gloo`, so they +need no accelerator — `gloo` has no `all_to_all`, so an end-to-end Ulysses forward pass cannot run here; that is +covered by `ContextAndTensorParallelTesterMixin` in `testing_utils/parallelism.py`, which needs four accelerators. +""" + +import os +import socket + +import pytest +import torch +import torch.distributed as dist +import torch.multiprocessing as mp + +from diffusers.models._modeling_parallel import ContextParallelConfig, ParallelConfig, TensorParallelConfig + + +def _find_free_port(): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("", 0)) + s.listen(1) + return s.getsockname()[1] + + +def _mesh_factorization_worker(rank, world_size, master_port, ulysses_degree, tp_degree, return_dict): + """Build a combined mesh, run `ParallelConfig.setup`, and report the process groups each parallelism landed on.""" + try: + os.environ["MASTER_ADDR"] = "localhost" + os.environ["MASTER_PORT"] = str(master_port) + os.environ["RANK"] = str(rank) + os.environ["WORLD_SIZE"] = str(world_size) + + dist.init_process_group(backend="gloo", rank=rank, world_size=world_size) + + mesh = torch.distributed.device_mesh.init_device_mesh( + "cpu", mesh_shape=(tp_degree, 1, ulysses_degree), mesh_dim_names=("tp", "ring", "ulysses") + ) + config = ParallelConfig( + context_parallel_config=ContextParallelConfig(ulysses_degree=ulysses_degree), + tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), + ) + config.setup(rank, world_size, torch.device("cpu"), mesh=mesh) + + cp_config = config.context_parallel_config + tp_config = config.tensor_parallel_config + return_dict[rank] = { + "status": "success", + "cp_ranks": dist.get_process_group_ranks(cp_config._flattened_mesh.get_group()), + "ulysses_local_rank": cp_config._ulysses_local_rank, + "tp_ranks": dist.get_process_group_ranks(tp_config._mesh.get_group()), + "tp_local_rank": tp_config._mesh.get_local_rank(), + "tp_degree": tp_config._tp_degree, + } + except Exception as e: # noqa: BLE001 — surfaced as a test failure by the caller + return_dict[rank] = {"status": "error", "error": f"{type(e).__name__}: {e}"} + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +def _missing_tp_dim_worker(rank, world_size, master_port, return_dict): + """A combined config handed a CP-only mesh must be rejected, naming the missing 'tp' dimension.""" + try: + os.environ["MASTER_ADDR"] = "localhost" + os.environ["MASTER_PORT"] = str(master_port) + os.environ["RANK"] = str(rank) + os.environ["WORLD_SIZE"] = str(world_size) + + dist.init_process_group(backend="gloo", rank=rank, world_size=world_size) + + mesh = torch.distributed.device_mesh.init_device_mesh( + "cpu", mesh_shape=(1, world_size), mesh_dim_names=("ring", "ulysses") + ) + config = ParallelConfig( + context_parallel_config=ContextParallelConfig(ulysses_degree=world_size), + tensor_parallel_config=TensorParallelConfig(tp_degree=1), + ) + try: + config.setup(rank, world_size, torch.device("cpu"), mesh=mesh) + except ValueError as e: + return_dict[rank] = {"status": "raised", "message": str(e)} + else: + return_dict[rank] = {"status": "no_raise"} + except Exception as e: # noqa: BLE001 + return_dict[rank] = {"status": "error", "error": f"{type(e).__name__}: {e}"} + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +def _spawn(worker, world_size, *args): + if not dist.is_available(): + pytest.skip("torch.distributed is not available.") + manager = mp.Manager() + return_dict = manager.dict() + mp.spawn(worker, args=(world_size, _find_free_port(), *args, return_dict), nprocs=world_size, join=True) + return return_dict + + +class TestCombinedParallelConfig: + """`ParallelConfig` accepting both parallelisms at once, and splitting the mesh between them.""" + + def test_both_configs_are_accepted(self): + # Combining the two used to raise outright; the mesh dimension per parallelism is what makes it work. + config = ParallelConfig( + context_parallel_config=ContextParallelConfig(ulysses_degree=2), + tensor_parallel_config=TensorParallelConfig(tp_degree=2), + ) + assert config._is_combined + assert config.context_parallel_config.ulysses_degree == 2 + assert config.tensor_parallel_config.tp_degree == 2 + + def test_single_parallelism_is_not_combined(self): + assert not ParallelConfig(context_parallel_config=ContextParallelConfig(ulysses_degree=2))._is_combined + assert not ParallelConfig(tensor_parallel_config=TensorParallelConfig(tp_degree=2))._is_combined + + def test_mesh_is_factored_between_the_two(self): + """Each parallelism must end up on its own process group: TP within a CP chunk, CP across the TP groups. + + With the default `mesh_shape=(tp=2, ring=1, ulysses=2)` over four ranks, "ulysses" is the fastest-varying + dimension, so ranks {0,1} and {2,3} are the CP groups and {0,2} / {1,3} are the TP groups. A TP all-reduce + must not reach a rank holding a different sequence chunk, and a CP collective must not reach a rank holding a + different weight shard — this asserts exactly that split. + """ + world_size = 4 + results = _spawn(_mesh_factorization_worker, world_size, 2, 2) + + for rank in range(world_size): + assert results[rank]["status"] == "success", results[rank].get("error") + + assert [results[r]["tp_ranks"] for r in range(4)] == [[0, 2], [1, 3], [0, 2], [1, 3]] + assert [results[r]["cp_ranks"] for r in range(4)] == [[0, 1], [0, 1], [2, 3], [2, 3]] + assert [results[r]["ulysses_local_rank"] for r in range(4)] == [0, 1, 0, 1] + # The TP shard index is the coordinate inside the TP group, which stops tracking the global rank as soon as + # the mesh has more than one dimension. Weight sharding keys off this, so it is the value that matters. + assert [results[r]["tp_local_rank"] for r in range(4)] == [0, 0, 1, 1] + assert all(results[r]["tp_degree"] == 2 for r in range(4)) + + def test_mesh_without_tp_dimension_is_rejected(self): + world_size = 2 + results = _spawn(_missing_tp_dim_worker, world_size) + + for rank in range(world_size): + assert results[rank]["status"] == "raised", ( + f"rank {rank}: expected a ValueError for a mesh with no 'tp' dimension, got {results[rank]}" + ) + assert "tp" in results[rank]["message"] diff --git a/tests/models/testing_utils/__init__.py b/tests/models/testing_utils/__init__.py index 648c79f103fd..6db810342821 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, HybridParallelTesterMixin, @@ -67,6 +68,7 @@ "BitsAndBytesConfigMixin", "BitsAndBytesTesterMixin", "CacheTesterMixin", + "ContextAndTensorParallelTesterMixin", "ContextParallelTesterMixin", "ContextParallelAttentionBackendsTesterMixin", "HybridParallelTesterMixin", diff --git a/tests/models/testing_utils/parallelism.py b/tests/models/testing_utils/parallelism.py index d691a011d584..d7f13da16cce 100644 --- a/tests/models/testing_utils/parallelism.py +++ b/tests/models/testing_utils/parallelism.py @@ -615,6 +615,150 @@ def test_tensor_parallel_tpu_inference(self, atol=1e-3, rtol=1e-3): torch.testing.assert_close(ref_output, tp_output, atol=atol, rtol=rtol) +def _context_and_tensor_parallel_worker( + rank, world_size, master_port, model_class, init_dict, cp_dict, tp_degree, inputs_dict, return_dict, state_dict +): + """Worker for combined context + tensor parallel inference. + + Both configs go into one `ParallelConfig`, which puts them on one mesh with a dimension each. The result should + still match the single-device reference: TP is mathematically equivalent to the unsharded model, and CP splits the + sequence and gathers it back, so neither changes the function being computed. + """ + try: + os.environ["MASTER_ADDR"] = "localhost" + os.environ["MASTER_PORT"] = str(master_port) + os.environ["RANK"] = str(rank) + os.environ["WORLD_SIZE"] = str(world_size) + + device_config = DEVICE_CONFIG.get(torch_device, DEVICE_CONFIG["cuda"]) + dist.init_process_group(backend=device_config["backend"], rank=rank, world_size=world_size) + + device_config["module"].set_device(rank) + device = torch.device(f"{torch_device}:{rank}") + + model = model_class(**init_dict) + model.load_state_dict(state_dict) + model.to(device) + model.eval() + + inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} + + model.enable_parallelism( + config=ParallelConfig( + context_parallel_config=ContextParallelConfig(**cp_dict), + tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), + ) + ) + + with torch.no_grad(): + output = model(**inputs_on_device, return_dict=False)[0] + + if rank == 0: + return_dict["status"] = "success" + return_dict["output_shape"] = list(output.shape) + return_dict["output"] = output.float().cpu().tolist() + + except Exception as e: + if rank == 0: + return_dict["status"] = "error" + return_dict["error"] = f"{type(e).__name__}: {e}" + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +@is_context_parallel +@is_tensor_parallel +@require_torch_multi_accelerator +class ContextAndTensorParallelTesterMixin: + """Context and tensor parallelism enabled together, over one device mesh. + + The two are orthogonal — CP cuts the sequence, TP cuts the weights — so composing them should leave the computed + function unchanged. Both axes are covered: Ulysses, which trades sequence for heads inside attention, and ring, + which does not touch the head dimension at all. + + Needs `cp_degree` x `tp_degree` accelerators (four by default). Head-count requirements differ per CP type, so a + model whose dummy config has too few heads skips rather than failing. + """ + + cp_degree = 2 + tp_degree = 2 + + @pytest.mark.parametrize("cp_type", ["ulysses_degree", "ring_degree"], ids=["ulysses", "ring"]) + def test_context_and_tensor_parallel_inference(self, cp_type, batch_size: int = 1): + if not torch.distributed.is_available(): + pytest.skip("torch.distributed is not available.") + + if getattr(self.model_class, "_tp_plan", None) is None: + pytest.skip("Model does not define a `_tp_plan` for tensor parallel inference.") + if getattr(self.model_class, "_cp_plan", None) is None: + pytest.skip("Model does not define a `_cp_plan` for context parallel inference.") + + if cp_type == "ring_degree": + active_backend, _ = _AttentionBackendRegistry.get_active_backend() + if active_backend == AttentionBackendName.NATIVE: + pytest.skip("Ring attention is not supported with the native attention backend.") + + world_size = self.cp_degree * self.tp_degree + device_module = DEVICE_CONFIG.get(torch_device, DEVICE_CONFIG["cuda"])["module"] + if device_module.device_count() < world_size: + pytest.skip(f"Combined CP x TP needs {world_size} accelerators, found {device_module.device_count()}.") + + init_dict = self.get_init_dict() + num_heads = init_dict.get("num_attention_heads") + # TP shards the heads; Ulysses then splits what TP left on each rank, so the two multiply. Ring leaves the + # head dimension alone, so only the TP degree has to divide the head count. + required_head_multiple = self.tp_degree * (self.cp_degree if cp_type == "ulysses_degree" else 1) + if num_heads is not None and num_heads % required_head_multiple != 0: + pytest.skip( + f"`num_attention_heads` ({num_heads}) is not divisible by {required_head_multiple}, required for " + f"{cp_type.removesuffix('_degree')}={self.cp_degree} x tp_degree={self.tp_degree}." + ) + + inputs_dict = self.get_dummy_inputs(batch_size=batch_size) + + # Single-device reference, captured before anything is sharded. + model = self.model_class(**init_dict).eval().to(torch_device) + state_dict = {k: v.cpu() for k, v in model.state_dict().items()} + with torch.no_grad(): + ref_output = model(**inputs_dict, return_dict=False)[0].float().cpu() + + inputs_dict = {k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} + + manager = mp.Manager() + return_dict = manager.dict() + mp.spawn( + _context_and_tensor_parallel_worker, + args=( + world_size, + _find_free_port(), + self.model_class, + init_dict, + {cp_type: self.cp_degree}, + self.tp_degree, + inputs_dict, + return_dict, + state_dict, + ), + nprocs=world_size, + join=True, + ) + + assert return_dict.get("status") == "success", ( + f"Combined context + tensor parallel inference failed: {return_dict.get('error', 'Unknown error')}" + ) + + combined_output = torch.tensor(return_dict["output"]) + assert list(ref_output.shape) == return_dict["output_shape"] + # Two sets of collectives reorder the summation on top of the sharded matmuls, so the tolerance matches the + # TP-only test rather than the tighter CP-only one. + torch.testing.assert_close(ref_output, combined_output, atol=1e-3, rtol=1e-3) + + @pytest.mark.parametrize("cp_type", ["ulysses_degree", "ring_degree"], ids=["ulysses", "ring"]) + def test_context_and_tensor_parallel_batch_inputs(self, cp_type): + self.test_context_and_tensor_parallel_inference(cp_type, batch_size=2) + + @is_context_parallel @is_tensor_parallel @require_torch_multi_accelerator diff --git a/tests/models/transformers/test_models_transformer_qwenimage.py b/tests/models/transformers/test_models_transformer_qwenimage.py index 6210aecff87f..10d36c8155ba 100644 --- a/tests/models/transformers/test_models_transformer_qwenimage.py +++ b/tests/models/transformers/test_models_transformer_qwenimage.py @@ -30,6 +30,7 @@ AttentionTesterMixin, BaseModelTesterConfig, BitsAndBytesTesterMixin, + ContextAndTensorParallelTesterMixin, ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, LoraHotSwappingForModelTesterMixin, @@ -320,6 +321,25 @@ def test_tensor_parallel_tpu_inference(self): super().test_tensor_parallel_tpu_inference(atol=2e-2, rtol=2e-2) +class TestQwenImageTransformerContextAndTensorParallel( + QwenImageTransformerTesterConfig, ContextAndTensorParallelTesterMixin +): + """Context Parallel x Tensor Parallel inference tests for QwenImage Transformer (4 accelerators). + + QwenImage is the model this runs on because its dummy config has four attention heads, and Ulysses splits the + heads TP already sharded — so `ulysses_degree` x `tp_degree` has to divide the head count. + """ + + def get_dummy_inputs(self, batch_size: int = 1) -> dict[str, torch.Tensor]: + inputs = super().get_dummy_inputs(batch_size=batch_size) + encoder_hidden_states_mask = inputs["encoder_hidden_states_mask"] + encoder_hidden_states_mask[:, 1] = 0 + encoder_hidden_states_mask[:, 3] = 0 + encoder_hidden_states_mask[:, 5:] = 0 + inputs["encoder_hidden_states_mask"] = encoder_hidden_states_mask + return inputs + + def make_neuron_tp_spec(): """Model spec consumed by the generic Neuron TP worker (``_neuron_tp_worker.py``). From 0c7b4aa100fa5601e0c456f0995b3c8168e5abf2 Mon Sep 17 00:00:00 2001 From: whn09 Date: Thu, 22 Oct 2026 15:50:38 +0800 Subject: [PATCH 05/16] docs: combining context and tensor parallelism Co-Authored-By: Claude Opus 5.5 --- .../en/training/distributed_inference.md | 75 ++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/docs/source/en/training/distributed_inference.md b/docs/source/en/training/distributed_inference.md index 818488b4cfce..af21296024f2 100644 --- a/docs/source/en/training/distributed_inference.md +++ b/docs/source/en/training/distributed_inference.md @@ -561,6 +561,79 @@ Validate a new plan numerically rather than by eye: generate with a fixed seed o > [!TIP] > Start from an existing plan for a similar architecture. [`QwenImageTransformer2DModel`] is fully unfused and every entry is plain `"colwise"`/`"rowwise"`, [`FluxTransformer2DModel`] adds a single packed row-wise projection, and [`Flux2Transformer2DModel`] covers both packed styles — see [`transformer_qwenimage.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_qwenimage.py), [`transformer_flux.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_flux.py), and [`transformer_flux2.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_flux2.py) respectively. +## Combining context and tensor parallelism + +The two strategies split a model along different axes: tensor parallelism shards the weights, context parallelism splits the sequence. A model whose weights don't fit on one device *and* whose sequence is too long for one device's attention needs both, and neither alone can help: TP doesn't divide the sequence, and CP doesn't divide the weights. + +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 TP all-reduces and the CP all-gathers or all-to-alls each stay inside their own process group. The model must define both a `_tp_plan` and a `_cp_plan`. + +```py +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() + device = torch.device(f"cuda:{rank}") + torch.cuda.set_device(device) + + # 4 devices: each weight is sharded 2 ways, and each shard's sequence is split 2 ways with Ulysses. + transformer = Flux2Transformer2DModel.from_pretrained( + "black-forest-labs/FLUX.2-dev", + subfolder="transformer", + torch_dtype=torch.bfloat16, + parallel_config=ParallelConfig( + tensor_parallel_config=TensorParallelConfig(tp_degree=2), + context_parallel_config=ContextParallelConfig(ulysses_degree=2), + ), + ) + + pipeline = DiffusionPipeline.from_pretrained( + "black-forest-labs/FLUX.2-dev", transformer=transformer, torch_dtype=torch.bfloat16 + ) + # As with tensor parallelism alone, move the other components individually, not with `pipeline.to(device)`. + pipeline.text_encoder.to(device) + pipeline.vae.to(device) + + generator = torch.Generator().manual_seed(42) + image = pipeline(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() +``` + +```shell +torchrun --nproc-per-node 4 tp_cp_flux2.py +``` + +The degrees are checked before anything is sharded: + +- `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. Pass `ulysses_anything=True` to pad the heads instead when they don't divide. + +The default mesh puts `"tp"` outermost, so the Ulysses groups are runs of consecutive ranks. Some accelerator runtimes, AWS Neuron among them, only accept contiguous replica groups for all-to-all while tolerating strided groups for the all-reduce TP needs, and only one axis of the mesh can be contiguous. On multi-node CUDA the opposite order is usually better, since TP's per-layer all-reduce is the most bandwidth-hungry collective and wants to stay inside one NVLink domain. To choose the layout yourself, build the mesh with `"tp"`, `"ring"` and `"ulysses"` dimensions and pass it as `mesh=` on either config. + +Which degree to raise first depends on what you are short of. TP is what lowers per-device memory; CP mostly lowers latency. For example, [MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3) (a 33B audio-video DiT, 56 heads) at 1344×768 and 124 frames on one AWS Trainium2 instance (trn2.48xlarge, loaded with `from_pretrained(..., parallel_config=...)`; peak memory is measured during denoising): + +| NeuronCores | config | weights / core | peak memory / core | s / step | +|---|---|---|---|---| +| 8 | TP=8 | 7.84 GiB | 18.7 GiB | 9.33 | +| 16 | TP=4 × Ulysses=4 | 15.53 GiB | 21.7 GiB | 5.31 | +| 32 | TP=4 × Ulysses=8 | 15.53 GiB | 20.5 GiB | 3.97 | +| 32 | TP=8 × Ulysses=4 | 7.84 GiB | 13.7 GiB | 3.81 | + +At the same 32 cores, TP=8 × Ulysses=4 is both faster and lighter than TP=4 × Ulysses=8, so on this model it pays to max out TP first and add CP on top. Its 56 heads cap TP at 8, so going further means raising the CP degree. + ## Choosing a strategy The strategies above solve different problems, and the useful question is not which is fastest in the abstract but what you are running out of. @@ -577,4 +650,4 @@ Some practical guidance: - **Throughput on many prompts, model already fits.** Use data parallelism. It is the only strategy here that scales throughput linearly without touching the model, and it leaves single-prompt latency alone. - **A single component's weights don't fit.** Reach for tensor parallelism first, since it lowers both memory and latency. It communicates at every block boundary, so it wants a fast interconnect like NVLink; over PCIe that 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. - **Activations, not weights, are the problem.** This is the long-sequence regime — large images, many frames — and context parallelism is the direct answer. Pick a backend from the [Ulysses/Ring benchmarks](#ulysses-attention) above. -- **Both weights and sequence are too large.** Combine tensor and context parallelism. [`TensorParallelConfig`] accepts a `mesh` argument so both can share one device mesh. This combination is not yet validated, so treat it as experimental. +- **Both weights and sequence are too large.** [Combine tensor and context parallelism](#combining-context-and-tensor-parallelism) in one [`ParallelConfig`], raising `tp_degree` until the weights fit and adding context parallelism on top for latency. From 146e89104e12db587399670d1cefaea402e30402 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Mon, 23 Nov 2026 13:46:09 +0000 Subject: [PATCH 06/16] Document and test TP+CP loading via from_pretrained; fix distributed inference snippet --- .../en/training/distributed_inference.md | 18 +++++--- src/diffusers/models/_modeling_parallel.py | 12 ++--- tests/models/testing_utils/parallelism.py | 46 +++++++++++++------ 3 files changed, 51 insertions(+), 25 deletions(-) diff --git a/docs/source/en/training/distributed_inference.md b/docs/source/en/training/distributed_inference.md index 0854e964c2ed..2e698d50015b 100644 --- a/docs/source/en/training/distributed_inference.md +++ b/docs/source/en/training/distributed_inference.md @@ -43,6 +43,7 @@ The two strategies split a model along different axes: tensor parallelism shards 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 TP all-reduces and the CP all-gathers or all-to-alls each stay inside their own process group. The model must define both a `_tp_plan` and a `_cp_plan`. ```py +import os import torch from torch import distributed as dist from diffusers import ( @@ -56,22 +57,23 @@ from diffusers import ( def main(): dist.init_process_group(backend="nccl") rank = dist.get_rank() - device = torch.device(f"cuda:{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) - # 4 devices: each weight is sharded 2 ways, and each shard's sequence is split 2 ways with Ulysses. + # 8 devices: 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", - torch_dtype=torch.bfloat16, + dtype=torch.bfloat16, parallel_config=ParallelConfig( - tensor_parallel_config=TensorParallelConfig(tp_degree=2), + tensor_parallel_config=TensorParallelConfig(tp_degree=4), context_parallel_config=ContextParallelConfig(ulysses_degree=2), ), ) pipeline = DiffusionPipeline.from_pretrained( - "black-forest-labs/FLUX.2-dev", transformer=transformer, torch_dtype=torch.bfloat16 + "black-forest-labs/FLUX.2-dev", transformer=transformer, dtype=torch.bfloat16 ) # As with tensor parallelism alone, move the other components individually, not with `pipeline.to(device)`. pipeline.text_encoder.to(device) @@ -87,10 +89,14 @@ if __name__ == "__main__": main() ``` +Save the script as `tp_cp_flux2.py` and launch it with `torchrun`. + ```shell -torchrun --nproc-per-node 4 tp_cp_flux2.py +torchrun --nproc-per-node 8 tp_cp_flux2.py ``` +Only the transformer is sharded. Each rank holds a full copy of the text encoder, so each GPU needs enough memory for the text encoder plus its share of the transformer. + The degrees are checked before anything is sharded: - `tp_degree` × `ring_degree` × `ulysses_degree` must not exceed the world size. diff --git a/src/diffusers/models/_modeling_parallel.py b/src/diffusers/models/_modeling_parallel.py index cb49d24fb4ed..e87f72276077 100644 --- a/src/diffusers/models/_modeling_parallel.py +++ b/src/diffusers/models/_modeling_parallel.py @@ -201,10 +201,10 @@ class ParallelConfig: Configuration for applying different parallelisms. Both may be set at once. The two are then applied over one device mesh with a dimension each — `("tp", "ring", - "ulysses")`, built by `enable_parallelism` — so their collectives stay in separate process groups. This is what - lets a model too large for one device (TP shards the weights) also run a sequence too long for one device's - attention scratchpad (CP splits the sequence): TP alone cannot divide the sequence, and CP alone cannot divide the - weights. + "ulysses")`, built by `enable_parallelism` or `from_pretrained(..., parallel_config=...)` — so their collectives + stay in separate process groups. This is what lets a model too large for one device (TP shards the weights) also + run a sequence too long for one device's attention scratchpad (CP splits the sequence): TP alone cannot divide the + sequence, and CP alone cannot divide the weights. Args: context_parallel_config (`ContextParallelConfig`, *optional*): @@ -259,8 +259,8 @@ def setup( 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}). `enable_parallelism` builds this mesh from `ring_degree`/`ulysses_degree`/" - f"`tp_degree`; if you build it yourself, set `mesh=` on one of the two configs." + f"{dim_names}). `enable_parallelism` and `from_pretrained` build this mesh from `ring_degree`/" + f"`ulysses_degree`/`tp_degree`; if you build it yourself, set `mesh=` on one of the two configs." ) # `ContextParallelConfig.setup` slices ("ring", "ulysses") off whatever mesh it is handed, so it takes # the full mesh. TP instead needs its own 1-D submesh: `parallelize_module` shards a weight over every diff --git a/tests/models/testing_utils/parallelism.py b/tests/models/testing_utils/parallelism.py index 89be99f5552f..562b7b9b23a2 100644 --- a/tests/models/testing_utils/parallelism.py +++ b/tests/models/testing_utils/parallelism.py @@ -931,13 +931,25 @@ def test_tensor_parallel_tpu_rng_sync(self, tmp_path, parallelism, loading, atol def _context_and_tensor_parallel_worker( - rank, world_size, master_port, model_class, init_dict, cp_dict, tp_degree, inputs_dict, return_dict, state_dict + rank, + world_size, + master_port, + model_class, + init_dict, + cp_dict, + tp_degree, + inputs_dict, + return_dict, + state_dict, + checkpoint_dir=None, ): """Worker for combined context + tensor parallel inference. Both configs go into one `ParallelConfig`, which puts them on one mesh with a dimension each. The result should still match the single-device reference: TP is mathematically equivalent to the unsharded model, and CP splits the sequence and gathers it back, so neither changes the function being computed. + + With `checkpoint_dir`, the model is loaded with `from_pretrained(..., parallel_config=...)` instead. """ try: os.environ["MASTER_ADDR"] = "localhost" @@ -951,20 +963,21 @@ def _context_and_tensor_parallel_worker( device_config["module"].set_device(rank) device = torch.device(f"{torch_device}:{rank}") - model = model_class(**init_dict) - model.load_state_dict(state_dict) - model.to(device) - model.eval() + config = ParallelConfig( + context_parallel_config=ContextParallelConfig(**cp_dict), + tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), + ) + if checkpoint_dir is not None: + model = model_class.from_pretrained(checkpoint_dir, parallel_config=config).eval() + else: + model = model_class(**init_dict) + model.load_state_dict(state_dict) + model.to(device) + model.eval() + model.enable_parallelism(config=config) inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} - model.enable_parallelism( - config=ParallelConfig( - context_parallel_config=ContextParallelConfig(**cp_dict), - tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), - ) - ) - with torch.no_grad(): output = model(**inputs_on_device, return_dict=False)[0] @@ -1000,7 +1013,7 @@ class ContextAndTensorParallelTesterMixin: tp_degree = 2 @pytest.mark.parametrize("cp_type", ["ulysses_degree", "ring_degree"], ids=["ulysses", "ring"]) - def test_context_and_tensor_parallel_inference(self, cp_type, batch_size: int = 1): + def test_context_and_tensor_parallel_inference(self, cp_type, batch_size: int = 1, checkpoint_dir=None): if not torch.distributed.is_available(): pytest.skip("torch.distributed is not available.") @@ -1037,6 +1050,8 @@ def test_context_and_tensor_parallel_inference(self, cp_type, batch_size: int = state_dict = {k: v.cpu() for k, v in model.state_dict().items()} with torch.no_grad(): ref_output = model(**inputs_dict, return_dict=False)[0].float().cpu() + if checkpoint_dir is not None: + model.save_pretrained(checkpoint_dir) inputs_dict = {k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} @@ -1054,6 +1069,7 @@ def test_context_and_tensor_parallel_inference(self, cp_type, batch_size: int = inputs_dict, return_dict, state_dict, + checkpoint_dir, ), nprocs=world_size, join=True, @@ -1073,6 +1089,10 @@ def test_context_and_tensor_parallel_inference(self, cp_type, batch_size: int = def test_context_and_tensor_parallel_batch_inputs(self, cp_type): self.test_context_and_tensor_parallel_inference(cp_type, batch_size=2) + @pytest.mark.parametrize("cp_type", ["ulysses_degree", "ring_degree"], ids=["ulysses", "ring"]) + def test_context_and_tensor_parallel_from_pretrained(self, cp_type, tmp_path): + self.test_context_and_tensor_parallel_inference(cp_type, checkpoint_dir=str(tmp_path / "checkpoint")) + @is_context_parallel @is_tensor_parallel From 09ecf62d0d2c5390038933377ec8e1b7950945b9 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Mon, 23 Nov 2026 17:28:57 +0000 Subject: [PATCH 07/16] Refactor TP+CP tests to share coverage across CUDA, TPU, and Neuron --- src/diffusers/hooks/context_parallel.py | 3 +- src/diffusers/models/_modeling_parallel.py | 18 +- src/diffusers/models/modeling_utils.py | 27 +- tests/models/test_parallelism_combined.py | 161 ++----- tests/models/testing_utils/__init__.py | 2 - tests/models/testing_utils/parallelism.py | 393 ++++++------------ .../transformers/_neuron_hybrid_worker.py | 125 ------ .../_neuron_sharded_load_worker.py | 170 -------- .../test_models_transformer_flux.py | 87 +--- .../test_models_transformer_qwenimage.py | 19 +- 10 files changed, 171 insertions(+), 834 deletions(-) delete mode 100644 tests/models/transformers/_neuron_hybrid_worker.py delete mode 100644 tests/models/transformers/_neuron_sharded_load_worker.py diff --git a/src/diffusers/hooks/context_parallel.py b/src/diffusers/hooks/context_parallel.py index 7327d0f31e7c..e59c035d3e41 100644 --- a/src/diffusers/hooks/context_parallel.py +++ b/src/diffusers/hooks/context_parallel.py @@ -364,8 +364,7 @@ def _all_gather_anything(tensor: torch.Tensor, dim: int, group: dist.device_mesh max_dim = max(gather_dims) if any(d != max_dim for d in gather_dims) and tensor.device.type in ("neuron", "tpu"): - # Neuron and TPU all-gathers require every rank to send the same size, so pad each chunk to the longest one, - # gather, and trim each chunk back to its real length. + # 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) diff --git a/src/diffusers/models/_modeling_parallel.py b/src/diffusers/models/_modeling_parallel.py index e87f72276077..59ba46449e83 100644 --- a/src/diffusers/models/_modeling_parallel.py +++ b/src/diffusers/models/_modeling_parallel.py @@ -198,13 +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 may be set at once. The two are then applied over one device mesh with a dimension each — `("tp", "ring", - "ulysses")`, built by `enable_parallelism` or `from_pretrained(..., parallel_config=...)` — so their collectives - stay in separate process groups. This is what lets a model too large for one device (TP shards the weights) also - run a sequence too long for one device's attention scratchpad (CP splits the sequence): TP alone cannot divide the - sequence, and CP alone cannot divide the weights. + 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*): @@ -246,11 +241,6 @@ def setup( self._device = device self._mesh = mesh - # Context and tensor parallelism compose because they cut the model along different axes: CP splits the - # sequence (and, under Ulysses, trades sequence for heads inside attention) while TP shards the Linear - # weights. Composing them means giving each its own mesh *dimension*, so that every collective one issues - # stays inside its own process group: TP's all-reduce must not reach a rank holding a different sequence - # chunk, and CP's sequence all-gather must not reach a rank holding a different weight shard. cp_mesh = tp_mesh = mesh if self._is_combined: dim_names = mesh.mesh_dim_names if mesh is not None else None @@ -262,9 +252,7 @@ def setup( f"{dim_names}). `enable_parallelism` and `from_pretrained` build this mesh from `ring_degree`/" f"`ulysses_degree`/`tp_degree`; if you build it yourself, set `mesh=` on one of the two configs." ) - # `ContextParallelConfig.setup` slices ("ring", "ulysses") off whatever mesh it is handed, so it takes - # the full mesh. TP instead needs its own 1-D submesh: `parallelize_module` shards a weight over every - # rank of the mesh it is given, so handing it the 3-D mesh would shard over the CP ranks as well. + # CP selects its axes in setup. TP takes a one-dimensional submesh. tp_mesh = mesh["tp"] if self.context_parallel_config is not None: diff --git a/src/diffusers/models/modeling_utils.py b/src/diffusers/models/modeling_utils.py index 4f0f3c061f04..5ab8e90109fb 100644 --- a/src/diffusers/models/modeling_utils.py +++ b/src/diffusers/models/modeling_utils.py @@ -1539,8 +1539,7 @@ 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) - # A config that also asks for context parallelism gets its hooks here, in the same order as - # `enable_parallelism`, which is no longer callable now that the weights are sharded. + # 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: @@ -1707,15 +1706,7 @@ def _resolve_parallel_config( mesh = None cp_config, tp_config = config.context_parallel_config, config.tensor_parallel_config if cp_config is not None and tp_config is not None: - # A single mesh spanning both parallelisms, with the context parallel dimensions varying fastest: a - # CP group is then a contiguous run of ranks and a TP group takes one rank out of each run. - # - # That order is a default, not a universal optimum. Some accelerator runtimes only accept contiguous - # replica groups for all-to-all -- which Ulysses needs -- while tolerating strided groups for - # all-reduce, which is all TP needs; since only one axis of a 2-D mesh can be contiguous, Ulysses - # gets it. On multi-node CUDA the opposite order is usually preferable, because TP is the most - # bandwidth-hungry collective and wants to stay within one NVLink domain. Pass `mesh=` on either - # config to choose the layout yourself. + # Keep Ulysses ranks contiguous for backends that require it for all-to-all. mesh = ( cp_config.mesh or tp_config.mesh @@ -1741,9 +1732,7 @@ 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 the combination up front — after `setup`, which resolves `_tp_degree` from the mesh, but before - # anything is recorded on the model or applied to it. CP hooks are applied before TP, so a check left to the - # TP branch would raise on a model already carrying CP hooks: half-parallelised, and not usable. + # 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 requested = cp_config.ring_degree * cp_config.ulysses_degree * tp_degree @@ -1756,8 +1745,7 @@ def _resolve_parallel_config( 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 trades sequence for heads inside attention (`SeqAllToAllDim` scatters over dim 2), and it - # only ever sees the heads TP left on this rank, so the count has to survive both splits. + # 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 " @@ -1827,12 +1815,7 @@ def _apply_context_parallel( config: ParallelConfig, cp_plan: dict[str, ContextParallelModelPlan] | None = None, ): - """Install the context-parallel hooks `config` asks for, if any, and hand it to the attention processors. - - Split out of `enable_parallelism` for the same reason as `_resolve_parallel_config`: `from_pretrained(..., - parallel_config=...)` shards the weights while reading them, so it cannot call `enable_parallelism` - afterwards, yet it still has to apply these hooks when the config asks for context parallelism. - """ + """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 diff --git a/tests/models/test_parallelism_combined.py b/tests/models/test_parallelism_combined.py index 4a404a06125e..0ee741980d66 100644 --- a/tests/models/test_parallelism_combined.py +++ b/tests/models/test_parallelism_combined.py @@ -13,16 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Tests for combining context parallelism with tensor parallelism on one device mesh. - -These cover the wiring rather than the numerics: that `ParallelConfig` hands each parallelism its own submesh, and -that the resulting process groups are the intended factorisation of the world. They run on CPU over `gloo`, so they -need no accelerator — `gloo` has no `all_to_all`, so an end-to-end Ulysses forward pass cannot run here; that is -covered by `ContextAndTensorParallelTesterMixin` in `testing_utils/parallelism.py`, which needs four accelerators. -""" - -import os -import socket +from datetime import timedelta import pytest import torch @@ -32,133 +23,39 @@ from diffusers.models._modeling_parallel import ContextParallelConfig, ParallelConfig, TensorParallelConfig -def _find_free_port(): - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - s.bind(("", 0)) - s.listen(1) - return s.getsockname()[1] - - -def _mesh_factorization_worker(rank, world_size, master_port, ulysses_degree, tp_degree, return_dict): - """Build a combined mesh, run `ParallelConfig.setup`, and report the process groups each parallelism landed on.""" +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: - os.environ["MASTER_ADDR"] = "localhost" - os.environ["MASTER_PORT"] = str(master_port) - os.environ["RANK"] = str(rank) - os.environ["WORLD_SIZE"] = str(world_size) - - dist.init_process_group(backend="gloo", rank=rank, world_size=world_size) - - mesh = torch.distributed.device_mesh.init_device_mesh( - "cpu", mesh_shape=(tp_degree, 1, ulysses_degree), mesh_dim_names=("tp", "ring", "ulysses") - ) - config = ParallelConfig( - context_parallel_config=ContextParallelConfig(ulysses_degree=ulysses_degree), - tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), - ) - config.setup(rank, world_size, torch.device("cpu"), mesh=mesh) - - cp_config = config.context_parallel_config - tp_config = config.tensor_parallel_config - return_dict[rank] = { - "status": "success", - "cp_ranks": dist.get_process_group_ranks(cp_config._flattened_mesh.get_group()), - "ulysses_local_rank": cp_config._ulysses_local_rank, - "tp_ranks": dist.get_process_group_ranks(tp_config._mesh.get_group()), - "tp_local_rank": tp_config._mesh.get_local_rank(), - "tp_degree": tp_config._tp_degree, - } - except Exception as e: # noqa: BLE001 — surfaced as a test failure by the caller - return_dict[rank] = {"status": "error", "error": f"{type(e).__name__}: {e}"} - finally: - if dist.is_initialized(): - dist.destroy_process_group() - - -def _missing_tp_dim_worker(rank, world_size, master_port, return_dict): - """A combined config handed a CP-only mesh must be rejected, naming the missing 'tp' dimension.""" - try: - os.environ["MASTER_ADDR"] = "localhost" - os.environ["MASTER_PORT"] = str(master_port) - os.environ["RANK"] = str(rank) - os.environ["WORLD_SIZE"] = str(world_size) - - dist.init_process_group(backend="gloo", rank=rank, world_size=world_size) - - mesh = torch.distributed.device_mesh.init_device_mesh( - "cpu", mesh_shape=(1, world_size), mesh_dim_names=("ring", "ulysses") - ) - config = ParallelConfig( - context_parallel_config=ContextParallelConfig(ulysses_degree=world_size), - tensor_parallel_config=TensorParallelConfig(tp_degree=1), - ) - try: - config.setup(rank, world_size, torch.device("cpu"), mesh=mesh) - except ValueError as e: - return_dict[rank] = {"status": "raised", "message": str(e)} - else: - return_dict[rank] = {"status": "no_raise"} - except Exception as e: # noqa: BLE001 - return_dict[rank] = {"status": "error", "error": f"{type(e).__name__}: {e}"} - finally: - if dist.is_initialized(): - dist.destroy_process_group() - - -def _spawn(worker, world_size, *args): - if not dist.is_available(): - pytest.skip("torch.distributed is not available.") - manager = mp.Manager() - return_dict = manager.dict() - mp.spawn(worker, args=(world_size, _find_free_port(), *args, return_dict), nprocs=world_size, join=True) - return return_dict - - -class TestCombinedParallelConfig: - """`ParallelConfig` accepting both parallelisms at once, and splitting the mesh between them.""" - - def test_both_configs_are_accepted(self): - # Combining the two used to raise outright; the mesh dimension per parallelism is what makes it work. + 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) config = ParallelConfig( context_parallel_config=ContextParallelConfig(ulysses_degree=2), tensor_parallel_config=TensorParallelConfig(tp_degree=2), ) - assert config._is_combined - assert config.context_parallel_config.ulysses_degree == 2 - assert config.tensor_parallel_config.tp_degree == 2 - - def test_single_parallelism_is_not_combined(self): - assert not ParallelConfig(context_parallel_config=ContextParallelConfig(ulysses_degree=2))._is_combined - assert not ParallelConfig(tensor_parallel_config=TensorParallelConfig(tp_degree=2))._is_combined - - def test_mesh_is_factored_between_the_two(self): - """Each parallelism must end up on its own process group: TP within a CP chunk, CP across the TP groups. - - With the default `mesh_shape=(tp=2, ring=1, ulysses=2)` over four ranks, "ulysses" is the fastest-varying - dimension, so ranks {0,1} and {2,3} are the CP groups and {0,2} / {1,3} are the TP groups. A TP all-reduce - must not reach a rank holding a different sequence chunk, and a CP collective must not reach a rank holding a - different weight shard — this asserts exactly that split. - """ - world_size = 4 - results = _spawn(_mesh_factorization_worker, world_size, 2, 2) + if not include_tp: + with pytest.raises(ValueError, match=r"\['tp'\].*missing"): + config.setup(rank, world_size, torch.device("cpu"), mesh=mesh) + return - for rank in range(world_size): - assert results[rank]["status"] == "success", results[rank].get("error") - - assert [results[r]["tp_ranks"] for r in range(4)] == [[0, 2], [1, 3], [0, 2], [1, 3]] - assert [results[r]["cp_ranks"] for r in range(4)] == [[0, 1], [0, 1], [2, 3], [2, 3]] - assert [results[r]["ulysses_local_rank"] for r in range(4)] == [0, 1, 0, 1] - # The TP shard index is the coordinate inside the TP group, which stops tracking the global rank as soon as - # the mesh has more than one dimension. Weight sharding keys off this, so it is the value that matters. - assert [results[r]["tp_local_rank"] for r in range(4)] == [0, 0, 1, 1] - assert all(results[r]["tp_degree"] == 2 for r in range(4)) + 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() - def test_mesh_without_tp_dimension_is_rejected(self): - world_size = 2 - results = _spawn(_missing_tp_dim_worker, world_size) - for rank in range(world_size): - assert results[rank]["status"] == "raised", ( - f"rank {rank}: expected a ValueError for a mesh with no 'tp' dimension, got {results[rank]}" - ) - assert "tp" in results[rank]["message"] +@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 6a26de7c27c8..4f8b672d33d9 100644 --- a/tests/models/testing_utils/__init__.py +++ b/tests/models/testing_utils/__init__.py @@ -24,7 +24,6 @@ ContextAndTensorParallelTesterMixin, ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, - HybridParallelTesterMixin, TensorParallelNeuronTesterMixin, TensorParallelTesterMixin, TensorParallelTPUTesterMixin, @@ -78,7 +77,6 @@ "ContextAndTensorParallelTesterMixin", "ContextParallelTesterMixin", "ContextParallelAttentionBackendsTesterMixin", - "HybridParallelTesterMixin", "TensorParallelTesterMixin", "TensorParallelNeuronTesterMixin", "TensorParallelTPUTesterMixin", diff --git a/tests/models/testing_utils/parallelism.py b/tests/models/testing_utils/parallelism.py index 562b7b9b23a2..0aea912d12d6 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 @@ -31,7 +33,7 @@ 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 @@ -464,63 +466,6 @@ def _tensor_parallel_from_pretrained_worker( dist.destroy_process_group() -def _hybrid_parallel_worker( - rank, world_size, master_port, model_class, init_dict, cp_dict, tp_degree, inputs_dict, return_dict, state_dict -): - """Worker function for combined tensor + context parallel inference testing. - - Both parallelisms are requested through a single `ParallelConfig`, which shares one device mesh between them, so - each rank holds `1 / tp_degree` of every sharded weight *and* `1 / (ring_degree * ulysses_degree)` of the - sequence. Rank 0 reports its output so the caller can compare it against a single-device reference: the - composition is mathematically equivalent to the unsharded model up to floating-point reduction order. - """ - try: - os.environ["MASTER_ADDR"] = "localhost" - os.environ["MASTER_PORT"] = str(master_port) - os.environ["RANK"] = str(rank) - os.environ["WORLD_SIZE"] = str(world_size) - - device_config = DEVICE_CONFIG.get(torch_device, DEVICE_CONFIG["cuda"]) - backend = device_config["backend"] - device_module = device_config["module"] - - dist.init_process_group(backend=backend, rank=rank, world_size=world_size) - - device_module.set_device(rank) - device = torch.device(f"{torch_device}:{rank}") - - model = model_class(**init_dict) - model.load_state_dict(state_dict) - model.to(device) - model.eval() - - inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} - - model.enable_parallelism( - config=ParallelConfig( - tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), - context_parallel_config=ContextParallelConfig(**cp_dict), - ) - ) - - with torch.no_grad(): - output = model(**inputs_on_device, return_dict=False)[0] - - if rank == 0: - return_dict["status"] = "success" - return_dict["output_shape"] = list(output.shape) - # Serialise via nested list so the manager dict can transport it across processes. - return_dict["output"] = output.float().cpu().tolist() - - except Exception as e: - if rank == 0: - return_dict["status"] = "error" - return_dict["error"] = str(e) - finally: - if dist.is_initialized(): - dist.destroy_process_group() - - def _parallel_rng_sync_worker( rank, world_size, @@ -931,239 +876,143 @@ def test_tensor_parallel_tpu_rng_sync(self, tmp_path, parallelism, loading, atol def _context_and_tensor_parallel_worker( - rank, - world_size, - master_port, - model_class, - init_dict, - cp_dict, - tp_degree, - inputs_dict, - return_dict, - state_dict, - checkpoint_dir=None, + rank, world_size, master_port, device_type, model_class, checkpoint, inputs, reference, config, loading ): - """Worker for combined context + tensor parallel inference. - - Both configs go into one `ParallelConfig`, which puts them on one mesh with a dimension each. The result should - still match the single-device reference: TP is mathematically equivalent to the unsharded model, and CP splits the - sequence and gathers it back, so neither changes the function being computed. + 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) - With `checkpoint_dir`, the model is loaded with `from_pretrained(..., parallel_config=...)` instead. - """ + dist.init_process_group(backend=DEVICE_CONFIG[device_type]["backend"], timeout=timedelta(minutes=3)) try: - os.environ["MASTER_ADDR"] = "localhost" - os.environ["MASTER_PORT"] = str(master_port) - os.environ["RANK"] = str(rank) - os.environ["WORLD_SIZE"] = str(world_size) - - device_config = DEVICE_CONFIG.get(torch_device, DEVICE_CONFIG["cuda"]) - dist.init_process_group(backend=device_config["backend"], rank=rank, world_size=world_size) - - device_config["module"].set_device(rank) - device = torch.device(f"{torch_device}:{rank}") - - config = ParallelConfig( - context_parallel_config=ContextParallelConfig(**cp_dict), - tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), - ) - if checkpoint_dir is not None: - model = model_class.from_pretrained(checkpoint_dir, parallel_config=config).eval() + if device_type == "tpu": + device = torch.device("tpu") + torch.set_float32_matmul_precision("highest") + elif device_type == "neuron": + device = torch.neuron.current_device() else: - model = model_class(**init_dict) - model.load_state_dict(state_dict) - model.to(device) - model.eval() - model.enable_parallelism(config=config) - - inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} + 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(**inputs_on_device, return_dict=False)[0] - - if rank == 0: - return_dict["status"] = "success" - return_dict["output_shape"] = list(output.shape) - return_dict["output"] = output.float().cpu().tolist() - - except Exception as e: - if rank == 0: - return_dict["status"] = "error" - return_dict["error"] = f"{type(e).__name__}: {e}" + output = model(**device_inputs, return_dict=False)[0] + tolerance = 2e-2 if device_type in ("tpu", "neuron") else 1e-3 + torch.testing.assert_close(output.float().cpu(), reference, atol=tolerance, rtol=tolerance) finally: - if dist.is_initialized(): - dist.destroy_process_group() + dist.destroy_process_group() @is_context_parallel @is_tensor_parallel -@require_torch_multi_accelerator class ContextAndTensorParallelTesterMixin: - """Context and tensor parallelism enabled together, over one device mesh. - - The two are orthogonal — CP cuts the sequence, TP cuts the weights — so composing them should leave the computed - function unchanged. Both axes are covered: Ulysses, which trades sequence for heads inside attention, and ring, - which does not touch the head dimension at all. - - Needs `cp_degree` x `tp_degree` accelerators (four by default). Head-count requirements differ per CP type, so a - model whose dummy config has too few heads skips rather than failing. - """ + """Run TPU and Neuron cases in a fresh pytest process so workers can acquire their devices.""" - cp_degree = 2 - tp_degree = 2 - - @pytest.mark.parametrize("cp_type", ["ulysses_degree", "ring_degree"], ids=["ulysses", "ring"]) - def test_context_and_tensor_parallel_inference(self, cp_type, batch_size: int = 1, checkpoint_dir=None): - if not torch.distributed.is_available(): - pytest.skip("torch.distributed is not available.") - - if getattr(self.model_class, "_tp_plan", None) is None: - pytest.skip("Model does not define a `_tp_plan` for tensor parallel inference.") - if getattr(self.model_class, "_cp_plan", None) is None: - pytest.skip("Model does not define a `_cp_plan` for context parallel inference.") - - if cp_type == "ring_degree": - active_backend, _ = _AttentionBackendRegistry.get_active_backend() - if active_backend == AttentionBackendName.NATIVE: - pytest.skip("Ring attention is not supported with the native attention backend.") - - world_size = self.cp_degree * self.tp_degree - device_module = DEVICE_CONFIG.get(torch_device, DEVICE_CONFIG["cuda"])["module"] - if device_module.device_count() < world_size: - pytest.skip(f"Combined CP x TP needs {world_size} accelerators, found {device_module.device_count()}.") - - init_dict = self.get_init_dict() - num_heads = init_dict.get("num_attention_heads") - # TP shards the heads; Ulysses then splits what TP left on each rank, so the two multiply. Ring leaves the - # head dimension alone, so only the TP degree has to divide the head count. - required_head_multiple = self.tp_degree * (self.cp_degree if cp_type == "ulysses_degree" else 1) - if num_heads is not None and num_heads % required_head_multiple != 0: - pytest.skip( - f"`num_attention_heads` ({num_heads}) is not divisible by {required_head_multiple}, required for " - f"{cp_type.removesuffix('_degree')}={self.cp_degree} x tp_degree={self.tp_degree}." - ) - - inputs_dict = self.get_dummy_inputs(batch_size=batch_size) - - # Single-device reference, captured before anything is sharded. - model = self.model_class(**init_dict).eval().to(torch_device) - state_dict = {k: v.cpu() for k, v in model.state_dict().items()} - with torch.no_grad(): - ref_output = model(**inputs_dict, return_dict=False)[0].float().cpu() - if checkpoint_dir is not None: - model.save_pretrained(checkpoint_dir) - - inputs_dict = {k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} - - manager = mp.Manager() - return_dict = manager.dict() - mp.spawn( - _context_and_tensor_parallel_worker, - args=( - world_size, - _find_free_port(), - self.model_class, - init_dict, - {cp_type: self.cp_degree}, - self.tp_degree, - inputs_dict, - return_dict, - state_dict, - checkpoint_dir, - ), - nprocs=world_size, - join=True, - ) - - assert return_dict.get("status") == "success", ( - f"Combined context + tensor parallel inference failed: {return_dict.get('error', 'Unknown error')}" - ) - - combined_output = torch.tensor(return_dict["output"]) - assert list(ref_output.shape) == return_dict["output_shape"] - # Two sets of collectives reorder the summation on top of the sharded matmuls, so the tolerance matches the - # TP-only test rather than the tighter CP-only one. - torch.testing.assert_close(ref_output, combined_output, atol=1e-3, rtol=1e-3) - - @pytest.mark.parametrize("cp_type", ["ulysses_degree", "ring_degree"], ids=["ulysses", "ring"]) - def test_context_and_tensor_parallel_batch_inputs(self, cp_type): - self.test_context_and_tensor_parallel_inference(cp_type, batch_size=2) - - @pytest.mark.parametrize("cp_type", ["ulysses_degree", "ring_degree"], ids=["ulysses", "ring"]) - def test_context_and_tensor_parallel_from_pretrained(self, cp_type, tmp_path): - self.test_context_and_tensor_parallel_inference(cp_type, checkpoint_dir=str(tmp_path / "checkpoint")) - - -@is_context_parallel -@is_tensor_parallel -@require_torch_multi_accelerator -class HybridParallelTesterMixin: - """Tensor parallelism and context parallelism together, from one `ParallelConfig`. - - Needs `tp_degree * ulysses_degree` accelerators (4 at the degrees used here), so it skips on a 2-device runner. - """ - - def test_hybrid_parallel_inference(self, batch_size: int = 1): - if not torch.distributed.is_available(): + @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 getattr(self.model_class, plan, None) is None: - pytest.skip(f"Model does not define a `{plan}`, which hybrid parallelism requires.") - - tp_degree, ulysses_degree = 2, 2 - world_size = tp_degree * ulysses_degree - device_count = DEVICE_CONFIG.get(torch_device, DEVICE_CONFIG["cuda"])["module"].device_count() + 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"tp_degree={tp_degree} x ulysses_degree={ulysses_degree} needs {world_size} accelerators, " - f"found {device_count}." - ) + pytest.skip(f"Needs {world_size} {device_type} devices, found {device_count}.") init_dict = self.get_init_dict() - num_heads = init_dict.get("num_attention_heads") - # Each rank keeps `num_heads // tp_degree` heads, which Ulysses splits again. - if num_heads is not None and num_heads % world_size != 0: - pytest.skip(f"`num_attention_heads` ({num_heads}) is not divisible by {world_size}.") - - inputs_dict = self.get_dummy_inputs(batch_size=batch_size) - - # Single-device reference - model = self.model_class(**init_dict).eval().to(torch_device) - state_dict = {k: v.cpu() for k, v in model.state_dict().items()} - with torch.no_grad(): - ref_output = model(**inputs_dict, return_dict=False)[0].float().cpu() - - inputs_dict = {k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items()} - - master_port = _find_free_port() - manager = mp.Manager() - return_dict = manager.dict() - - mp.spawn( - _hybrid_parallel_worker, - args=( - world_size, - master_port, - self.model_class, - init_dict, - {"ulysses_degree": ulysses_degree}, - tp_degree, - inputs_dict, - return_dict, - state_dict, - ), - nprocs=world_size, - join=True, - ) - - assert return_dict.get("status") == "success", ( - f"Hybrid parallel inference failed: {return_dict.get('error', 'Unknown error')}" + 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 = model(**inputs, return_dict=False)[0].float() + + 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), ) - - output = torch.tensor(return_dict["output"]) - # Sharded matmuls plus the Ulysses all-to-all reorder the summation, hence the tolerance. - torch.testing.assert_close(ref_output, output, atol=1e-3, rtol=1e-3) + 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 diff --git a/tests/models/transformers/_neuron_hybrid_worker.py b/tests/models/transformers/_neuron_hybrid_worker.py deleted file mode 100644 index 640aada1a764..000000000000 --- a/tests/models/transformers/_neuron_hybrid_worker.py +++ /dev/null @@ -1,125 +0,0 @@ -# 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. - -"""Generic torchrun worker: assert a model's Neuron tensor-parallel x context-parallel output matches its reference. - -Covers the two parallelisms composed in a single `ParallelConfig`. The model under test is supplied as a -`module:function` spec reference on the command line, and the referenced factory returns -`(model_class, init_dict, inputs)` with CPU tensors. - - torchrun --nproc_per_node=8 _neuron_hybrid_worker.py \\ - tests.models.transformers.test_models_transformer_flux:make_neuron_hybrid_spec - -`tp_degree` and `ulysses_degree` are read from `TP_DEGREE` / `ULYSSES_DEGREE` (defaults 2 and 4, whose product is -the launched world size). `ulysses_degree` cannot be 2 on Neuron: its all-to-all only accepts group sizes of 4, 8, -16 or multiples of 32. - -No mesh is passed, so this also exercises the default mesh layout that `enable_parallelism` builds for the combined -case -- which matters on Neuron, where the all-to-all Ulysses depends on rejects strided replica groups and so the -context-parallel dimensions have to vary fastest. - -Exit code 0 means the composed path is numerically equivalent to the unsharded model; non-zero means failure. -""" - -import argparse -import importlib -import os -import sys -import traceback - - -# Make the in-repo `diffusers` and `tests` packages importable when run via torchrun from an arbitrary CWD. -sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "src")) -sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..")) - -import torch -import torch.distributed as dist -import torch_neuronx # noqa: F401 — registers torch.neuron - -from diffusers import ContextParallelConfig, ParallelConfig, TensorParallelConfig - - -def main(): - parser = argparse.ArgumentParser(description="Neuron tensor-parallel x context-parallel correctness worker.") - parser.add_argument( - "spec", - help="`module:function` reference returning (model_class, init_dict, cpu_inputs) for the model under test.", - ) - args = parser.parse_args() - module_name, _, fn_name = args.spec.partition(":") - model_class, init_dict, inputs = getattr(importlib.import_module(module_name), fn_name)() - - tp_degree = int(os.environ.get("TP_DEGREE", "2")) - ulysses_degree = int(os.environ.get("ULYSSES_DEGREE", "4")) - - dist.init_process_group(backend="neuron") - rank = dist.get_rank() - world_size = dist.get_world_size() - device = torch.neuron.current_device() - - if tp_degree * ulysses_degree != world_size: - raise ValueError( - f"tp_degree ({tp_degree}) x ulysses_degree ({ulysses_degree}) must equal the world size ({world_size})." - ) - - # Identical weights on every rank (same seed), kept on CPU as the Neuron pre-shard backend requires. - torch.manual_seed(0) - model = model_class(**init_dict).eval() - - # Single-device (unsharded) reference on CPU, computed before the shard plan mutates the weights in place. - with torch.no_grad(): - ref_output = model(**inputs, return_dict=False)[0].float().cpu() - - model.enable_parallelism( - config=ParallelConfig( - tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), - context_parallel_config=ContextParallelConfig(ulysses_degree=ulysses_degree), - ) - ) - model = model.to(device) - torch.neuron.synchronize() - - inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} - with torch.no_grad(): - output = model(**inputs_on_device, return_dict=False)[0] - torch.neuron.synchronize() - output = output.float().cpu() - - if rank == 0: - assert output.shape == ref_output.shape, f"shape mismatch: {output.shape} vs {ref_output.shape}" - assert torch.isfinite(output).all(), "output contains non-finite values" - max_abs = (output - ref_output).abs().max().item() - denom = ref_output.abs().max().item() + 1e-6 - print( - f"[rank0] tp_degree={tp_degree} ulysses_degree={ulysses_degree} " - f"output_shape={tuple(output.shape)} max_abs_diff={max_abs:.4e} max_rel_diff={max_abs / denom:.4e}" - ) - # Neuron runs matmuls in bf16 internally, so compare with a bf16-level tolerance, as - # `TensorParallelNeuronTesterMixin` does. A wrong shard plan or a mis-ordered mesh produces grossly different output and is caught well - # inside this bound. - torch.testing.assert_close(output, ref_output, atol=2e-2, rtol=2e-2) - print("[rank0] PASS: Neuron hybrid-parallel output matches single-device reference.") - - dist.barrier() - dist.destroy_process_group() - - -if __name__ == "__main__": - try: - main() - except Exception: - traceback.print_exc() - # Ensure a non-zero exit so the launching pytest sees the failure. - os._exit(1) diff --git a/tests/models/transformers/_neuron_sharded_load_worker.py b/tests/models/transformers/_neuron_sharded_load_worker.py deleted file mode 100644 index fb2cee7fbfac..000000000000 --- a/tests/models/transformers/_neuron_sharded_load_worker.py +++ /dev/null @@ -1,170 +0,0 @@ -# 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. - -"""Generic torchrun worker: assert `from_pretrained(..., parallel_config=...)` installs the context-parallel hooks. - -The sharded-load path shards weights while reading the checkpoint, so it cannot call `enable_parallelism` afterwards -and applies the parallelism itself. Tensor parallelism it did apply; the context-parallel hooks it did not, which is -silent — the model still returns the right numbers, every rank just redundantly computes the whole sequence. So this -worker checks both halves: the hooks are registered *and* the output still matches a single-device reference. - -Same contract as `_neuron_hybrid_worker.py`: the model under test is supplied as a `module:function` spec reference on -the command line, and the referenced factory returns `(model_class, init_dict, inputs)` with CPU tensors. - - torchrun --nproc_per_node=8 _neuron_sharded_load_worker.py \\ - tests.models.transformers.test_models_transformer_flux:make_neuron_sharded_load_spec - -`tp_degree` and `ulysses_degree` are read from `TP_DEGREE` / `ULYSSES_DEGREE` (defaults 2 and 4, whose product is -the launched world size). `ulysses_degree` cannot be 2 on Neuron: its all-to-all only accepts group sizes of 4, 8, -16 or multiples of 32. - -Rank 0 writes the checkpoint that every rank then reads, so this is single-node only, as the rest of the Neuron -test workers are. - -Exit code 0 means the sharded-load path applied both parallelisms correctly; non-zero means failure. -""" - -import argparse -import importlib -import os -import shutil -import sys -import tempfile -import traceback - - -# Make the in-repo `diffusers` and `tests` packages importable when run via torchrun from an arbitrary CWD. -sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "src")) -sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..")) - -import torch -import torch.distributed as dist -import torch_neuronx # noqa: F401 — registers torch.neuron - -from diffusers import ContextParallelConfig, ParallelConfig, TensorParallelConfig - - -def _context_parallel_hook_names(model): - """Every `cp_input---*` / `cp_output---*` hook `apply_context_parallel` registered on `model`.""" - names = [] - for module in model.modules(): - registry = getattr(module, "_diffusers_hook", None) - if registry is not None: - names.extend(name for name in registry.hooks if name.startswith(("cp_input", "cp_output"))) - return names - - -def main(): - parser = argparse.ArgumentParser(description="Neuron sharded-load context-parallel hook worker.") - parser.add_argument( - "spec", - help="`module:function` reference returning (model_class, init_dict, cpu_inputs) for the model under test.", - ) - args = parser.parse_args() - module_name, _, fn_name = args.spec.partition(":") - model_class, init_dict, inputs = getattr(importlib.import_module(module_name), fn_name)() - - tp_degree = int(os.environ.get("TP_DEGREE", "2")) - ulysses_degree = int(os.environ.get("ULYSSES_DEGREE", "4")) - - dist.init_process_group(backend="neuron") - rank = dist.get_rank() - world_size = dist.get_world_size() - device = torch.neuron.current_device() - - if tp_degree * ulysses_degree != world_size: - raise ValueError( - f"tp_degree ({tp_degree}) x ulysses_degree ({ulysses_degree}) must equal the world size ({world_size})." - ) - - # Rank 0 writes the checkpoint the sharded loader then reads on every rank. Safetensors, because that is what - # the per-rank streaming loader requires. - checkpoint_dir = os.environ.get( - "SHARDED_LOAD_CHECKPOINT_DIR", os.path.join(tempfile.gettempdir(), "diffusers_neuron_sharded_load_ckpt") - ) - if rank == 0: - shutil.rmtree(checkpoint_dir, ignore_errors=True) - torch.manual_seed(0) - model_class(**init_dict).eval().save_pretrained(checkpoint_dir) - dist.barrier() - - # Single-device (unsharded) reference, read back from the same checkpoint so only the loading path differs. - ref_output = None - if rank == 0: - reference = model_class.from_pretrained(checkpoint_dir).eval() - with torch.no_grad(): - ref_output = reference(**inputs, return_dict=False)[0].float().cpu() - del reference - - model = model_class.from_pretrained( - checkpoint_dir, - parallel_config=ParallelConfig( - tensor_parallel_config=TensorParallelConfig(tp_degree=tp_degree), - context_parallel_config=ContextParallelConfig(ulysses_degree=ulysses_degree), - ), - ).eval() - torch.neuron.synchronize() - - # The point of the test: the loader has to install these itself, since `enable_parallelism` is unavailable - # once the weights are sharded. - hook_names = _context_parallel_hook_names(model) - assert hook_names, ( - "`from_pretrained(..., parallel_config=...)` applied tensor parallelism but registered no context-parallel " - "hooks, so the `context_parallel_config` was silently ignored." - ) - processors = [getattr(module, "processor", None) for module in model.modules()] - processor_configs = [ - getattr(p, "_parallel_config", None) for p in processors if p is not None and hasattr(p, "_parallel_config") - ] - assert processor_configs and all(c is not None for c in processor_configs), ( - "Context-parallel hooks are registered but the attention processors did not receive the `ParallelConfig`, " - "so attention would run without the Ulysses all-to-all." - ) - - inputs_on_device = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} - with torch.no_grad(): - output = model(**inputs_on_device, return_dict=False)[0] - torch.neuron.synchronize() - output = output.float().cpu() - - if rank == 0: - assert output.shape == ref_output.shape, f"shape mismatch: {output.shape} vs {ref_output.shape}" - assert torch.isfinite(output).all(), "output contains non-finite values" - max_abs = (output - ref_output).abs().max().item() - denom = ref_output.abs().max().item() + 1e-6 - print( - f"[rank0] tp_degree={tp_degree} ulysses_degree={ulysses_degree} " - f"context_parallel_hooks={len(hook_names)} output_shape={tuple(output.shape)} " - f"max_abs_diff={max_abs:.4e} max_rel_diff={max_abs / denom:.4e}" - ) - # Neuron runs matmuls in bf16 internally, so compare with a bf16-level tolerance, as - # `TensorParallelNeuronTesterMixin` does. A wrong shard plan or a mis-ordered mesh produces grossly different output and is caught well - # inside this bound. - torch.testing.assert_close(output, ref_output, atol=2e-2, rtol=2e-2) - print("[rank0] PASS: sharded load applied both parallelisms and matches the single-device reference.") - - dist.barrier() - if rank == 0: - shutil.rmtree(checkpoint_dir, ignore_errors=True) - dist.destroy_process_group() - - -if __name__ == "__main__": - try: - main() - except Exception: - traceback.print_exc() - # Ensure a non-zero exit so the launching pytest sees the failure. - os._exit(1) diff --git a/tests/models/transformers/test_models_transformer_flux.py b/tests/models/transformers/test_models_transformer_flux.py index d40226584dff..021962792625 100644 --- a/tests/models/transformers/test_models_transformer_flux.py +++ b/tests/models/transformers/test_models_transformer_flux.py @@ -13,9 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import os -import subprocess -import sys import tempfile from typing import Any @@ -27,26 +24,20 @@ from diffusers.models.transformers.transformer_flux import FluxIPAdapterAttnProcessor from diffusers.utils.torch_utils import randn_tensor -from ...testing_utils import ( - enable_full_determinism, - is_context_parallel, - is_tensor_parallel, - require_torch_neuron, - torch_device, -) +from ...testing_utils import enable_full_determinism, torch_device from ..testing_utils import ( AttentionBackendTesterMixin, AttentionTesterMixin, BaseModelTesterConfig, BitsAndBytesCompileTesterMixin, BitsAndBytesTesterMixin, + ContextAndTensorParallelTesterMixin, ContextParallelAttentionBackendsTesterMixin, ContextParallelTesterMixin, FasterCacheTesterMixin, FirstBlockCacheTesterMixin, GGUFCompileTesterMixin, GGUFTesterMixin, - HybridParallelTesterMixin, IPAdapterTesterMixin, LoraHotSwappingForModelTesterMixin, LoraTesterMixin, @@ -293,83 +284,15 @@ def get_init_dict(self): return {**super().get_init_dict(), "num_attention_heads": self.tp_world_size} -class TestFluxTransformerHybridParallel(FluxTransformerTesterConfig, HybridParallelTesterMixin): - """Tensor Parallel x Context Parallel inference tests for Flux Transformer (needs 4 accelerators).""" - - -def make_neuron_hybrid_spec(): - """Model spec consumed by the generic Neuron hybrid worker (`_neuron_hybrid_worker.py`). - - Returns `(model_class, init_dict, cpu_inputs)`, with `num_attention_heads` is raised to 8 so the head count survives - being divided twice: `tp_degree=2` leaves 4 heads per rank and `ulysses_degree=4` splits those into 1 each. - (`ulysses_degree` cannot be 2 on Neuron, whose all-to-all only accepts group sizes of 4, 8, 16 or multiples - of 32.) - """ - config = FluxTransformerTesterConfig() - init_dict = config.get_init_dict() | {"num_attention_heads": 8} - return FluxTransformer2DModel, init_dict, config.get_dummy_inputs(device="cpu") - - -def make_neuron_sharded_load_spec(): - """Model spec consumed by the sharded-load worker (`_neuron_sharded_load_worker.py`). - - Returns `(model_class, init_dict, cpu_inputs)`, with `num_attention_heads` is raised to 8 so the head count survives - being divided twice: `tp_degree=2` leaves 4 heads per rank and `ulysses_degree=4` splits those into 1 each. - (`ulysses_degree` cannot be 2 on Neuron, whose all-to-all only accepts group sizes of 4, 8, 16 or multiples - of 32.) - """ - config = FluxTransformerTesterConfig() - init_dict = config.get_init_dict() | {"num_attention_heads": 8} - return FluxTransformer2DModel, init_dict, config.get_dummy_inputs(device="cpu") - - -@is_tensor_parallel -@require_torch_neuron -class TestFluxTransformerShardedLoadNeuron: - """`from_pretrained(..., parallel_config=...)` with both parallelisms, on AWS Neuron. - - Launched through `torchrun` like `TestFluxTransformerHybridParallelNeuron`, at `tp_degree=2 x ulysses_degree=4`, i.e. 8 - ranks. The worker asserts that the sharded-load path registered the context-parallel hooks — which numbers alone - cannot detect, since a model that silently skips them still returns the right answer — and that the output still - matches a single-device reference read back from the same checkpoint. - """ - - def test_sharded_load_context_parallel_neuron(self): - worker = os.path.join(os.path.dirname(__file__), "_neuron_sharded_load_worker.py") - spec = "tests.models.transformers.test_models_transformer_flux:make_neuron_sharded_load_spec" - cmd = [sys.executable, "-m", "torch.distributed.run", "--nproc_per_node=8", worker, spec] - result = subprocess.run(cmd, capture_output=True, text=True) - assert result.returncode == 0, ( - f"Neuron sharded-load worker failed (exit {result.returncode}).\n" - f"--- stdout ---\n{result.stdout}\n--- stderr ---\n{result.stderr}" - ) +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.""" -@is_context_parallel -@is_tensor_parallel -@require_torch_neuron -class TestFluxTransformerHybridParallelNeuron: - """Tensor Parallel x Context Parallel inference test for Flux Transformer on AWS Neuron. - - Launches `_neuron_hybrid_worker.py` through `torchrun` with the `"neuron"` distributed backend, at - `tp_degree=2 x ulysses_degree=4`, i.e. 8 ranks. - """ - - def test_hybrid_parallel_neuron_inference(self): - worker = os.path.join(os.path.dirname(__file__), "_neuron_hybrid_worker.py") - spec = "tests.models.transformers.test_models_transformer_flux:make_neuron_hybrid_spec" - cmd = [sys.executable, "-m", "torch.distributed.run", "--nproc_per_node=8", worker, spec] - result = subprocess.run(cmd, capture_output=True, text=True) - assert result.returncode == 0, ( - f"Neuron hybrid-parallel worker failed (exit {result.returncode}).\n" - f"--- stdout ---\n{result.stdout}\n--- stderr ---\n{result.stderr}" - ) - - class TestFluxTransformerIPAdapter(FluxTransformerTesterConfig, IPAdapterTesterMixin): """IP Adapter tests for Flux Transformer.""" diff --git a/tests/models/transformers/test_models_transformer_qwenimage.py b/tests/models/transformers/test_models_transformer_qwenimage.py index fcce23451bed..8508e3095317 100644 --- a/tests/models/transformers/test_models_transformer_qwenimage.py +++ b/tests/models/transformers/test_models_transformer_qwenimage.py @@ -320,19 +320,14 @@ def test_tensor_parallel_tpu_inference(self): class TestQwenImageTransformerContextAndTensorParallel( QwenImageTransformerTesterConfig, ContextAndTensorParallelTesterMixin ): - """Context Parallel x Tensor Parallel inference tests for QwenImage Transformer (4 accelerators). - - QwenImage is the model this runs on because its dummy config has four attention heads, and Ulysses splits the - heads TP already sharded — so `ulysses_degree` x `tp_degree` has to divide the head count. - """ + def get_init_dict(self): + return {**super().get_init_dict(), "num_attention_heads": 8} - def get_dummy_inputs(self, batch_size: int = 1) -> dict[str, torch.Tensor]: - inputs = super().get_dummy_inputs(batch_size=batch_size) - encoder_hidden_states_mask = inputs["encoder_hidden_states_mask"] - encoder_hidden_states_mask[:, 1] = 0 - encoder_hidden_states_mask[:, 3] = 0 - encoder_hidden_states_mask[:, 5:] = 0 - inputs["encoder_hidden_states_mask"] = encoder_hidden_states_mask + 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 From 5ef4ef67748220eee0067aa8964aad0f485be146 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Mon, 23 Nov 2026 17:43:36 +0000 Subject: [PATCH 08/16] Test TP+CP inference on all transformers that define both plans --- tests/models/testing_utils/parallelism.py | 8 +++++--- .../transformers/test_models_transformer_flux2.py | 6 ++++++ .../test_models_transformer_minimax_h3.py | 12 ++++++++++++ .../test_models_transformer_minimax_h3_image.py | 8 ++++++++ 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/tests/models/testing_utils/parallelism.py b/tests/models/testing_utils/parallelism.py index 0aea912d12d6..dcb589d4d64b 100644 --- a/tests/models/testing_utils/parallelism.py +++ b/tests/models/testing_utils/parallelism.py @@ -929,9 +929,11 @@ def _context_and_tensor_parallel_worker( 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)[0] + output = model(**device_inputs, return_dict=False) tolerance = 2e-2 if device_type in ("tpu", "neuron") else 1e-3 - torch.testing.assert_close(output.float().cpu(), reference, atol=tolerance, rtol=tolerance) + torch.testing.assert_close( + tuple(item.float().cpu() for item in output), reference, atol=tolerance, rtol=tolerance + ) finally: dist.destroy_process_group() @@ -986,7 +988,7 @@ def test_context_and_tensor_parallel_inference(self, tmp_path, cp_axis, loading, 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 = model(**inputs, return_dict=False)[0].float() + reference = tuple(item.float() for item in model(**inputs, return_dict=False)) checkpoint = tmp_path / "checkpoint" model.save_pretrained(checkpoint) 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 d9258f04127e..b9a21f0f4598 100644 --- a/tests/models/transformers/test_models_transformer_minimax_h3.py +++ b/tests/models/transformers/test_models_transformer_minimax_h3.py @@ -23,6 +23,7 @@ from ..testing_utils import ( AttentionTesterMixin, BaseModelTesterConfig, + ContextAndTensorParallelTesterMixin, ContextParallelTesterMixin, LoraTesterMixin, MemoryTesterMixin, @@ -193,6 +194,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.""" From 8b1445dc98a091d242ee2119b78d55c6c53efb75 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Thu, 26 Nov 2026 18:14:57 +0000 Subject: [PATCH 09/16] docs: address Steven's review on combining TP and CP --- .../en/optimization/context_parallelism.md | 2 + .../en/optimization/tensor_parallelism.md | 79 ++++++++++++++++++ .../en/training/distributed_inference.md | 81 +------------------ 3 files changed, 82 insertions(+), 80 deletions(-) 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..35e57e7a5c30 100644 --- a/docs/source/en/optimization/tensor_parallelism.md +++ b/docs/source/en/optimization/tensor_parallelism.md @@ -81,6 +81,85 @@ 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 with `from_pretrained(..., parallel_config=...)` at 1344×768 and 124 frames on one AWS Trainium2 instance (trn2.48xlarge). The peak memory measured during denoising was: + +| NeuronCores | config | weights / core | peak memory / core | s / step | +|---|---|---|---|---| +| 8 | TP=8 | 7.84 GiB | 18.7 GiB | 9.33 | +| 16 | TP=4 × Ulysses=4 | 15.53 GiB | 21.7 GiB | 5.31 | +| 32 | TP=4 × Ulysses=8 | 15.53 GiB | 20.5 GiB | 3.97 | +| 32 | TP=8 × Ulysses=4 | 7.84 GiB | 13.7 GiB | 3.81 | + +At the same 32 cores, TP=8 × Ulysses=4 is both faster and lighter than TP=4 × Ulysses=8, so on this model it pays to max out TP first and add CP on top. Its 56 heads cap TP at 8, so going further means raising the CP degree. + ## 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/training/distributed_inference.md b/docs/source/en/training/distributed_inference.md index 2e698d50015b..664ad76dd92e 100644 --- a/docs/source/en/training/distributed_inference.md +++ b/docs/source/en/training/distributed_inference.md @@ -32,85 +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, [combine tensor and context parallelism](#combining-context-and-tensor-parallelism) in one [`ParallelConfig`]. Raise `tp_degree` until the weights fit, then add context parallelism on top for latency. +- 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. - -## Combining context and tensor parallelism - -The two strategies split a model along different axes: tensor parallelism shards the weights, context parallelism splits the sequence. A model whose weights don't fit on one device *and* whose sequence is too long for one device's attention needs both, and neither alone can help: TP doesn't divide the sequence, and CP doesn't divide the weights. - -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 TP all-reduces and the CP all-gathers or all-to-alls each stay inside their own process group. The model must define both a `_tp_plan` and a `_cp_plan`. - -```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) - - # 8 devices: 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), - ), - ) - - pipeline = 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 `pipeline.to(device)`. - pipeline.text_encoder.to(device) - pipeline.vae.to(device) - - generator = torch.Generator().manual_seed(42) - image = pipeline(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 -``` - -Only the transformer is sharded. Each rank holds a full copy of the text encoder, so each GPU needs enough memory for the text encoder plus its share of the transformer. - -The degrees are checked before anything is sharded: - -- `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. Pass `ulysses_anything=True` to pad the heads instead when they don't divide. - -The default mesh puts `"tp"` outermost, so the Ulysses groups are runs of consecutive ranks. Some accelerator runtimes, AWS Neuron among them, only accept contiguous replica groups for all-to-all while tolerating strided groups for the all-reduce TP needs, and only one axis of the mesh can be contiguous. On multi-node CUDA the opposite order is usually better, since TP's per-layer all-reduce is the most bandwidth-hungry collective and wants to stay inside one NVLink domain. To choose the layout yourself, build the mesh with `"tp"`, `"ring"` and `"ulysses"` dimensions and pass it as `mesh=` on either config. - -Which degree to raise first depends on what you are short of. TP is what lowers per-device memory; CP mostly lowers latency. For example, [MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3) (a 33B audio-video DiT, 56 heads) at 1344×768 and 124 frames on one AWS Trainium2 instance (trn2.48xlarge, loaded with `from_pretrained(..., parallel_config=...)`; peak memory is measured during denoising): - -| NeuronCores | config | weights / core | peak memory / core | s / step | -|---|---|---|---|---| -| 8 | TP=8 | 7.84 GiB | 18.7 GiB | 9.33 | -| 16 | TP=4 × Ulysses=4 | 15.53 GiB | 21.7 GiB | 5.31 | -| 32 | TP=4 × Ulysses=8 | 15.53 GiB | 20.5 GiB | 3.97 | -| 32 | TP=8 × Ulysses=4 | 7.84 GiB | 13.7 GiB | 3.81 | - -At the same 32 cores, TP=8 × Ulysses=4 is both faster and lighter than TP=4 × Ulysses=8, so on this model it pays to max out TP first and add CP on top. Its 56 heads cap TP at 8, so going further means raising the CP degree. From 08ca471dfb5ec03882cc853f3ef6d7efbf953785 Mon Sep 17 00:00:00 2001 From: Jingya HUANG <44135271+JingyaHuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:26:20 +0000 Subject: [PATCH 10/16] refactor(parallel): check combined mesh dims in __post_init__ Validate a user-supplied mesh for combined TP and CP when the ParallelConfig is created instead of in setup(). --- src/diffusers/models/_modeling_parallel.py | 23 +++++++++++++--------- tests/models/test_parallelism_combined.py | 13 +++++++----- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/diffusers/models/_modeling_parallel.py b/src/diffusers/models/_modeling_parallel.py index 59ba46449e83..2605754f2914 100644 --- a/src/diffusers/models/_modeling_parallel.py +++ b/src/diffusers/models/_modeling_parallel.py @@ -223,6 +223,20 @@ def __post_init__(self): "`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`." + ) + @property def _is_combined(self) -> bool: """Whether both context and tensor parallelism are requested, i.e. they must share one mesh.""" @@ -243,15 +257,6 @@ def setup( cp_mesh = tp_mesh = mesh if self._is_combined: - dim_names = mesh.mesh_dim_names if mesh is not None else None - 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}). `enable_parallelism` and `from_pretrained` build this mesh from `ring_degree`/" - f"`ulysses_degree`/`tp_degree`; if you build it yourself, set `mesh=` on one of the two configs." - ) # CP selects its axes in setup. TP takes a one-dimensional submesh. tp_mesh = mesh["tp"] diff --git a/tests/models/test_parallelism_combined.py b/tests/models/test_parallelism_combined.py index 0ee741980d66..98565e2a9bcf 100644 --- a/tests/models/test_parallelism_combined.py +++ b/tests/models/test_parallelism_combined.py @@ -30,15 +30,18 @@ def _check_combined_mesh(rank, world_size, rendezvous, include_tp): 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) - config = ParallelConfig( - context_parallel_config=ContextParallelConfig(ulysses_degree=2), - tensor_parallel_config=TensorParallelConfig(tp_degree=2), - ) if not include_tp: with pytest.raises(ValueError, match=r"\['tp'\].*missing"): - config.setup(rank, world_size, torch.device("cpu"), mesh=mesh) + ParallelConfig( + context_parallel_config=ContextParallelConfig(ulysses_degree=2, mesh=mesh), + 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 From 25b0b8d142d2806129632eae27dcee0308b3fb8a Mon Sep 17 00:00:00 2001 From: Jingya HUANG <44135271+JingyaHuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:26:34 +0000 Subject: [PATCH 11/16] refactor(parallel): check combined world size in __post_init__ Raise when tp_degree * ring_degree * ulysses_degree exceeds the world size as soon as the ParallelConfig is created, if torch.distributed is initialized. Drop the check in _resolve_parallel_config, which init_device_mesh preempted. --- src/diffusers/models/_modeling_parallel.py | 10 ++++++++++ src/diffusers/models/modeling_utils.py | 7 ------- tests/models/test_parallelism_combined.py | 5 +++++ 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/diffusers/models/_modeling_parallel.py b/src/diffusers/models/_modeling_parallel.py index 2605754f2914..494286b48dfb 100644 --- a/src/diffusers/models/_modeling_parallel.py +++ b/src/diffusers/models/_modeling_parallel.py @@ -236,6 +236,16 @@ def __post_init__(self): 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: diff --git a/src/diffusers/models/modeling_utils.py b/src/diffusers/models/modeling_utils.py index 5ab8e90109fb..eaebe4b9ea7a 100644 --- a/src/diffusers/models/modeling_utils.py +++ b/src/diffusers/models/modeling_utils.py @@ -1735,13 +1735,6 @@ def _resolve_parallel_config( # 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 - requested = cp_config.ring_degree * cp_config.ulysses_degree * 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_degree}) = {requested} " - f"devices, which exceeds the world size ({world_size})." - ) 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: diff --git a/tests/models/test_parallelism_combined.py b/tests/models/test_parallelism_combined.py index 98565e2a9bcf..d870b3317a15 100644 --- a/tests/models/test_parallelism_combined.py +++ b/tests/models/test_parallelism_combined.py @@ -36,6 +36,11 @@ def _check_combined_mesh(rank, world_size, rendezvous, include_tp): 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( From b4e9ac01b395aeb83630c156400ba014832207c7 Mon Sep 17 00:00:00 2001 From: Jingya HUANG <44135271+JingyaHuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:44:14 +0000 Subject: [PATCH 12/16] refactor(parallel): drop redundant guards in _apply_context_parallel The helper returns early when there is no context parallel config, so the two later checks were always true. --- src/diffusers/models/modeling_utils.py | 78 +++++++++++++------------- 1 file changed, 38 insertions(+), 40 deletions(-) diff --git a/src/diffusers/models/modeling_utils.py b/src/diffusers/models/modeling_utils.py index eaebe4b9ea7a..7cf7da591ab2 100644 --- a/src/diffusers/models/modeling_utils.py +++ b/src/diffusers/models/modeling_utils.py @@ -1819,52 +1819,50 @@ def _apply_context_parallel( 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 - - 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) + for module in self.modules(): + if not isinstance(module, attention_classes): + continue - 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()`." - ) + processor = module.processor + if processor is None or not hasattr(processor, "_attention_backend"): + continue - # All modules use the same attention processor and backend. We don't need to - # iterate over all modules after checking the first processor - break + 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()`." + ) + + # 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) + 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) @classmethod def _load_pretrained_model( From 22374a4f0cb1a733bc477e34178c3e1bb348e3e9 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Thu, 26 Nov 2026 18:24:13 +0000 Subject: [PATCH 13/16] docs: address Steven's review on combining TP and CP Move the combined section into the tensor parallelism guide and link to it from the distributed inference overview and the context parallelism guide. Co-Authored-By: Claude Opus 5.5 --- docs/source/en/optimization/tensor_parallelism.md | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/docs/source/en/optimization/tensor_parallelism.md b/docs/source/en/optimization/tensor_parallelism.md index 35e57e7a5c30..4244a82d0aa9 100644 --- a/docs/source/en/optimization/tensor_parallelism.md +++ b/docs/source/en/optimization/tensor_parallelism.md @@ -149,16 +149,7 @@ torchrun --nproc-per-node 8 tp_cp_flux2.py 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 with `from_pretrained(..., parallel_config=...)` at 1344×768 and 124 frames on one AWS Trainium2 instance (trn2.48xlarge). The peak memory measured during denoising was: - -| NeuronCores | config | weights / core | peak memory / core | s / step | -|---|---|---|---|---| -| 8 | TP=8 | 7.84 GiB | 18.7 GiB | 9.33 | -| 16 | TP=4 × Ulysses=4 | 15.53 GiB | 21.7 GiB | 5.31 | -| 32 | TP=4 × Ulysses=8 | 15.53 GiB | 20.5 GiB | 3.97 | -| 32 | TP=8 × Ulysses=4 | 7.84 GiB | 13.7 GiB | 3.81 | - -At the same 32 cores, TP=8 × Ulysses=4 is both faster and lighter than TP=4 × Ulysses=8, so on this model it pays to max out TP first and add CP on top. Its 56 heads cap TP at 8, so going further means raising the CP degree. +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 a fixed number of devices with a fast device-to-device interconnect, such as NVLink between GPUs, NeuronLink between Trainium chips, or ICI between TPU chips, raising `tp_degree` as far as the head count allows and then adding context parallelism is usually both faster and lighter than the reverse. Over slower links, such as PCIe, TP's per-layer all-reduce can outweigh its savings, so try a higher context parallel degree instead. Once the head count caps `tp_degree`, raise the context parallel degree to use more devices. ## Limitations From 7185021b0dc1ae7ab4be271e9defc180b58aaa83 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Tue, 1 Dec 2026 17:20:17 +0000 Subject: [PATCH 14/16] tests: launch TPU workers with set_tpu_launch_env from torch_tpu 0.3 --- tests/models/testing_utils/parallelism.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/models/testing_utils/parallelism.py b/tests/models/testing_utils/parallelism.py index dcb589d4d64b..c1b86b973895 100644 --- a/tests/models/testing_utils/parallelism.py +++ b/tests/models/testing_utils/parallelism.py @@ -791,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: @@ -814,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( @@ -846,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 @@ -856,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( From 5902568002db8abfb874c665f7440507ceac8825 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Tue, 1 Dec 2026 17:43:25 +0000 Subject: [PATCH 15/16] docs: add CUDA benchmarks for combining TP and CP --- docs/source/en/optimization/tensor_parallelism.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/source/en/optimization/tensor_parallelism.md b/docs/source/en/optimization/tensor_parallelism.md index 4244a82d0aa9..4933a0412540 100644 --- a/docs/source/en/optimization/tensor_parallelism.md +++ b/docs/source/en/optimization/tensor_parallelism.md @@ -149,7 +149,18 @@ torchrun --nproc-per-node 8 tp_cp_flux2.py 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 a fixed number of devices with a fast device-to-device interconnect, such as NVLink between GPUs, NeuronLink between Trainium chips, or ICI between TPU chips, raising `tp_degree` as far as the head count allows and then adding context parallelism is usually both faster and lighter than the reverse. Over slower links, such as PCIe, TP's per-layer all-reduce can outweigh its savings, so try a higher context parallel degree instead. Once the head count caps `tp_degree`, raise the context parallel degree to use more devices. +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 From c48eb2d71147bc55cb10cd675eed50f4faee5ad5 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Tue, 1 Dec 2026 17:43:26 +0000 Subject: [PATCH 16/16] docs: update the TorchTPU launch command for torch_tpu 0.3 --- docs/source/en/optimization/tpu.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 ```