From dfbee01234080fdaa8d1c9f892346a837582ebf9 Mon Sep 17 00:00:00 2001 From: Sayak Paul Date: Fri, 4 Dec 2026 14:22:37 +0000 Subject: [PATCH] remove modeling specific changes and move to hooks --- .../en/optimization/tensor_parallelism.md | 9 +- src/diffusers/hooks/tensor_parallel.py | 92 +++++++++++++++---- .../transformer_nucleusmoe_image.py | 43 +++------ 3 files changed, 94 insertions(+), 50 deletions(-) diff --git a/docs/source/en/optimization/tensor_parallelism.md b/docs/source/en/optimization/tensor_parallelism.md index 8e9eb4d47dfc..f0ab07559b8d 100644 --- a/docs/source/en/optimization/tensor_parallelism.md +++ b/docs/source/en/optimization/tensor_parallelism.md @@ -145,10 +145,15 @@ Use `"packed_gated_experts"` on an expert module with two bias-free projections 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. +The ranks must also pick the same tokens for each expert, or the summed outputs belong to different tokens. Use `"rank0_output"` on the router, the layer whose output decides which tokens each expert gets. Its weights stay replicated, and every rank continues with rank 0's output. + +NucleusMoE-Image wraps both entries in `Conditional` because only some blocks contain routed experts. ```py -_tp_plan = {"transformer_blocks.*.img_mlp.experts": Conditional("packed_gated_experts")} +_tp_plan = { + "transformer_blocks.*.img_mlp.gate": Conditional("rank0_output"), + "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. diff --git a/src/diffusers/hooks/tensor_parallel.py b/src/diffusers/hooks/tensor_parallel.py index 76d6d7730c24..03088a2b746e 100644 --- a/src/diffusers/hooks/tensor_parallel.py +++ b/src/diffusers/hooks/tensor_parallel.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import functools from typing import NamedTuple import torch @@ -98,6 +99,65 @@ def _packed_gated_expert_specs(module) -> dict[str, TPShardSpec]: return {"gate_up_proj": TPShardSpec(2, [width, width]), "down_proj": TPShardSpec(1, [width])} +def _forward_on_local_shards(module: torch.nn.Module, names: "list[str]") -> None: + """Run `module.forward` on this rank's local shard of each parameter in `names`. + + For a module whose forward cannot run on `DTensor` parameters. They stay `DTensor`s outside the call. + """ + forward = module.forward + + @functools.wraps(forward) + def forward_on_local_shards(*args, **kwargs): + sharded = {name: module._parameters[name] for name in names} + module._parameters.update({name: param.to_local() for name, param in sharded.items()}) + try: + return forward(*args, **kwargs) + finally: + module._parameters.update(sharded) + + module.forward = forward_on_local_shards + + +def _packed_gated_experts_style(partition: bool): + """The `parallelize_module` style of `"packed_gated_experts"`. + + The expert module runs on its local shards and its partial output is summed across ranks. `partition=False` skips + the sharding, for parameters that are already placed as `DTensor` shards. + """ + from torch.distributed.tensor import Partial, Replicate + from torch.distributed.tensor.parallel import PrepareModuleOutput + + class _PackedGatedExperts(PrepareModuleOutput): + def _apply(self, module, device_mesh): + specs = _packed_gated_expert_specs(module) + if partition: + for name, spec in specs.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) + _forward_on_local_shards(module, list(specs)) + return super()._apply(module, device_mesh) + + return _PackedGatedExperts(output_layouts=Partial(), desired_output_layouts=Replicate()) + + +def _rank0_output_style(): + """The `parallelize_module` style of `"rank0_output"`: every rank continues with rank 0's output. + + The other ranks contribute zeros to the all-reduce, so the result is bitwise the same on every rank. + """ + from torch.distributed.tensor import Partial, Replicate + from torch.distributed.tensor.parallel import PrepareModuleOutput + + class _Rank0Output(PrepareModuleOutput): + def _prepare_out_fn(self, outputs, device_mesh): + if device_mesh.get_local_rank() != 0: + outputs = torch.zeros_like(outputs) + return super()._prepare_out_fn(outputs, device_mesh) + + return _Rank0Output(output_layouts=Partial(), desired_output_layouts=Replicate()) + + def _local_shard(tensor, dim: int, block_sizes: "list[int]", tp_mesh) -> torch.Tensor: """Extract this rank's slice of `tensor` along `dim`. @@ -150,6 +210,8 @@ 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 == "rank0_output": + continue if style == "packed_gated_experts": for name, spec in _packed_gated_expert_specs(submodule).items(): specs[f"{path}.{name}"] = spec @@ -175,7 +237,7 @@ 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', 'packed_gated_experts', " + f"Expected 'colwise', 'rowwise', 'rowwise_split_input', 'packed_gated_experts', 'rank0_output', " f"PackedColwiseParallel, or PackedRowwiseParallel." ) @@ -296,8 +358,8 @@ def _styles(relative_plan: dict) -> dict: `PackedRowwiseParallel` marker instances. Returns `{relative_path: ColwiseParallel() | RowwiseParallel() | }`. Divisibility by the TP degree is checked earlier, by `resolve_tp_shard_specs`. """ - from torch.distributed.tensor import Partial, Replicate, distribute_tensor - from torch.distributed.tensor.parallel import ColwiseParallel, PrepareModuleOutput, RowwiseParallel + from torch.distributed.tensor import Replicate, distribute_tensor + from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel def _make_packed_col(marker: PackedColwiseParallel) -> ColwiseParallel: class _PackedColwiseImpl(ColwiseParallel): @@ -329,14 +391,6 @@ 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": @@ -350,7 +404,9 @@ def _apply(self, module, device_mesh): # 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()) + resolved[path] = _packed_gated_experts_style(partition=True) + elif style == "rank0_output": + resolved[path] = _rank0_output_style() elif isinstance(style, PackedColwiseParallel): resolved[path] = _make_packed_col(style) elif isinstance(style, PackedRowwiseParallel): @@ -358,7 +414,7 @@ def _apply(self, module, device_mesh): else: raise ValueError( f"Unsupported tensor-parallel style '{style}' for '{path}'. " - f"Expected 'colwise', 'rowwise', 'rowwise_split_input', 'packed_gated_experts', " + f"Expected 'colwise', 'rowwise', 'rowwise_split_input', 'packed_gated_experts', 'rank0_output', " f"PackedColwiseParallel, or PackedRowwiseParallel." ) return resolved @@ -375,8 +431,8 @@ def _hooks_only_styles(relative_plan: dict) -> dict: 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 Partial, Replicate - from torch.distributed.tensor.parallel import ColwiseParallel, PrepareModuleOutput, RowwiseParallel + from torch.distributed.tensor import Replicate + from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel class _NoPartitionColwise(ColwiseParallel): def _partition_linear_fn(self, name, module, device_mesh): @@ -393,13 +449,15 @@ def _partition_linear_fn(self, name, module, device_mesh): 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()) + resolved[path] = _packed_gated_experts_style(partition=False) + elif style == "rank0_output": + resolved[path] = _rank0_output_style() 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', 'packed_gated_experts', " + f"Expected 'colwise', 'rowwise', 'rowwise_split_input', 'packed_gated_experts', 'rank0_output', " f"PackedColwiseParallel, or PackedRowwiseParallel." ) return resolved diff --git a/src/diffusers/models/transformers/transformer_nucleusmoe_image.py b/src/diffusers/models/transformers/transformer_nucleusmoe_image.py index f44224d3f0d4..65e5cdbc078f 100644 --- a/src/diffusers/models/transformers/transformer_nucleusmoe_image.py +++ b/src/diffusers/models/transformers/transformer_nucleusmoe_image.py @@ -19,7 +19,6 @@ 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 @@ -396,11 +395,6 @@ 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, @@ -451,12 +445,11 @@ 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, gate_up_proj[expert_idx]) + gate_up = torch.matmul(x_expert, self.gate_up_proj[expert_idx]) gate, up = gate_up.chunk(2, dim=-1) - out_expert = torch.matmul(F.silu(gate) * up, down_proj[expert_idx]) + out_expert = torch.matmul(F.silu(gate) * up, self.down_proj[expert_idx]) expert_outputs.append(out_expert) # Concatenate real-token outputs, then re-append zero rows for the padding. @@ -497,10 +490,9 @@ def _run_experts_grouped_mm( """ offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32) - gate_up_proj, down_proj = self._local_weights() - gate_up = F.grouped_mm(x, gate_up_proj, offs=offsets) + gate_up = F.grouped_mm(x, self.gate_up_proj, offs=offsets) gate, up = gate_up.chunk(2, dim=-1) - out = F.grouped_mm(F.silu(gate) * up, down_proj, offs=offsets) + out = F.grouped_mm(F.silu(gate) * up, self.down_proj, offs=offsets) return out.type_as(x) @@ -589,18 +581,8 @@ 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) - 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) + 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) gating_flat = gating_flat / (token_score_sums[global_token_indices] + 1e-12) gating_flat = gating_flat * self.route_scale @@ -619,12 +601,8 @@ def forward( out = self.shared_expert(hidden_states).reshape(bs * slen, dim) - 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) + 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 @@ -793,7 +771,10 @@ class NucleusMoEImageTransformer2DModel( Scaling factor applied to routing weights. """ - _tp_plan = {"transformer_blocks.*.img_mlp.experts": Conditional("packed_gated_experts")} + _tp_plan = { + "transformer_blocks.*.img_mlp.gate": Conditional("rank0_output"), + "transformer_blocks.*.img_mlp.experts": Conditional("packed_gated_experts"), + } _supports_gradient_checkpointing = True _no_split_modules = ["NucleusMoEImageTransformerBlock"] _skip_layerwise_casting_patterns = ["pos_embed", "norm"]