Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
764e7c8
Add tensor-parallel support for MiniMax-H3
JingyaHuang Aug 21, 2026
58d9b51
Shard MiniMax-H3's adaln_proj to fit tensor parallelism on one device
JingyaHuang Aug 21, 2026
c766b88
Build MiniMax-H3's row timestep plan on CPU, as its caller expects
JingyaHuang Aug 21, 2026
4162784
feat:combine tp+cp
JingyaHuang Aug 27, 2026
7f649f9
Allow tensor parallelism and context parallelism in one ParallelConfig
whn09 Sep 7, 2026
673a3f1
feat: validate the support on TPU
JingyaHuang Sep 30, 2026
3db653d
fix: put tp first in the combined TP+CP mesh
JingyaHuang Oct 8, 2026
9c0f7aa
fix: style
JingyaHuang Oct 8, 2026
bbc55a7
fix: apply context parallelism on the sharded-load path
JingyaHuang Oct 9, 2026
6ce34c7
revert: attention head padding
JingyaHuang Oct 9, 2026
986ea9a
revert: drop the Neuron all-gather padding and restore the TPU pre-sh…
JingyaHuang Oct 10, 2026
6845f33
refactor: share the CPU pre-shard path between Neuron and TPU tensor …
JingyaHuang Oct 10, 2026
e8a38d3
Merge branch 'main' into add-h3-tp-support
JingyaHuang Oct 13, 2026
2590829
fix: new device count API for TPU since deprecation
JingyaHuang Oct 13, 2026
ce4198a
fix: pad uneven all-gathers on Neuron and TPU in _all_gather_anything
JingyaHuang Oct 13, 2026
d2c362e
Merge branch 'main' into add-h3-tp-support
JingyaHuang Oct 14, 2026
3cd26a9
Merge branch 'main' into add-h3-tp-support
JingyaHuang Oct 14, 2026
6b3b3e8
Merge branch 'main' into add-h3-tp-support
JingyaHuang Oct 14, 2026
cd61166
fix: fall back to one device when no accelerator is present
JingyaHuang Oct 14, 2026
cc85110
Move TP+CP composition to #14725
JingyaHuang Oct 14, 2026
b1076e6
Merge branch 'main' into add-h3-tp-support
JingyaHuang Oct 15, 2026
8526d94
review: use `config._device` for the Neuron TP device
JingyaHuang Oct 15, 2026
ed452ef
review: replace ReplicatedInputRowwiseParallel with a "rowwise_split_…
JingyaHuang Oct 15, 2026
bc35ec2
review: explain when to use "rowwise_split_input"
JingyaHuang Oct 15, 2026
3ea9cc5
Merge branch 'main' into add-h3-tp-support
JingyaHuang Oct 22, 2026
660bb6d
feat:shard tensor-parallel weights locally on every device
JingyaHuang Oct 26, 2026
82e45d4
Merge branch 'main' into add-h3-tp-support
JingyaHuang Oct 27, 2026
dd54cfb
Merge branch 'main' into add-h3-tp-support
sayakpaul Oct 27, 2026
9ec4666
doc: improve the explanation of rowwise_split_input
JingyaHuang Oct 28, 2026
d13196b
review: remove useless zero division prevention
JingyaHuang Oct 28, 2026
ff24da5
review: simplify the docstring
JingyaHuang Oct 28, 2026
63732ec
revert: Restore standard TP sharding and isolate the Neuron workaround
JingyaHuang Nov 2, 2026
8e2fa1d
revert: no refactoring of in-memory sharding
JingyaHuang Nov 2, 2026
669f503
Merge branch 'main' into add-h3-tp-support
JingyaHuang Nov 2, 2026
4d13666
Merge branch 'main' into add-h3-tp-support
JingyaHuang Nov 4, 2026
b680a25
revert: keep the in-memory TP path as on main
JingyaHuang Nov 4, 2026
39bcfef
style: pika
JingyaHuang Nov 4, 2026
8b78dfe
Merge branch 'add-h3-tp-support' of github.com:JingyaHuang/diffusers …
JingyaHuang Nov 4, 2026
8c74bb1
style: make fix-copies
JingyaHuang Nov 4, 2026
3dc0194
Merge branch 'main' into add-h3-tp-support
sayakpaul Nov 5, 2026
510487e
Merge branch 'main' into add-h3-tp-support
sayakpaul Nov 5, 2026
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
3 changes: 2 additions & 1 deletion docs/source/en/training/distributed_inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ torchrun --nproc-per-node 4 tensor_parallel_flux.py
>
> Combining tensor parallelism with quantization, offloading, or LoRA adapters isn't supported yet either, so those raise however the model is sharded.
>
> To shard a model that is already in memory, call [`~ModelMixin.enable_parallelism`] with the same config instead — that loads everything first and reshards it, so it costs full checkpoint memory on every rank.
> We recommend loading tensor-parallel models this way. You can also shard a model that is already in memory by calling [`~ModelMixin.enable_parallelism`] with the same config, but that loads everything first and reshards it, so it costs full checkpoint memory on every rank.
Saving a tensor-parallel model isn't supported yet, and [`~ModelMixin.save_pretrained`] raises on one. Save the model before sharding it.

