diff --git a/docs/source/en/optimization/tensor_parallelism.md b/docs/source/en/optimization/tensor_parallelism.md index 870e27872f30..d044090fdafc 100644 --- a/docs/source/en/optimization/tensor_parallelism.md +++ b/docs/source/en/optimization/tensor_parallelism.md @@ -139,13 +139,37 @@ self.to_out._tp_packed_row_blocks = [self.inner_dim, self.mlp_hidden_dim] The plan in [`transformer_flux2.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_flux2.py) uses both forms. The double-stream SwiGLU pair passes `blocks` directly. The fused single-stream QKV and MLP projection stores its sizes on the `Linear` in `Flux2ParallelSelfAttention.__init__`, because they depend on `mlp_ratio` and `mlp_mult_factor`. +### Norms and rotary embeddings across heads + +Some models apply the QK-norm and the rotary embedding to the full `heads * head_dim` projection before splitting it into heads, such as LTX-Video and LTX-2 (`qk_norm="rms_norm_across_heads"`). Under tensor parallelism each rank only holds the columns of its own heads, so these need two more styles. + +| Style | Applies to | Each rank | +|---|---|---| +| `"rmsnorm_across_heads"` | a `torch.nn.RMSNorm` after a `"colwise"` projection | holds its slice of the norm weight and all-reduces the sum of squares, so it normalizes by the statistics of the full row | +| `ShardOutput()` | a module without parameters, such as the rotary embedding | keeps its own contiguous chunk of each output tensor | + +`ShardOutput` takes the dim to cut as `dim`. When the dim depends on the config, omit it and set `_tp_output_shard_dim` on the module during `__init__` instead. + +```py +# in src/diffusers/models/transformers/your_model.py +from ...hooks.tensor_parallel import ShardOutput +``` + +```py +# in the model's _tp_plan +"transformer_blocks.*.attn1.norm_q": "rmsnorm_across_heads", +"rope": ShardOutput(), +``` + +The attention processor must also reshape by `head_dim` rather than by the global head count, as in `query.unflatten(2, (-1, attn.head_dim))`, so it works on any number of local heads. The plan in [`transformer_ltx2.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_ltx2.py) uses both styles. + ### What to leave out -Modules left out of the plan are replicated on every rank. Leave out normalization layers, patch and text embeddings, and the final `norm_out` and `proj_out`. They're small, so sharding them saves little memory and adds communication. AdaLN modulation (`img_mod` and `txt_mod`) is usually small enough to leave out too. When it's large, like MiniMax-H3's `adaln_proj.linear`, shard it with `"rowwise_split_input"`. +Modules left out of the plan are replicated on every rank. Leave out normalization layers (other than the QK-norms across heads above), patch and text embeddings, and the final `norm_out` and `proj_out`. They're small, so sharding them saves little memory and adds communication. AdaLN modulation (`img_mod` and `txt_mod`) is usually small enough to leave out too. When it's large, like MiniMax-H3's `adaln_proj.linear`, shard it with `"rowwise_split_input"`. ### Constraints and verification -- `tp_degree` must divide `config.num_attention_heads`. +- `tp_degree` must divide `config.num_attention_heads`, and the head count of every attention module whose `to_q` is `"colwise"`. - Every packed block must *individually* be divisible by `tp_degree`, not just their sum. [`~ModelMixin.from_pretrained`] and [`~ModelMixin.enable_parallelism`] check both before loading or sharding any weight. diff --git a/src/diffusers/hooks/tensor_parallel.py b/src/diffusers/hooks/tensor_parallel.py index 06a75b71556c..6694752ba667 100644 --- a/src/diffusers/hooks/tensor_parallel.py +++ b/src/diffusers/hooks/tensor_parallel.py @@ -50,6 +50,35 @@ def __init__(self, blocks: "list[int] | None" = None): self.blocks = blocks +class ShardOutput: + """Keep only this rank's contiguous chunk of a parameter-free module's output tensors along `dim`. + + For a module, such as a rotary embedding, whose outputs span all attention heads and are consumed next to + column-sharded projections. If `dim` is `None`, the module must carry a `_tp_output_shard_dim` attribute set during + model `__init__`. + """ + + def __init__(self, dim: "int | None" = None): + self.dim = dim + + +def _output_shard_dim(style: ShardOutput, module, path: str) -> int: + """The dim of a `ShardOutput` style: its own `dim`, else the `_tp_output_shard_dim` attribute on the module.""" + dim = style.dim if style.dim is not None else getattr(module, "_tp_output_shard_dim", None) + if dim is None: + raise ValueError( + f"'{path}' uses ShardOutput but has no dim: pass `dim` to it, or set `_tp_output_shard_dim` on the module " + f"in the model's `__init__`." + ) + return dim + + +_SUPPORTED_STYLES_MESSAGE = ( + "Expected 'colwise', 'rowwise', 'rowwise_split_input', 'rmsnorm_across_heads', PackedColwiseParallel, " + "PackedRowwiseParallel, or ShardOutput." +) + + def _packed_blocks(style: "PackedColwiseParallel | PackedRowwiseParallel", module, path: str) -> "list[int]": """The blocks of a packed style: its own `blocks`, else the `_tp_packed_*_blocks` attribute on the Linear.""" attr = "_tp_packed_col_blocks" if isinstance(style, PackedColwiseParallel) else "_tp_packed_row_blocks" @@ -161,17 +190,28 @@ def resolve_tp_shard_specs(model: torch.nn.Module, tp_plan: dict, tp_degree: int blocks = _packed_blocks(style, submodule, path) weight_spec = TPShardSpec(1, _blocks_to_block_sizes(submodule.weight.shape[1], blocks)) bias_spec = TPShardSpec(None, None) + elif style == "rmsnorm_across_heads": + _check_rmsnorm(submodule, path) + if submodule.weight is None: + continue + # The norm weight lines up with the columns of the colwise projection that feeds it. + weight_spec = TPShardSpec(0, [submodule.weight.shape[0]]) + bias_spec = None + elif isinstance(style, ShardOutput): + _output_shard_dim(style, submodule, path) + continue # no parameters to place else: raise ValueError( - f"Unsupported tensor-parallel style '{style}' for '{path}'. " - f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or " - f"PackedRowwiseParallel." + f"Unsupported tensor-parallel style '{style}' for '{path}'. {_SUPPORTED_STYLES_MESSAGE}" ) specs[f"{path}.weight"] = weight_spec - if submodule.bias is not None: + if bias_spec is not None and getattr(submodule, "bias", None) is not None: specs[f"{path}.bias"] = bias_spec + if style == "colwise" and relative_path.endswith("to_q"): + _check_attention_heads(block, relative_path, path, tp_degree) + for name, spec in specs.items(): for block_size in spec.block_sizes or []: if block_size % tp_degree != 0: @@ -183,6 +223,32 @@ def resolve_tp_shard_specs(model: torch.nn.Module, tp_plan: dict, tp_degree: int return specs +def _check_rmsnorm(module: torch.nn.Module, path: str) -> None: + """Reject a `"rmsnorm_across_heads"` target that is not a `torch.nn.RMSNorm` over its last dimension.""" + if not isinstance(module, torch.nn.RMSNorm) or len(module.normalized_shape) != 1: + raise ValueError( + f"'{path}' uses 'rmsnorm_across_heads', which needs a `torch.nn.RMSNorm` over the last dimension, but got " + f"'{module.__class__.__name__}'." + ) + + +def _check_attention_heads(block: torch.nn.Module, relative_path: str, path: str, tp_degree: int) -> None: + """Reject a colwise `to_q` whose attention module has a head count that `tp_degree` does not divide. + + The shape checks alone would accept a split through the middle of a head whenever `heads * head_dim` divides by + `tp_degree`. This catches attention modules that `config.num_attention_heads` does not describe, such as the audio + attentions of LTX-2. + """ + parent_path = relative_path.rpartition(".")[0] + attention = block.get_submodule(parent_path) if parent_path else block + heads = getattr(attention, "heads", None) + if isinstance(heads, int) and heads % tp_degree != 0: + raise ValueError( + f"Cannot shard '{path}' across {tp_degree} tensor-parallel ranks: its attention module has {heads} heads, " + f"which is not divisible by {tp_degree}." + ) + + def _maybe_get_submodule(module: torch.nn.Module, path: str) -> "torch.nn.Module | None": """Resolve the dotted `path` on `module`, or return `None` if an attribute along it is missing or `None`.""" for atom in path.split("."): @@ -278,12 +344,87 @@ def _shard_packed_param(param, dim: int, blocks: "list[int]", device_mesh, src_d ) +def _rmsnorm_across_heads_style(partition: bool): + """A style that makes a `torch.nn.RMSNorm` over all heads work on this rank's column slice. + + The weight is sharded like the colwise projection that feeds the norm. In the forward, the sum of squares of the + local slice is all-reduced, so every rank normalizes by the statistics of the full row and the output matches the + unsharded norm. Only a `[..., 1]` tensor is exchanged. `partition=False` leaves an already sharded weight in place. + """ + import torch.distributed._functional_collectives as funcol + from torch.distributed.tensor import DTensor, Shard, distribute_tensor + from torch.distributed.tensor.parallel import ParallelStyle + + class _RMSNormAcrossHeads(ParallelStyle): + def _apply(self, module, device_mesh): + _check_rmsnorm(module, module.__class__.__name__) + weight = module.weight + if partition and weight is not None and not isinstance(weight, DTensor): + module.register_parameter( + "weight", + torch.nn.Parameter( + distribute_tensor(weight, device_mesh, [Shard(0)], src_data_rank=self.src_data_rank), + requires_grad=weight.requires_grad, + ), + ) + full_dim = module.normalized_shape[0] + + def forward(hidden_states: torch.Tensor) -> torch.Tensor: + # Same math as `torch.nn.functional.rms_norm`: computed in float32, cast back at the end. + upcast = hidden_states.float() + square_sum = funcol.all_reduce(upcast.pow(2).sum(-1, keepdim=True), "sum", device_mesh) + eps = module.eps if module.eps is not None else torch.finfo(hidden_states.dtype).eps + output = upcast * torch.rsqrt(square_sum / full_dim + eps) + if module.weight is not None: + weight = module.weight + weight = weight.to_local() if isinstance(weight, DTensor) else weight + output = output * weight + return output.to(hidden_states.dtype) + + module.forward = forward + return module + + return _RMSNormAcrossHeads() + + +def _shard_output_style(marker: ShardOutput): + """A style that keeps only this rank's contiguous chunk of each output tensor of a parameter-free module.""" + from torch.distributed.tensor.parallel import ParallelStyle + + class _ShardOutputImpl(ParallelStyle): + def _apply(self, module, device_mesh): + dim = _output_shard_dim(marker, module, module.__class__.__name__) + rank, world_size = device_mesh.get_local_rank(), device_mesh.size() + + def shard(tensor): + if not isinstance(tensor, torch.Tensor): + return tensor + size = tensor.shape[dim] + if size % world_size != 0: + raise ValueError( + f"Cannot shard an output of '{module.__class__.__name__}' across {world_size} tensor-parallel " + f"ranks: its size {size} along dim {dim} is not divisible by {world_size}." + ) + chunk = size // world_size + return tensor.narrow(dim, rank * chunk, chunk) + + def hook(_module, _args, output): + if isinstance(output, (tuple, list)): + return type(output)(shard(tensor) for tensor in output) + return shard(output) + + module.register_forward_hook(hook) + return module + + return _ShardOutputImpl() + + def _styles(relative_plan: dict) -> dict: """Map a `{relative_path: style}` plan to `parallelize_module` style instances. - Values may be plain strings (`"colwise"` / `"rowwise"` / `"rowwise_split_input"`) or `PackedColwiseParallel` / - `PackedRowwiseParallel` marker instances. Returns `{relative_path: ColwiseParallel() | RowwiseParallel() | }`. Divisibility by the TP degree is checked earlier, by `resolve_tp_shard_specs`. + Values may be plain strings (`"colwise"` / `"rowwise"` / `"rowwise_split_input"` / `"rmsnorm_across_heads"`) or + `PackedColwiseParallel` / `PackedRowwiseParallel` / `ShardOutput` marker instances. Returns `{relative_path: + ParallelStyle}`. Divisibility by the TP degree is checked earlier, by `resolve_tp_shard_specs`. """ from torch.distributed.tensor import Replicate, distribute_tensor from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel @@ -334,12 +475,12 @@ def _partition_linear_fn(self, name, module, device_mesh): resolved[path] = _make_packed_col(style) elif isinstance(style, PackedRowwiseParallel): resolved[path] = _make_packed_row(style) + elif style == "rmsnorm_across_heads": + resolved[path] = _rmsnorm_across_heads_style(partition=True) + elif isinstance(style, ShardOutput): + resolved[path] = _shard_output_style(style) else: - raise ValueError( - f"Unsupported tensor-parallel style '{style}' for '{path}'. " - f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or " - f"PackedRowwiseParallel." - ) + raise ValueError(f"Unsupported tensor-parallel style '{style}' for '{path}'. {_SUPPORTED_STYLES_MESSAGE}") return resolved @@ -373,12 +514,12 @@ def _partition_linear_fn(self, name, module, device_mesh): resolved[path] = _NoPartitionRowwise() elif style == "rowwise_split_input": resolved[path] = _NoPartitionRowwise(input_layouts=Replicate()) + elif style == "rmsnorm_across_heads": + resolved[path] = _rmsnorm_across_heads_style(partition=False) + elif isinstance(style, ShardOutput): + resolved[path] = _shard_output_style(style) else: - raise ValueError( - f"Unsupported tensor-parallel style '{style}' for '{path}'. " - f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or " - f"PackedRowwiseParallel." - ) + raise ValueError(f"Unsupported tensor-parallel style '{style}' for '{path}'. {_SUPPORTED_STYLES_MESSAGE}") return resolved @@ -534,8 +675,8 @@ def apply_tensor_parallel( config (`TensorParallelConfig`): The tensor-parallel config. Its device mesh must already be set up with `config.setup(...)`. tp_plan (`dict`): - A flat mapping of module-name globs to a `"colwise"`/`"rowwise"` style (or a packed variant), usually the - model's `_tp_plan`. + A flat mapping of module-name globs to a tensor-parallel style (`"colwise"`, `"rowwise"`, a packed variant, + ...), usually the model's `_tp_plan`. weights_already_sharded (`bool`, defaults to `False`): Whether the planned parameters are already `DTensor` shards, as they are after a streaming `from_pretrained` load. If `True`, only the forward hooks are registered. This is passed explicitly rather diff --git a/src/diffusers/models/transformers/transformer_ltx.py b/src/diffusers/models/transformers/transformer_ltx.py index fa5754ec90c5..bb7f922fe9b0 100644 --- a/src/diffusers/models/transformers/transformer_ltx.py +++ b/src/diffusers/models/transformers/transformer_ltx.py @@ -21,6 +21,7 @@ import torch.nn as nn from ...configuration_utils import ConfigMixin, register_to_config +from ...hooks.tensor_parallel import ShardOutput from ...loaders import FromOriginalModelMixin, PeftAdapterMixin from ...utils import apply_lora_scale, deprecate, logging from ...utils.torch_utils import maybe_allow_in_graph @@ -68,7 +69,7 @@ def __call__( if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) - attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) + attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])[:, :1] if encoder_hidden_states is None: encoder_hidden_states = hidden_states @@ -84,9 +85,9 @@ def __call__( query = apply_rotary_emb(query, image_rotary_emb) key = apply_rotary_emb(key, image_rotary_emb) - query = query.unflatten(2, (attn.heads, -1)) - key = key.unflatten(2, (attn.heads, -1)) - value = value.unflatten(2, (attn.heads, -1)) + query = query.unflatten(2, (-1, attn.head_dim)) + key = key.unflatten(2, (-1, attn.head_dim)) + value = value.unflatten(2, (-1, attn.head_dim)) hidden_states = dispatch_attention_fn( query, @@ -190,6 +191,8 @@ def __init__( self.patch_size = patch_size self.patch_size_t = patch_size_t self.theta = theta + # The dim of the cos/sin outputs that spans the attention heads, which tensor parallelism shards. + self._tp_output_shard_dim = -1 def _prepare_video_coords( self, @@ -408,6 +411,27 @@ class LTXVideoTransformer3DModel( _supports_gradient_checkpointing = True _skip_layerwise_casting_patterns = ["norm"] _repeated_blocks = ["LTXVideoTransformerBlock"] + # Tensor parallelism shards every attention by heads and every feed-forward by its hidden dim. The QK-norms + # normalize across all heads, so they are sharded with the heads and all-reduce their statistics, and the rotary + # embedding, which also spans all heads, is cut to this rank's heads. The AdaLN modulation, scale-shift tables, + # input/output projections and caption projection stay replicated. + _tp_plan = { + **{ + f"transformer_blocks.*.{attention}.{name}": style + for attention in ("attn1", "attn2") + for name, style in ( + ("to_q", "colwise"), + ("to_k", "colwise"), + ("to_v", "colwise"), + ("to_out.0", "rowwise"), + ("norm_q", "rmsnorm_across_heads"), + ("norm_k", "rmsnorm_across_heads"), + ) + }, + "transformer_blocks.*.ff.net.0.proj": "colwise", + "transformer_blocks.*.ff.net.2": "rowwise", + "rope": ShardOutput(), + } _cp_plan = { "": { "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), diff --git a/src/diffusers/models/transformers/transformer_ltx2.py b/src/diffusers/models/transformers/transformer_ltx2.py index 9c56b0fa0a39..06f4f85ca341 100644 --- a/src/diffusers/models/transformers/transformer_ltx2.py +++ b/src/diffusers/models/transformers/transformer_ltx2.py @@ -21,9 +21,10 @@ import torch.nn as nn from ...configuration_utils import ConfigMixin, register_to_config +from ...hooks.tensor_parallel import ShardOutput from ...loaders import FromOriginalModelMixin, PeftAdapterMixin from ...utils import BaseOutput, apply_lora_scale, logging -from .._modeling_parallel import ContextParallelInput, ContextParallelOutput +from .._modeling_parallel import Conditional, ContextParallelInput, ContextParallelOutput from ..attention import AttentionMixin, AttentionModuleMixin, FeedForward from ..attention_dispatch import dispatch_attention_fn from ..cache_utils import CacheMixin @@ -170,7 +171,7 @@ def __call__( if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) - attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) + attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])[:, :1] if encoder_hidden_states is None: encoder_hidden_states = hidden_states @@ -196,9 +197,9 @@ def __call__( query = apply_split_rotary_emb(query, query_rotary_emb) key = apply_split_rotary_emb(key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb) - query = query.unflatten(2, (attn.heads, -1)) - key = key.unflatten(2, (attn.heads, -1)) - value = value.unflatten(2, (attn.heads, -1)) + query = query.unflatten(2, (-1, attn.head_dim)) + key = key.unflatten(2, (-1, attn.head_dim)) + value = value.unflatten(2, (-1, attn.head_dim)) hidden_states = dispatch_attention_fn( query, @@ -214,7 +215,7 @@ def __call__( hidden_states = hidden_states.to(query.dtype) if attn.to_gate_logits is not None: - hidden_states = hidden_states.unflatten(2, (attn.heads, -1)) # [B, T, H, D] + hidden_states = hidden_states.unflatten(2, (-1, attn.head_dim)) # [B, T, H, D] # The factor of 2.0 is so that if the gates logits are zero-initialized the initial gates are all 1 gates = 2.0 * torch.sigmoid(gate_logits) # [B, T, H] hidden_states = hidden_states * gates.unsqueeze(-1) @@ -250,7 +251,7 @@ def __call__( if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) - attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) + attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])[:, :1] if encoder_hidden_states is None: encoder_hidden_states = hidden_states @@ -285,9 +286,9 @@ def __call__( key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb ) - query = query.unflatten(2, (attn.heads, -1)) - key = key.unflatten(2, (attn.heads, -1)) - value = value.unflatten(2, (attn.heads, -1)) + query = query.unflatten(2, (-1, attn.head_dim)) + key = key.unflatten(2, (-1, attn.head_dim)) + value = value.unflatten(2, (-1, attn.head_dim)) hidden_states = dispatch_attention_fn( query, @@ -307,7 +308,7 @@ def __call__( hidden_states = torch.lerp(value, hidden_states, perturbation_mask) if attn.to_gate_logits is not None: - hidden_states = hidden_states.unflatten(2, (attn.heads, -1)) # [B, T, H, D] + hidden_states = hidden_states.unflatten(2, (-1, attn.head_dim)) # [B, T, H, D] # The factor of 2.0 is so that if the gates logits are zero-initialized the initial gates are all 1 gates = 2.0 * torch.sigmoid(gate_logits) # [B, T, H] hidden_states = hidden_states * gates.unsqueeze(-1) @@ -839,6 +840,8 @@ def __init__( if rope_type not in ["interleaved", "split"]: raise ValueError(f"{rope_type=} not supported. Choose between 'interleaved' and 'split'.") self.rope_type = rope_type + # The dim of the cos/sin outputs that spans the attention heads, which tensor parallelism shards. + self._tp_output_shard_dim = -1 if rope_type == "interleaved" else 1 self.base_num_frames = base_num_frames self.num_attention_heads = num_attention_heads @@ -1113,6 +1116,40 @@ class LTX2VideoTransformer3DModel( _supports_gradient_checkpointing = True _skip_layerwise_casting_patterns = ["norm"] _repeated_blocks = ["LTX2VideoTransformerBlock"] + # Tensor parallelism shards every attention by heads and every feed-forward by its hidden dim. The QK-norms + # normalize across all heads, so they are sharded with the heads and all-reduce their statistics, and the rotary + # embeddings, which also span all heads, are cut to this rank's heads. The AdaLN modulations, scale-shift tables, + # input/output projections and caption projections stay replicated. + _tp_plan = { + **{ + f"transformer_blocks.*.{attention}.{name}": style + for attention in ( + "attn1", + "attn2", + "audio_attn1", + "audio_attn2", + "audio_to_video_attn", + "video_to_audio_attn", + ) + for name, style in ( + ("to_q", "colwise"), + ("to_k", "colwise"), + ("to_v", "colwise"), + ("to_gate_logits", Conditional("colwise")), + ("to_out.0", "rowwise"), + ("norm_q", "rmsnorm_across_heads"), + ("norm_k", "rmsnorm_across_heads"), + ) + }, + "transformer_blocks.*.ff.net.0.proj": "colwise", + "transformer_blocks.*.ff.net.2": "rowwise", + "transformer_blocks.*.audio_ff.net.0.proj": "colwise", + "transformer_blocks.*.audio_ff.net.2": "rowwise", + "rope": ShardOutput(), + "audio_rope": ShardOutput(), + "cross_attn_rope": ShardOutput(), + "cross_attn_audio_rope": ShardOutput(), + } _cp_plan = { "": { "hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False), diff --git a/src/diffusers/models/transformers/transformer_sana_wm_refiner.py b/src/diffusers/models/transformers/transformer_sana_wm_refiner.py index d47ef91bec64..9c21617c4d02 100644 --- a/src/diffusers/models/transformers/transformer_sana_wm_refiner.py +++ b/src/diffusers/models/transformers/transformer_sana_wm_refiner.py @@ -154,7 +154,7 @@ def __call__( if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) - attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) + attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])[:, :1] if encoder_hidden_states is None: encoder_hidden_states = hidden_states @@ -180,9 +180,9 @@ def __call__( query = apply_split_rotary_emb(query, query_rotary_emb) key = apply_split_rotary_emb(key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb) - query = query.unflatten(2, (attn.heads, -1)) - key = key.unflatten(2, (attn.heads, -1)) - value = value.unflatten(2, (attn.heads, -1)) + query = query.unflatten(2, (-1, attn.head_dim)) + key = key.unflatten(2, (-1, attn.head_dim)) + value = value.unflatten(2, (-1, attn.head_dim)) hidden_states = dispatch_attention_fn( query, @@ -198,7 +198,7 @@ def __call__( hidden_states = hidden_states.to(query.dtype) if attn.to_gate_logits is not None: - hidden_states = hidden_states.unflatten(2, (attn.heads, -1)) # [B, T, H, D] + hidden_states = hidden_states.unflatten(2, (-1, attn.head_dim)) # [B, T, H, D] # The factor of 2.0 is so that if the gates logits are zero-initialized the initial gates are all 1 gates = 2.0 * torch.sigmoid(gate_logits) # [B, T, H] hidden_states = hidden_states * gates.unsqueeze(-1) @@ -235,7 +235,7 @@ def __call__( if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) - attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) + attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])[:, :1] if encoder_hidden_states is None: encoder_hidden_states = hidden_states @@ -270,9 +270,9 @@ def __call__( key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb ) - query = query.unflatten(2, (attn.heads, -1)) - key = key.unflatten(2, (attn.heads, -1)) - value = value.unflatten(2, (attn.heads, -1)) + query = query.unflatten(2, (-1, attn.head_dim)) + key = key.unflatten(2, (-1, attn.head_dim)) + value = value.unflatten(2, (-1, attn.head_dim)) hidden_states = dispatch_attention_fn( query, @@ -292,7 +292,7 @@ def __call__( hidden_states = torch.lerp(value, hidden_states, perturbation_mask) if attn.to_gate_logits is not None: - hidden_states = hidden_states.unflatten(2, (attn.heads, -1)) # [B, T, H, D] + hidden_states = hidden_states.unflatten(2, (-1, attn.head_dim)) # [B, T, H, D] # The factor of 2.0 is so that if the gates logits are zero-initialized the initial gates are all 1 gates = 2.0 * torch.sigmoid(gate_logits) # [B, T, H] hidden_states = hidden_states * gates.unsqueeze(-1) @@ -424,6 +424,8 @@ def __init__( if rope_type not in ["interleaved", "split"]: raise ValueError(f"{rope_type=} not supported. Choose between 'interleaved' and 'split'.") self.rope_type = rope_type + # The dim of the cos/sin outputs that spans the attention heads, which tensor parallelism shards. + self._tp_output_shard_dim = -1 if rope_type == "interleaved" else 1 self.base_num_frames = base_num_frames self.num_attention_heads = num_attention_heads diff --git a/tests/models/transformers/test_models_transformer_ltx.py b/tests/models/transformers/test_models_transformer_ltx.py index a6faa9904386..92e180334682 100644 --- a/tests/models/transformers/test_models_transformer_ltx.py +++ b/tests/models/transformers/test_models_transformer_ltx.py @@ -24,6 +24,9 @@ MemoryTesterMixin, ModelTesterMixin, SingleFileTesterMixin, + TensorParallelNeuronTesterMixin, + TensorParallelTesterMixin, + TensorParallelTPUTesterMixin, TorchCompileTesterMixin, TrainingTesterMixin, ) @@ -65,8 +68,7 @@ def get_init_dict(self): "caption_channels": 16, } - def get_dummy_inputs(self) -> dict[str, torch.Tensor]: - batch_size = 2 + def get_dummy_inputs(self, batch_size: int = 2, device=torch_device) -> dict[str, torch.Tensor]: num_channels = 4 num_frames = 2 height = 16 @@ -78,13 +80,13 @@ def get_dummy_inputs(self) -> dict[str, torch.Tensor]: "hidden_states": randn_tensor( (batch_size, num_frames * height * width, num_channels), generator=self.generator, - device=torch_device, + device=device, ), "encoder_hidden_states": randn_tensor( - (batch_size, sequence_length, embedding_dim), generator=self.generator, device=torch_device + (batch_size, sequence_length, embedding_dim), generator=self.generator, device=device ), - "timestep": torch.randint(0, 1000, size=(batch_size,), generator=self.generator).to(torch_device), - "encoder_attention_mask": torch.ones((batch_size, sequence_length)).bool().to(torch_device), + "timestep": torch.randint(0, 1000, size=(batch_size,), generator=self.generator).to(device), + "encoder_attention_mask": torch.ones((batch_size, sequence_length)).bool().to(device), "num_frames": num_frames, "height": height, "width": width, @@ -95,6 +97,26 @@ class TestLTXTransformer(LTXTransformerTesterConfig, ModelTesterMixin): """Core model tests for LTX Video Transformer.""" +class TestLTXTransformerTensorParallel(LTXTransformerTesterConfig, TensorParallelTesterMixin): + """Tensor Parallel inference tests for LTX Video Transformer (CUDA/XPU multi-accelerator).""" + + +class TestLTXTransformerTensorParallelTPU(LTXTransformerTesterConfig, TensorParallelTPUTesterMixin): + """Tensor Parallel inference test for LTX Video Transformer on TPU.""" + + def get_init_dict(self): + # One head per chip, keeping the inner dims of the base config. + return { + **super().get_init_dict(), + "num_attention_heads": self.tp_world_size, + "attention_head_dim": 4, + } + + +class TestLTXTransformerTensorParallelNeuron(LTXTransformerTesterConfig, TensorParallelNeuronTesterMixin): + """Tensor Parallel inference test for LTX Video Transformer on AWS Neuron.""" + + class TestLTXTransformerMemory(LTXTransformerTesterConfig, MemoryTesterMixin): """Memory optimization tests for LTX Video Transformer.""" diff --git a/tests/models/transformers/test_models_transformer_ltx2.py b/tests/models/transformers/test_models_transformer_ltx2.py index 516c478df499..47b7cca7c8bc 100644 --- a/tests/models/transformers/test_models_transformer_ltx2.py +++ b/tests/models/transformers/test_models_transformer_ltx2.py @@ -25,6 +25,9 @@ LoraTesterMixin, MemoryTesterMixin, ModelTesterMixin, + TensorParallelNeuronTesterMixin, + TensorParallelTesterMixin, + TensorParallelTPUTesterMixin, TorchCompileTesterMixin, TrainingTesterMixin, ) @@ -74,8 +77,7 @@ def get_init_dict(self): "rope_double_precision": False, } - def get_dummy_inputs(self) -> dict[str, torch.Tensor]: - batch_size = 2 + def get_dummy_inputs(self, batch_size: int = 2, device=torch_device) -> dict[str, torch.Tensor]: num_frames = 2 num_channels = 4 height = 16 @@ -90,21 +92,21 @@ def get_dummy_inputs(self) -> dict[str, torch.Tensor]: "hidden_states": randn_tensor( (batch_size, num_frames * height * width, num_channels), generator=self.generator, - device=torch_device, + device=device, ), "audio_hidden_states": randn_tensor( (batch_size, audio_num_frames, audio_num_channels * num_mel_bins), generator=self.generator, - device=torch_device, + device=device, ), "encoder_hidden_states": randn_tensor( - (batch_size, sequence_length, embedding_dim), generator=self.generator, device=torch_device + (batch_size, sequence_length, embedding_dim), generator=self.generator, device=device ), "audio_encoder_hidden_states": randn_tensor( - (batch_size, sequence_length, embedding_dim), generator=self.generator, device=torch_device + (batch_size, sequence_length, embedding_dim), generator=self.generator, device=device ), - "timestep": (randn_tensor((batch_size,), generator=self.generator, device=torch_device).abs() * 1000), - "encoder_attention_mask": torch.ones((batch_size, sequence_length)).bool().to(torch_device), + "timestep": (randn_tensor((batch_size,), generator=self.generator, device=device).abs() * 1000), + "encoder_attention_mask": torch.ones((batch_size, sequence_length)).bool().to(device), "num_frames": num_frames, "height": height, "width": width, @@ -159,6 +161,57 @@ def test_keyframes_mask_is_ignored_without_the_embedding(self): assert torch.allclose(without_mask, with_mask, atol=1e-5) +class TestLTX2TransformerTensorParallel(LTX2TransformerTesterConfig, TensorParallelTesterMixin): + """Tensor Parallel inference tests for LTX-2 Transformer (CUDA/XPU multi-accelerator).""" + + +class TestLTX2TransformerTensorParallelTPU(LTX2TransformerTesterConfig, TensorParallelTPUTesterMixin): + """Tensor Parallel inference test for LTX-2 Transformer on TPU.""" + + def get_init_dict(self): + # One head per chip, keeping the inner dims of the base config. + return { + **super().get_init_dict(), + "num_attention_heads": self.tp_world_size, + "attention_head_dim": 4, + "audio_num_attention_heads": self.tp_world_size, + "audio_attention_head_dim": 2, + } + + +class TestLTX2TransformerTensorParallelPlan(LTX2TransformerTesterConfig): + """Checks of the LTX-2 `_tp_plan` that need no accelerator.""" + + def test_shard_specs(self): + from diffusers.hooks.tensor_parallel import TPShardSpec, resolve_tp_shard_specs + + model = self.model_class(**self.get_init_dict()) + specs = resolve_tp_shard_specs(model, self.model_class._tp_plan, 2) + + for attention in ("attn1", "audio_attn1", "audio_to_video_attn"): + prefix = f"transformer_blocks.0.{attention}" + inner_dim = getattr(model.transformer_blocks[0], attention).inner_dim + assert specs[f"{prefix}.to_q.weight"] == TPShardSpec(0, [inner_dim]) + assert specs[f"{prefix}.to_out.0.weight"] == TPShardSpec(1, [inner_dim]) + # The QK-norms are sharded like the projections that feed them. + assert specs[f"{prefix}.norm_q.weight"] == TPShardSpec(0, [inner_dim]) + # The rotary embeddings have no parameters to place. + assert not any(name.startswith("rope.") for name in specs) + + def test_uneven_audio_heads_raises(self): + from diffusers.hooks.tensor_parallel import resolve_tp_shard_specs + + # The audio inner dim (8) divides by 4, but its 2 heads do not. + init_dict = {**self.get_init_dict(), "num_attention_heads": 4, "attention_head_dim": 4} + model = self.model_class(**init_dict) + with pytest.raises(ValueError, match="audio_attn1.to_q.*2 heads"): + resolve_tp_shard_specs(model, self.model_class._tp_plan, 4) + + +class TestLTX2TransformerTensorParallelNeuron(LTX2TransformerTesterConfig, TensorParallelNeuronTesterMixin): + """Tensor Parallel inference test for LTX-2 Transformer on AWS Neuron.""" + + class TestLTX2TransformerMemory(LTX2TransformerTesterConfig, MemoryTesterMixin): """Memory optimization tests for LTX2 Video Transformer."""