FSDP2 shards parameters, gradients and optimizer state across GPUs, but every layer is still gathered in full on each GPU before it computes. That works until a single layer, or the activations of a long sequence, no longer fits, or until scaling FSDP to hundreds of GPUs makes all-gather latency the bottleneck. Tensor parallelism (TP) splits the computation inside a layer across GPUs. Combined with FSDP2 it gives you 2D parallelism, the standard recipe for large-model training in native PyTorch.
This tutorial shows how to set it up with DTensor and torch.distributed.tensor.parallel. Verify API names against your installed PyTorch version, since this area has moved quickly across 2.x releases.
When to reach for tensor parallelism
- A single transformer block's weights plus activations do not fit in memory even with FSDP2 and activation checkpointing.
- You are scaling past a few hundred GPUs and FSDP all-gathers dominate step time.
- Global batch size is capped, so you cannot add more data-parallel replicas without hurting convergence.
- You need lower per-GPU activation memory for long sequences (sequence parallel helps here).
If none of these apply, stay with FSDP2 alone. TP adds communication on the critical path of every layer, so it only pays off over fast interconnect (NVLink within a node). Keep TP groups inside one node.
The idea: column-wise then row-wise
For an MLP block y = W2(act(W1 x)), shard W1 by columns, so each GPU computes a slice of the hidden activation independently. Shard W2 by rows, so each GPU consumes its own slice and produces a partial sum. A single all-reduce at the end combines them. Attention works the same way: shard heads across GPUs for the QKV projections (colwise) and the output projection (rowwise). Two collectives per block in the forward pass, and that is the whole cost.
Step 1: build a 2D device mesh
import os
import torch
from torch.distributed.device_mesh import init_device_mesh
world = int(os.environ["WORLD_SIZE"])
tp_size = 8 # GPUs per node
dp_size = world // tp_size
mesh = init_device_mesh("cuda", (dp_size, tp_size), mesh_dim_names=("dp", "tp"))
tp_mesh = mesh["tp"]
dp_mesh = mesh["dp"]
Launch with torchrun --nproc_per_node=8 --nnodes=N train.py. The last mesh dimension varies fastest, so ranks in the same node share a TP group.
Step 2: apply a tensor-parallel plan
from torch.distributed.tensor.parallel import (
parallelize_module, ColwiseParallel, RowwiseParallel,
PrepareModuleInput, SequenceParallel,
)
from torch.distributed.tensor import Replicate, Shard
for block in model.layers:
plan = {
"attention_norm": SequenceParallel(),
"attention": PrepareModuleInput(
input_layouts=(Shard(1), None),
desired_input_layouts=(Replicate(), None),
),
"attention.wq": ColwiseParallel(),
"attention.wk": ColwiseParallel(),
"attention.wv": ColwiseParallel(),
"attention.wo": RowwiseParallel(output_layouts=Shard(1)),
"ffn_norm": SequenceParallel(),
"feed_forward.w1": ColwiseParallel(),
"feed_forward.w3": ColwiseParallel(),
"feed_forward.w2": RowwiseParallel(output_layouts=Shard(1)),
}
parallelize_module(block, tp_mesh, plan)
The module names above match a Llama-style block; adapt them to your model. The Shard(1) layouts keep activations sharded along the sequence dimension between the TP regions (sequence parallel), so norms and residuals run on a fraction of the tokens and activation memory drops by the TP degree. Your embedding and output layers also need a plan; they are usually sharded over the vocabulary dimension.
Two constraints to check up front: the number of attention heads (and KV heads for GQA) must be divisible by tp_size, and so must the hidden dimension of the FFN.
Step 3: layer FSDP2 on the data-parallel dimension
Apply TP first, then FSDP2 over the dp mesh:
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
for block in model.layers:
fully_shard(block, mesh=dp_mesh, mp_policy=mp)
fully_shard(model, mesh=dp_mesh, mp_policy=mp)
FSDP2 sees parameters that are already DTensors sharded on the tp dimension and shards them further on the dp dimension. Order matters: TP first, FSDP second.
Step 4: data loading and the loss
Only the dp dimension should see different data. All ranks in a TP group must receive identical input batches, so build your sampler from dp_mesh.get_local_rank() and dp_mesh.size(), not from the global rank. This is the most common 2D bug: ranks silently training on different tokens inside a TP group gives garbage loss that still looks like it is decreasing.
The output logits are usually sharded over the vocabulary. Use the loss-parallel context to avoid gathering a huge logits tensor:
from torch.distributed.tensor.parallel import loss_parallel
with loss_parallel():
loss = torch.nn.functional.cross_entropy(logits.flatten(0, 1), labels.flatten(0, 1))
loss.backward()
For this, the final projection should use ColwiseParallel(output_layouts=Shard(-1), use_local_output=False).
Step 5: compile and checkpoint
Apply torch.compile per block after the parallelism wrappers, since the compiler can fuse the pointwise work around collectives. Save with torch.distributed.checkpoint, which understands DTensor and lets you resume on a different mesh shape, so you can restart from 64 GPUs on 128.
Validating correctness
- Single-GPU parity. Run 20 steps with the same seed and data on one GPU and on the 2D mesh, and compare loss curves. Expect agreement to bf16 noise, not bitwise equality.
- Gradient norm. It should match across TP sizes within tolerance. A mismatch usually points to a missing
Replicateinput layout or non-identical batches within a TP group. - Shape checks. Print
param.placementsandparam.device_meshfor a few weights to confirm(Shard(0), Shard(0))-style placements on the expected dimensions.
Performance checklist
- Profile with
torch.profilerand look at exposed (non-overlapped) NCCL time per layer. If it exceeds about 15 percent of step time, lower the TP degree. - Keep TP within NVLink. Cross-node TP over Ethernet or InfiniBand is almost always a loss.
- Raise per-GPU batch or sequence length after enabling sequence parallel, since you just freed activation memory.
- Consider async TP (
torch._inductorsymmetric-memory overlap) once the baseline is correct; it is still experimental, so benchmark before adopting.
Common failure modes
| Symptom | Likely cause |
|---|---|
| Hang at first step | Ranks disagree on mesh shape or a module is skipped on some ranks |
| Loss decreases but eval is poor | Different data in the same TP group |
| Shape error in attention | Heads not divisible by tp_size, or reshape uses global head count instead of local |
| OOM despite TP | Logits gathered in full; use loss parallel |
| Slow steps | TP group crosses nodes |
Takeaways
Tensor parallelism is not a replacement for FSDP2; it is the second axis you add when one axis stops scaling. Start with FSDP2, profile, and only introduce TP when memory or all-gather time forces you to. Keep it within a node, feed identical data to each TP group, and verify parity against a single GPU before any long run.
If your team is planning a large training run and wants an experienced PyTorch architect to review the parallelism design, get in touch.