Expand All @@ -511,6 +511,7 @@ Each key may contain **at most one `*`**, and the prefix before it must resolve
|---|---|---|---|
| `"colwise"` | output features (`weight` dim 0) | computes a slice of the output | `to_q`, `to_k`, `to_v`, FFN in-projection |
| `"rowwise"` | input features (`weight` dim 1) | computes a partial sum | `to_out.0`, FFN out-projection |
| `"rowwise_split_input"` | input features (`weight` dim 1) | computes a partial result using its slice of the input and weights; `AllReduce` adds these results so every rank gets all output features | a standalone projection that reads a replicated activation, e.g. an AdaLN modulation projection off the timestep embedding |

Always pair them in that order. A `"colwise"` projection leaves its output sharded, the following `"rowwise"` projection consumes that shard directly, and a single `AllReduce` at the block boundary reconstructs the result. Sharding the pair any other way forces a gather in the middle and communicates far more.

Expand Down
27 changes: 20 additions & 7 deletions src/diffusers/hooks/tensor_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ def resolve_tp_shard_specs(model: torch.nn.Module, tp_plan: dict, tp_degree: int
if style == "colwise":
weight_spec = TPShardSpec(0, [submodule.weight.shape[0]])
bias_spec = weight_spec
elif style == "rowwise":
elif style in ("rowwise", "rowwise_split_input"):
# Both place the weight the same way; they differ only in the forward input/output hooks.
weight_spec = TPShardSpec(1, [submodule.weight.shape[1]])
bias_spec = TPShardSpec(None, None)
elif isinstance(style, PackedColwiseParallel):
Expand All @@ -163,7 +164,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', PackedColwiseParallel, or PackedRowwiseParallel."
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or "
f"PackedRowwiseParallel."
)

specs[f"{path}.weight"] = weight_spec
Expand Down Expand Up @@ -242,9 +244,9 @@ def _shard_packed_param(param, dim: int, blocks: "list[int]", device_mesh, src_d
def _styles(relative_plan: dict) -> dict:
"""Map a `{relative_path: style}` plan to `parallelize_module` style instances.
Values may be plain strings (`"colwise"` / `"rowwise"`) 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"`) 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`.
"""
from torch.distributed.tensor import Replicate, distribute_tensor
from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel
Expand Down Expand Up @@ -285,14 +287,21 @@ def _partition_linear_fn(self, name, module, device_mesh):
resolved[path] = ColwiseParallel()
elif style == "rowwise":
resolved[path] = RowwiseParallel()
elif style == "rowwise_split_input":
# Same weight split as "rowwise", for a Linear whose input arrives whole instead of split by a "colwise"
# layer before it; each rank slices its own columns locally. E.g. an AdaLN modulation projection reading
# 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 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', PackedColwiseParallel, or PackedRowwiseParallel."
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or "
f"PackedRowwiseParallel."
)
return resolved

Expand All @@ -308,6 +317,7 @@ 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 Replicate
from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel

class _NoPartitionColwise(ColwiseParallel):
Expand All @@ -324,10 +334,13 @@ def _partition_linear_fn(self, name, module, device_mesh):
resolved[path] = _NoPartitionColwise()
elif style == "rowwise" or isinstance(style, PackedRowwiseParallel):
resolved[path] = _NoPartitionRowwise()
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', PackedColwiseParallel, or PackedRowwiseParallel."
f"Expected 'colwise', 'rowwise', 'rowwise_split_input', PackedColwiseParallel, or "
f"PackedRowwiseParallel."
)
return resolved

