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
14 changes: 14 additions & 0 deletions docs/source/en/optimization/tensor_parallelism.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,20 @@ 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`.

### Packed gated experts

Use `"packed_gated_experts"` on an expert module with two bias-free projections stored as packed weight parameters. `gate_up_proj` has shape `[num_experts, hidden_size, 2 * intermediate_size]`, with the gate channels followed by the up channels. `down_proj` has shape `[num_experts, intermediate_size, hidden_size]`. The TP degree must divide `intermediate_size`.

All ranks process the same routed tokens. Each rank takes a different slice of the intermediate channels, pairing the corresponding gate and up channels with the same input channels of the down projection. The expert computes its own elementwise gate activation on those local shards. After the down projection, PyTorch sums the partial outputs across ranks.

NucleusMoE-Image uses this plan entry because only some blocks contain routed experts.

```py
_tp_plan = {"transformer_blocks.*.img_mlp.experts": Conditional("packed_gated_experts")}
```

The released NucleusMoE-Image transformer supports TP2 and TP4 with attention, routing, and its shared expert replicated.

### 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"`.
Expand Down
49 changes: 36 additions & 13 deletions src/diffusers/hooks/tensor_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ class TPShardSpec(NamedTuple):
block_sizes: "list[int] | None"


def _packed_gated_expert_specs(module) -> dict[str, TPShardSpec]:
"""Shard matching intermediate channels of the packed gate, up, and down projections for every expert."""
width = module.down_proj.shape[1]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What if the module doesn't have down_proj? I think we should validate better and early.

return {"gate_up_proj": TPShardSpec(2, [width, width]), "down_proj": TPShardSpec(1, [width])}


def _local_shard(tensor, dim: int, block_sizes: "list[int]", tp_mesh) -> torch.Tensor:
"""Extract this rank's slice of `tensor` along `dim`.

Expand Down Expand Up @@ -119,8 +125,8 @@ def _local_shard(tensor, dim: int, block_sizes: "list[int]", tp_mesh) -> torch.T
def resolve_tp_shard_specs(model: torch.nn.Module, tp_plan: dict, tp_degree: int) -> "dict[str, TPShardSpec]":
"""Map every `_tp_plan`-covered parameter name to its `TPShardSpec`.

Parameters absent from the result are untouched by tensor parallelism. Both `weight` and `bias` of each planned
module are covered.
A planned linear contributes its weight and optional bias. A packed gated expert module contributes its
`gate_up_proj` and `down_proj` parameters. Parameters absent from the result are untouched by tensor parallelism.

