Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions docs/source/en/optimization/tensor_parallelism.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
179 changes: 160 additions & 19 deletions src/diffusers/hooks/tensor_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand All @@ -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("."):
Expand Down Expand Up @@ -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() | <packed
impl>}`. 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
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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
Expand Down
32 changes: 28 additions & 4 deletions src/diffusers/models/transformers/transformer_ltx.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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),
Expand Down
Loading
Loading