Expand Down
7 changes: 1 addition & 6 deletions src/diffusers/models/model_loading_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,12 +407,7 @@ def _load_shard_file_tp(
from ..hooks.tensor_parallel import _local_shard

tp_mesh = tp_config._mesh
# `TensorParallelConfig._device` is derived from the default accelerator, which is not meaningful on
# Neuron; resolve it the way the Neuron pre-shard backend does.
if tp_mesh.device_type == "neuron":
device = torch.neuron.current_device()
else:
device = tp_config._device
device = tp_config._device

mismatched_keys = []

Expand Down
15 changes: 15 additions & 0 deletions src/diffusers/models/modeling_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1547,8 +1547,19 @@ def from_pretrained(cls, pretrained_model_name_or_path: str | os.PathLike | None
if tp_shard_specs is not None:
# The weights are already sharded, so this only registers the forward hooks. `_parallel_config`
# was recorded by `_resolve_parallel_config` before loading.
from torch.distributed.tensor import DTensor

from ..hooks.tensor_parallel import apply_tensor_parallel

# Non-persistent buffers are absent from both the state dict and the checkpoint, and
# `init_empty_weights` leaves them as real CPU tensors, so move them across explicitly.
tp_device = tp_config._device
for name, buffer in model.named_buffers():
if buffer.device != tp_device and not isinstance(buffer, DTensor):
module_path, _, buffer_name = name.rpartition(".")
module = model.get_submodule(module_path) if module_path else model
module._buffers[buffer_name] = buffer.to(tp_device)

apply_tensor_parallel(model, tp_config, cls._tp_plan, weights_already_sharded=True)
else:
model.enable_parallelism(config=parallel_config)
Expand Down Expand Up @@ -1780,6 +1791,10 @@ def enable_parallelism(
model=self,
)
resolve_tp_shard_specs(self, self._tp_plan, _tp_degree(tp_config))
logger.warning(
"Sharding an in-memory model costs full checkpoint memory on every rank. Prefer "
"`from_pretrained(..., parallel_config=...)`, which reads only each rank's shard."
)

config = self._resolve_parallel_config(config)

Expand Down
48 changes: 45 additions & 3 deletions src/diffusers/models/transformers/transformer_minimax_h3.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import torch.nn as nn

from ...configuration_utils import ConfigMixin, register_to_config
from ...hooks.tensor_parallel import PackedColwiseParallel
from ...loaders import FromOriginalModelMixin, PeftAdapterMixin
from ...utils import BaseOutput, apply_lora_scale, logging
from .._modeling_parallel import ContextParallelInput, ContextParallelOutput
Expand Down Expand Up @@ -179,9 +180,11 @@ def __call__(
key = attn.to_k(hidden_states)
value = attn.to_v(hidden_states)

query = query.unflatten(-1, (attn.heads, -1))
key = key.unflatten(-1, (attn.heads, -1))
value = value.unflatten(-1, (attn.heads, -1))
# Reshape by a fixed `head_dim` and let `-1` absorb the head count. Under tensor parallelism each rank
# holds a column-sharded slice (`attn.heads // tp_degree` heads); this keeps the processor TP-agnostic.
query = query.unflatten(-1, (-1, attn.head_dim))
key = key.unflatten(-1, (-1, attn.head_dim))
value = value.unflatten(-1, (-1, attn.head_dim))

query = attn.norm_q(query)
key = attn.norm_k(key)
Expand Down Expand Up @@ -451,6 +454,45 @@ class MiniMaxH3Transformer3DModel(
"audio_proj_out",
"rope",
]
# Tensor-parallel plan: how each block's Linears shard across the TP mesh. Q/K/V and the attention output
# are unfused, so they are plain "colwise"/"rowwise" (torch's ColwiseParallel / RowwiseParallel). The one
# packed projection is the SwiGLU input `ff.net.0.proj`, a single Linear producing `[value; gate]` in equal
# halves, hence PackedColwiseParallel([1, 1]) so each half is sharded independently.
#
# `adaln_proj.linear` is the one projection that has to keep its full output width: the six modulation
# parameters it produces scale and shift the full hidden dim of the packed sequence, which is already all-reduced
# by the time they are applied. Sharding it colwise would need an all-gather to rebuild that width, so it is
# sharded `"rowwise_split_input"` instead — over its `time_embed_dim` input, reading the replicated
# `temb` and all-reducing the result. It is worth the collective: at `6 * hidden_size * MINIMAX_H3_MODALITY_NUM`
# outputs per block it is ~40% of the denoiser's weights, and leaving it replicated puts the per-rank floor above
# a single device's memory at any TP degree. The all-reduce itself is over `num_timesteps * 6 * hidden_size *
# MINIMAX_H3_MODALITY_NUM` elements, i.e. hundreds of KB, once per block per step.
#
# Intentionally absent, i.e. replicated on every rank: the RMSNorms (`norm1`, `norm2`,
# `token_refiner.final_norm`, `norm_out.norm`); the QK-norms, which apply over `head_dim` after the heads are
# already split; `norm_out.linear`, which indexes the full hidden dim as `adaln_proj` does but is a single
# `2 * hidden_size` projection rather than one per block, so sharding it would buy nothing; and the patch/text
# embedders and the two output heads.
#
# `attn.to_qkv` is deliberately not listed: it only exists after `fuse_projections()`, and the plan is
# resolved by attribute lookup, so an unconditional entry would break the ordinary unfused model.
_tp_plan = {
# denoiser block stack
"transformer_blocks.*.attn.to_q": "colwise",
"transformer_blocks.*.attn.to_k": "colwise",
"transformer_blocks.*.attn.to_v": "colwise",
"transformer_blocks.*.attn.to_out.0": "rowwise",
"transformer_blocks.*.ff.net.0.proj": PackedColwiseParallel([1, 1]),
"transformer_blocks.*.ff.net.2": "rowwise",
"transformer_blocks.*.adaln_proj.linear": "rowwise_split_input",
# the token-refiner blocks are the same attention + SwiGLU FFN, minus AdaLN and rotary
"token_refiner.refiner_blocks.*.attn.to_q": "colwise",
"token_refiner.refiner_blocks.*.attn.to_k": "colwise",
"token_refiner.refiner_blocks.*.attn.to_v": "colwise",
"token_refiner.refiner_blocks.*.attn.to_out.0": "rowwise",
"token_refiner.refiner_blocks.*.ff.net.0.proj": PackedColwiseParallel([1, 1]),
"token_refiner.refiner_blocks.*.ff.net.2": "rowwise",
}
# Context parallelism shards the packed sequence, so the split cannot happen on the inputs of `forward`: the rows
# of the three modalities are scattered into the packed buffer with sequence-wide indices, which only address the
# full sequence. The split therefore happens once the buffer is built, at the first block, and everything that is
Expand Down
4 changes: 4 additions & 0 deletions src/diffusers/modular_pipelines/minimax_h3/before_denoise.py
Original file line number Diff line number Diff line change
Expand Up @@ -1231,6 +1231,10 @@ def build_row_timesteps(
Returns:
`tuple[torch.Tensor, torch.Tensor]`: the distinct timesteps, sorted, and the index of every row into them.
"""
# The layout step puts the indices on the execution device, but this plan is built on CPU.
video_indices = video_indices.cpu()
audio_indices = audio_indices.cpu()
Comment on lines +1234 to +1236

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.

Why is this change needed?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

it's just that video_indices and audio_indices were on device

block_state.video_indices = video_indices.to(device)

but

row_timesteps = torch.full((sequence_length,), video_timestep, dtype=torch.float32)

happens on cpu, and it failed without moving indices back to cpu.

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.

But why does it particularly show up for TP? Does regular inference fail without it?

@JingyaHuang JingyaHuang Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'm almost sure that's bc I changed the definition of pipeline's device in my tp PR, but let me confirm.

@JingyaHuang JingyaHuang Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

ok @sayakpaul , on cuda actually it works w/o. the change since PyTorch itself copies a foreign-device index onto the indexed tensor's device:
https://github.com/pytorch/pytorch/blob/735a2ec9b17c91c93d6714f88115f97394b836c9/aten/src/ATen/native/IndexingUtils.h#L60-L61
so there was a hidden GPU→CPU copy, and it's not the case for Neuron which check the device consistency first:
https://github.com/aws-neuron/torch-neuronx/blob/d9d8423807874b11c8d59242b09378e68bc9a504/torch_neuronx/csrc/core/dispatch/PreprocessArgs.cpp#L31-L42

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

So here the move of indices to cpu is equivalent to what had happened under the hood in PyTorch.


sequence_length = int(video_indices.numel() + audio_indices.numel() + num_text_tokens)
row_timesteps = torch.full((sequence_length,), video_timestep, dtype=torch.float32)
row_timesteps[video_indices[:num_condition_video_rows]] = condition_video_timestep
Expand Down
4 changes: 4 additions & 0 deletions src/diffusers/modular_pipelines/p_h3_image/before_denoise.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,10 @@ def build_row_timesteps(
Returns:
`tuple[torch.Tensor, torch.Tensor]`: the distinct timesteps, sorted, and the index of every row into them.
"""
# The layout step puts the indices on the execution device, but this plan is built on CPU.
video_indices = video_indices.cpu()
audio_indices = audio_indices.cpu()

sequence_length = int(video_indices.numel() + audio_indices.numel() + num_text_tokens)
row_timesteps = torch.full((sequence_length,), video_timestep, dtype=torch.float32)
row_timesteps[video_indices[:num_condition_video_rows]] = condition_video_timestep
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,10 @@ def build_row_timesteps(
Returns:
`tuple[torch.Tensor, torch.Tensor]`: the distinct timesteps, sorted, and the index of every row into them.
"""
# The layout step puts the indices on the execution device, but this plan is built on CPU.
video_indices = video_indices.cpu()
audio_indices = audio_indices.cpu()

sequence_length = int(video_indices.numel() + audio_indices.numel() + num_text_tokens)
row_timesteps = torch.full((sequence_length,), video_timestep, dtype=torch.float32)
row_timesteps[video_indices[:num_condition_video_rows]] = condition_video_timestep
Expand Down
Loading
Loading