Raises if any sharded block is not divisible by `tp_degree`, so an uneven split is rejected before any weight is
read or sharded. Left to `Shard`, it would give the trailing ranks a smaller slice and break the paired
Expand All @@ -144,6 +150,11 @@ def resolve_tp_shard_specs(model: torch.nn.Module, tp_plan: dict, tp_degree: int
submodule = getattr(submodule, atom)
path = f"{prefix}.{relative_path}" if prefix else relative_path

if style == "packed_gated_experts":
for name, spec in _packed_gated_expert_specs(submodule).items():
specs[f"{path}.{name}"] = spec
continue

# `_tp_packed_*_blocks` hold absolute sizes rather than proportions; that works because
# they sum to the full dimension, so `_blocks_to_block_sizes` computes `unit == 1`.
if style == "colwise":
Expand All @@ -164,8 +175,8 @@ def resolve_tp_shard_specs(model: torch.nn.Module, tp_plan: dict, tp_degree: int
else:
raise ValueError(
f"Unsupported tensor-parallel style '{style}' for '{path}'. "
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or "
f"PackedRowwiseParallel."
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', 'packed_gated_experts', "
f"PackedColwiseParallel, or PackedRowwiseParallel."
)

specs[f"{path}.weight"] = weight_spec
Expand Down Expand Up @@ -285,8 +296,8 @@ def _styles(relative_plan: dict) -> dict:
`PackedRowwiseParallel` marker instances. Returns `{relative_path: ColwiseParallel() | RowwiseParallel() | <packed
impl>}`. 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
from torch.distributed.tensor import Partial, Replicate, distribute_tensor
from torch.distributed.tensor.parallel import ColwiseParallel, PrepareModuleOutput, RowwiseParallel

def _make_packed_col(marker: PackedColwiseParallel) -> ColwiseParallel:
class _PackedColwiseImpl(ColwiseParallel):
Expand Down Expand Up @@ -318,6 +329,14 @@ def _partition_linear_fn(self, name, module, device_mesh):

return _PackedRowwiseImpl()

class _PackedGatedExperts(PrepareModuleOutput):
def _apply(self, module, device_mesh):
for name, spec in _packed_gated_expert_specs(module).items():
param = getattr(module, name)
local = _shard_packed_param(param, spec.dim, spec.block_sizes, device_mesh, self.src_data_rank)
module.register_parameter(name, local)
return super()._apply(module, device_mesh)

resolved = {}
for path, style in relative_plan.items():
if style == "colwise":
Expand All @@ -330,15 +349,17 @@ def _partition_linear_fn(self, name, module, device_mesh):
# the timestep embedding (MiniMax-H3's `adaln_proj.linear`), or an output projection after a gathered
# QK-norm. Same as the transformers style of the same name.
resolved[path] = RowwiseParallel(input_layouts=Replicate())
elif style == "packed_gated_experts":
resolved[path] = _PackedGatedExperts(output_layouts=Partial(), desired_output_layouts=Replicate())
elif isinstance(style, PackedColwiseParallel):
resolved[path] = _make_packed_col(style)
elif isinstance(style, PackedRowwiseParallel):
resolved[path] = _make_packed_row(style)
else:
raise ValueError(
f"Unsupported tensor-parallel style '{style}' for '{path}'. "
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or "
f"PackedRowwiseParallel."
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', 'packed_gated_experts', "
f"PackedColwiseParallel, or PackedRowwiseParallel."
)
return resolved

Expand All @@ -348,14 +369,14 @@ def _hooks_only_styles(relative_plan: dict) -> dict:

Used when the caller has already placed every planned parameter as a sharded `DTensor`. `parallelize_module` then
runs only to register the forward input/output hooks; `_partition_linear_fn` must not re-partition. Packed and
plain styles share hook behaviour, so both collapse onto the two styles here.
plain linear projections share hooks. Packed gated experts reduce the partial output of the expert module.

Note this is not purely additive: `distribute_module` still replicates any *remaining* plain parameter of the
targeted module into a `Replicate()` DTensor via a broadcast. Callers should therefore place every planned
parameter themselves, and must ensure none is left on `meta` — the broadcast would be issued on a meta tensor.
"""
from torch.distributed.tensor import Replicate
from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel
from torch.distributed.tensor import Partial, Replicate
from torch.distributed.tensor.parallel import ColwiseParallel, PrepareModuleOutput, RowwiseParallel

class _NoPartitionColwise(ColwiseParallel):
def _partition_linear_fn(self, name, module, device_mesh):
Expand All @@ -371,13 +392,15 @@ def _partition_linear_fn(self, name, module, device_mesh):
resolved[path] = _NoPartitionColwise()
elif style == "rowwise" or isinstance(style, PackedRowwiseParallel):
resolved[path] = _NoPartitionRowwise()
elif style == "packed_gated_experts":
resolved[path] = PrepareModuleOutput(output_layouts=Partial(), desired_output_layouts=Replicate())
elif style == "rowwise_split_input":
resolved[path] = _NoPartitionRowwise(input_layouts=Replicate())
else:
raise ValueError(
f"Unsupported tensor-parallel style '{style}' for '{path}'. "
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or "
f"PackedRowwiseParallel."
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', 'packed_gated_experts', "
f"PackedColwiseParallel, or PackedRowwiseParallel."
)
return resolved

Expand Down
40 changes: 32 additions & 8 deletions src/diffusers/models/transformers/transformer_nucleusmoe_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributed.tensor import DTensor

from ...configuration_utils import ConfigMixin, register_to_config
from ...loaders import FromOriginalModelMixin, PeftAdapterMixin
from ...utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
from .._modeling_parallel import Conditional
from ..attention import AttentionMixin, FeedForward
from ..attention_dispatch import dispatch_attention_fn
from ..attention_processor import Attention
Expand Down Expand Up @@ -394,6 +396,11 @@ def __init__(
self.gate_up_proj = nn.Parameter(torch.empty(num_experts, hidden_size, 2 * moe_intermediate_dim))
self.down_proj = nn.Parameter(torch.empty(num_experts, moe_intermediate_dim, hidden_size))

def _local_weights(self) -> tuple[torch.Tensor, torch.Tensor]:
if isinstance(self.gate_up_proj, DTensor):
return self.gate_up_proj.to_local(), self.down_proj.to_local()
return self.gate_up_proj, self.down_proj

def _run_experts_for_loop(
self,
x: torch.Tensor,
Expand Down Expand Up @@ -444,11 +451,12 @@ def _run_experts_for_loop(
dim=0,
)

gate_up_proj, down_proj = self._local_weights()
expert_outputs = []
for expert_idx, x_expert in enumerate(x_per_expert):
gate_up = torch.matmul(x_expert, self.gate_up_proj[expert_idx])
gate_up = torch.matmul(x_expert, gate_up_proj[expert_idx])
gate, up = gate_up.chunk(2, dim=-1)
out_expert = torch.matmul(F.silu(gate) * up, self.down_proj[expert_idx])
out_expert = torch.matmul(F.silu(gate) * up, down_proj[expert_idx])
expert_outputs.append(out_expert)

# Concatenate real-token outputs, then re-append zero rows for the padding.
Expand Down Expand Up @@ -489,9 +497,10 @@ def _run_experts_grouped_mm(
"""
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)

gate_up = F.grouped_mm(x, self.gate_up_proj, offs=offsets)
gate_up_proj, down_proj = self._local_weights()
gate_up = F.grouped_mm(x, gate_up_proj, offs=offsets)
gate, up = gate_up.chunk(2, dim=-1)
out = F.grouped_mm(F.silu(gate) * up, self.down_proj, offs=offsets)
out = F.grouped_mm(F.silu(gate) * up, down_proj, offs=offsets)

return out.type_as(x)

Expand Down Expand Up @@ -580,8 +589,18 @@ def forward(
global_token_indices = (batch_offsets + top_indices).transpose(0, 1).reshape(self.num_experts, -1).reshape(-1)
gating_flat = gating.transpose(0, 1).reshape(self.num_experts, -1).reshape(-1)

token_score_sums = torch.zeros(bs * slen, device=hidden_states.device, dtype=gating_flat.dtype)
token_score_sums.scatter_add_(0, global_token_indices, gating_flat)
sharded_experts = isinstance(self.experts.gate_up_proj, DTensor)
if sharded_experts:
# Repeated token indices must accumulate in the same order on every rank,
# otherwise the next block can route different tokens into the same collective.
indices, order = global_token_indices.sort(stable=True)
offsets = torch.searchsorted(indices, torch.arange(bs * slen + 1, device=indices.device))
token_score_sums = torch.segment_reduce(gating_flat[order].float(), "sum", offsets=offsets).to(
gating_flat.dtype
)
else:
token_score_sums = gating_flat.new_zeros(bs * slen)
token_score_sums.scatter_add_(0, global_token_indices, gating_flat)
gating_flat = gating_flat / (token_score_sums[global_token_indices] + 1e-12)
gating_flat = gating_flat * self.route_scale

Expand All @@ -600,8 +619,12 @@ def forward(

out = self.shared_expert(hidden_states).reshape(bs * slen, dim)

scatter_idx = global_token_indices.reshape(-1, 1).expand(-1, dim)
out = out.scatter_add(dim=0, index=scatter_idx, src=routed_output)
if sharded_experts:
routed_sum = torch.segment_reduce(routed_output[order].float(), "sum", offsets=offsets)
out = (out.float() + routed_sum).to(hidden_states.dtype)
else:
scatter_idx = global_token_indices.reshape(-1, 1).expand(-1, dim)
out = out.scatter_add(dim=0, index=scatter_idx, src=routed_output)
out = out.reshape(bs, slen, dim)

return out
Expand Down Expand Up @@ -770,6 +793,7 @@ class NucleusMoEImageTransformer2DModel(
Scaling factor applied to routing weights.
"""

_tp_plan = {"transformer_blocks.*.img_mlp.experts": Conditional("packed_gated_experts")}
_supports_gradient_checkpointing = True
_no_split_modules = ["NucleusMoEImageTransformerBlock"]
_skip_layerwise_casting_patterns = ["pos_embed", "norm"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@
# limitations under the License.


import pytest
import torch

from diffusers import NucleusMoEImageTransformer2DModel
from diffusers.hooks.tensor_parallel import TPShardSpec, resolve_tp_shard_specs
from diffusers.models.transformers.transformer_nucleusmoe_image import SwiGLUExperts
from diffusers.utils.torch_utils import randn_tensor

from ...testing_utils import enable_full_determinism, torch_device
Expand All @@ -26,6 +29,7 @@
LoraTesterMixin,
MemoryTesterMixin,
ModelTesterMixin,
TensorParallelTesterMixin,
TorchCompileTesterMixin,
TrainingTesterMixin,
)
Expand Down Expand Up @@ -73,8 +77,7 @@ def get_init_dict(self) -> dict:
"capacity_factors": [8.0, 8.0],
}

def get_dummy_inputs(self) -> dict:
batch_size = 1
def get_dummy_inputs(self, batch_size=1) -> dict:
in_channels = 16
joint_attention_dim = 16
height = width = 4
Expand Down Expand Up @@ -128,6 +131,41 @@ def test_without_attention_mask(self):
assert output.sample.shape[1] == inputs["hidden_states"].shape[1]


class TestNucleusMoEImageTransformerTensorParallel(NucleusMoEImageTransformerTesterConfig, TensorParallelTesterMixin):
def get_init_dict(self):
return {
**super().get_init_dict(),
"moe_enabled": True,
"dense_moe_strategy": "leave_first_block_dense",
"num_experts": 4,
"moe_intermediate_dim": 32,
"capacity_factors": [0, 2],
}

def test_packed_expert_shard_specs(self):
with torch.device("meta"):
model = self.model_class(**self.get_init_dict())
prefix = "transformer_blocks.1.img_mlp.experts"
assert resolve_tp_shard_specs(model, model._tp_plan, tp_degree=4) == {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this supposed to run on 4 GPUs?

f"{prefix}.gate_up_proj": TPShardSpec(2, [32, 32]),
f"{prefix}.down_proj": TPShardSpec(1, [32]),
}
with pytest.raises(ValueError, match="not divisible by 3"):
resolve_tp_shard_specs(model, model._tp_plan, tp_degree=3)

@pytest.fixture(autouse=True)
def initialize_experts(self, monkeypatch):
# The checkpoint normally supplies these two torch.empty parameters.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this could be confusing. It's not the checkpoint that supplies torch.empty, it's the initialization block.

original_init = SwiGLUExperts.__init__

def init(module, *args, **kwargs):
original_init(module, *args, **kwargs)
torch.nn.init.normal_(module.gate_up_proj, std=0.1)
torch.nn.init.normal_(module.down_proj, std=0.1)

monkeypatch.setattr(SwiGLUExperts, "__init__", init)


class TestNucleusMoEImageTransformerMemory(NucleusMoEImageTransformerTesterConfig, MemoryTesterMixin):
"""Memory optimization tests for NucleusMoE Image Transformer."""

Expand Down