Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
acdf4bf
[core] Shard tensor-parallel checkpoints on load and save
JingyaHuang Aug 20, 2026
0b9686b
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Aug 20, 2026
40ddb53
Raise when tensor parallelism is combined with quantization, offloadi…
JingyaHuang Aug 20, 2026
0760934
Merge branch 'add-shard-ckpt-loading' of github.com:JingyaHuang/diffu…
JingyaHuang Aug 21, 2026
842c643
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Aug 25, 2026
949cbdc
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Aug 26, 2026
eb3f7f3
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Aug 27, 2026
a754bbe
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Aug 27, 2026
6055292
Merge branch 'add-shard-ckpt-loading' of github.com:JingyaHuang/diffu…
JingyaHuang Aug 28, 2026
fd31c34
Merge branch 'main' into add-shard-ckpt-loading
sayakpaul Sep 2, 2026
9511143
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Sep 10, 2026
53fd823
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Sep 19, 2026
4112d18
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Sep 23, 2026
f741782
review: remove tp save/ dcp related
JingyaHuang Sep 23, 2026
1b4d1d7
review: add a new helper .
JingyaHuang Sep 23, 2026
4e9a927
review: moved the TP checks into enable_parallelism
JingyaHuang Sep 23, 2026
0cca9a3
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Sep 24, 2026
7ea8b97
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Sep 28, 2026
a89e7e4
review: move the warning under caution block
JingyaHuang Sep 28, 2026
e3fdafd
review: add loading time numbers
JingyaHuang Sep 28, 2026
8a6ff80
review: move tp size dividende check
JingyaHuang Sep 29, 2026
64c9e86
review: delete test
JingyaHuang Sep 29, 2026
b52a272
review: consolidate tp checks
JingyaHuang Sep 29, 2026
068d7ab
review: consolidate the tp checks, all in tensor_parallel.py
JingyaHuang Sep 29, 2026
6a56929
review: improve conditionals
JingyaHuang Sep 29, 2026
85dc21b
review: debug info
JingyaHuang Sep 29, 2026
aad9e9e
review: check weights format before instantiating the model
JingyaHuang Sep 29, 2026
fc76c2c
review: restore duplicated _find_mismatched_keys since irrelevant
JingyaHuang Sep 29, 2026
cb01688
Merge branch 'main' into add-shard-ckpt-loading
JingyaHuang Sep 29, 2026
30d4184
revert: delete duplicated helper
JingyaHuang Sep 29, 2026
8f577c6
review: remove the dead duplicate _find_mismatched_keys again
JingyaHuang Sep 29, 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
63 changes: 41 additions & 22 deletions docs/source/en/training/distributed_inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -436,43 +436,51 @@ pipeline = DiffusionPipeline.from_pretrained(

[Tensor parallelism](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=tensor_parallelism) shards the weight matrices of a model across devices. Each device holds a column-wise (`"colwise"`) or row-wise (`"rowwise"`) slice of each layer, computes a partial result, and an `AllReduce`/`AllGather` at the layer boundary reconstructs the full output. Unlike context parallelism, it reduces the per-device *weight* memory, which is useful for models that do not fit on a single device.

Pass a [`TensorParallelConfig`] to [`~ModelMixin.enable_parallelism`]. `tp_degree` is the number of devices to shard across and must divide the model's number of attention heads. The model must define a `_tp_plan` (a flat mapping of module-name globs to a `"colwise"`/`"rowwise"` style).
Pass a [`TensorParallelConfig`] to the `parallel_config` argument of the model's [`~ModelMixin.from_pretrained`]. `tp_degree` is the number of devices to shard across and must divide the model's number of attention heads. The model must define a `_tp_plan` (a flat mapping of module-name globs to a `"colwise"`/`"rowwise"` style).

Loading this way shards the checkpoint *while reading it*: each rank reads only its own slice of each sharded weight and places it straight onto its own device. Nothing full-size is ever materialized, so per-rank memory falls as `tp_degree` rises.
Comment thread
JingyaHuang marked this conversation as resolved.

Compared to loading the full model and then calling [`~ModelMixin.enable_parallelism`], it loads faster and uses less CPU memory per rank, with the gap growing as `tp_degree` rises. Numbers below are for a FLUX.1-shaped synthetic checkpoint (1.33B params, bf16).

| tp_degree | method | load time | peak CPU/rank |
|---|---|---|---|
| 2 | `from_pretrained(parallel_config=...)` | 1.92s | 2.70GB |
| 2 | `from_pretrained` + `enable_parallelism` | 3.06s | 4.08GB |
| 4 | `from_pretrained(parallel_config=...)` | 1.45s | 2.20GB |
| 4 | `from_pretrained` + `enable_parallelism` | 3.29s | 4.08GB |

```py
import torch
from torch import distributed as dist
from diffusers import DiffusionPipeline, TensorParallelConfig
from diffusers import DiffusionPipeline, Flux2Transformer2DModel, TensorParallelConfig

def setup_distributed():
if not dist.is_initialized():
dist.init_process_group(backend="nccl")
rank = dist.get_rank()
def main():
dist.init_process_group(backend="nccl")
rank, world_size = dist.get_rank(), dist.get_world_size()
device = torch.device(f"cuda:{rank}")
torch.cuda.set_device(device)
return device

def main():
device = setup_distributed()
world_size = dist.get_world_size()
# Each rank reads only its own shard of every planned weight, straight onto `cuda:rank`.
transformer = Flux2Transformer2DModel.from_pretrained(
"black-forest-labs/FLUX.2-dev",
subfolder="transformer",
torch_dtype=torch.bfloat16,
parallel_config=TensorParallelConfig(tp_degree=world_size),
)

pipeline = DiffusionPipeline.from_pretrained(
"black-forest-labs/FLUX.2-dev", torch_dtype=torch.bfloat16
) # weights stay on CPU

# Shard the transformer first, then move only each rank's slice onto the accelerator.
pipeline.transformer.enable_parallelism(config=TensorParallelConfig(tp_degree=world_size))
pipeline.transformer.to(device)

# Move the remaining, non-sharded components onto the accelerator individually.
"black-forest-labs/FLUX.2-dev", transformer=transformer, torch_dtype=torch.bfloat16
)
# The transformer is already on its device; move the remaining components individually. Do not call
# `pipeline.to(device)` — that would move every rank's shards onto the same device.
pipeline.text_encoder.to(device)
pipeline.vae.to(device)

generator = torch.Generator().manual_seed(42)
image = pipeline(prompt="a cat holding a sign that says hello", generator=generator).images[0]
if dist.get_rank() == 0:
if rank == 0:
image.save("output.png")
if dist.is_initialized():
dist.destroy_process_group()
dist.destroy_process_group()

if __name__ == "__main__":
main()
Expand All @@ -484,6 +492,15 @@ torchrun --nproc-per-node 4 tensor_parallel_flux.py

`tp_degree` is taken from `world_size` above, so `--nproc-per-node 4` shards the transformer across 4 devices.

> [!CAUTION]
> Loading with a tensor-parallel `parallel_config` isn't supported yet with `device_map`, `quantization_config`, `low_cpu_mem_usage=False`, `use_flashpack=True`, or non-safetensors weights; each raises rather than quietly falling back to loading the full checkpoint.
>
> 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.

Saving a tensor-parallel model isn't supported yet, and [`~ModelMixin.save_pretrained`] raises on one. Save the model before sharding it.

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.

Perfecto!


### Writing a tensor parallelism plan

Tensor parallelism only works on models that define a `_tp_plan`, a flat class attribute mapping module-name globs to a sharding style. Writing one is mostly a matter of pairing each projection that *expands* the hidden dimension with the projection that *contracts* it back.
Expand Down Expand Up @@ -536,9 +553,11 @@ Anything absent from the plan stays replicated on every rank, which is the right

#### Constraints and verification

- `tp_degree` must divide `config.num_attention_heads`. This is validated in [`~ModelMixin.enable_parallelism`].
- `tp_degree` must divide `config.num_attention_heads`.
- Every packed block must *individually* be divisible by `tp_degree`, not just their sum.

Both are validated by [`~ModelMixin.from_pretrained`] and [`~ModelMixin.enable_parallelism`] before any weight is loaded or sharded.

Validate a new plan numerically rather than by eye: generate with a fixed seed on a single device, then again under tensor parallelism, and compare the outputs. A misplaced `"colwise"`/`"rowwise"` usually still runs and produces a plausible but wrong image.

> [!TIP]
Expand Down
Loading
Loading