Suppose you already have a PyTorch network. Its first layer expands four features to eight, then it removes negative values, and the second layer reduces the features back to four. If you assign whole layers to GPUs, GPU 0 computes the entire first layer and hands eight intermediate values to GPU 1 for the second. Here we want tensor parallelism: both GPUs compute the first layer, each keeping four intermediate values, then each uses its four values in the second multiplication. When replacing these layers with Megatron Core 0.12.0 equivalents, how should we split weights to save a transfer between layers?12
Give the model six more GPUs and the original split can spread the same multiplication across more devices. Another arrangement, 2.5D tensor parallelism, lays the eight GPUs out in two squares of four, each handling different inputs with a copy of the blocked weights. An older Colossal-AI example uses exactly eight GPUs. Comparing the layouts shows where changing a GPU count is enough and where multiplication and communication must both change.3
📓 Draft verification status. A complete two-process training step follows. I checked the interfaces against the 0.12.0 source and the expected loss can be calculated by hand. An end-to-end run on two GPUs with NCCL communication remains unverified.
Starting from ordinary linear layers, which weights does each process hold?
The original model is Linear(4, 8) → ReLU → Linear(8, 4). ReLU sets each negative number to zero. Follow the token below through both layers to see what each GPU gets.
flowchart TB
X["同一个词元输入 (1, −2, 3, 0)"]
X --> A["GPU 0 · 第一层算前四个值<br/>(1, −2, 3, 0)"]
X --> B["GPU 1 · 第一层算后四个值<br/>(2, −4, 6, 0)"]
A -->|"本卡做 ReLU"| C["GPU 0 留下 (1, 0, 3, 0)"]
B -->|"本卡做 ReLU"| D["GPU 1 留下 (2, 0, 6, 0)"]
C --> E["第二层 · GPU 0 的部分和<br/>(1, 0, 3, 0)"]
D --> F["第二层 · GPU 1 的部分和<br/>(2, 0, 6, 0)"]
E --> S["跨卡逐项相加<br/>两张卡都得到 (3, 0, 9, 0)"]
F --> S
Figure 1. Read downward on the left. GPU 0 can begin the second layer with its own four intermediate values. The paths meet at the bottom: for the third output alone, GPU 0 contributes 3 and GPU 1 contributes 6. Only their sum gives 9. The weights come from the script below. To simplify hand calculation, the second layer adds corresponding values from the two groups.
| Original model | Megatron layer | Actual weight.shape on each GPU |
|---|---|---|
Linear(4, 8) | ColumnParallelLinear, keep output local | (4, 4), four output rows of the original weight |
Linear(8, 4) | RowParallelLinear, directly accept local input | (4, 4), four input columns of the original weight |
Why does a “column” split slice rows when copying PyTorch weights? In handwritten matrix multiplication we often write X @ W, but PyTorch Linear stores W.T. The first layer splits output features, corresponding to axis 0 in PyTorch’s stored weight. The second splits input features, axis 1. With the same boundary on the eight intermediate features, activations can pass directly to the next layer on the same GPU.2
How do I know the parallel version really learned the same thing?
Set the first layer’s eight outputs in two groups equal to the input and twice the input. The second layer adds the groups, so the network should output 3 × ReLU(x). For tokens [1,-2,3,0] and [0,1,-1,2] with zero targets, the mean squared error over the eight outputs should be 16.875. Loss alone is insufficient: splitting the wrong axis could coincidentally produce the same scalar. The script also compares each output, the gradient back to the input, gradients for both layers’ weights, and the weights on each GPU after one update.
On Linux with two visible NVIDIA GPUs, CUDA-enabled PyTorch, and NCCL configured, save the following code as train_tp.py. torchrun starts two processes, each binding to a GPU according to LOCAL_RANK. A rank is a process’s number within the group. Together the two GPUs form one tensor-parallel group and compute on the same input batch.14
python -m pip install megatron-core==0.12.0
CUDA_DEVICE_MAX_CONNECTIONS=1 torchrun --standalone --nproc-per-node=2 train_tp.py
import os
import torch
import torch.distributed as dist
from torch import nn
from megatron.core import parallel_state
from megatron.core.tensor_parallel.layers import ColumnParallelLinear, RowParallelLinear
from megatron.core.transformer.transformer_config import TransformerConfig
def train_one_step(device):
rank = parallel_state.get_tensor_model_parallel_rank()
cfg = TransformerConfig(
num_layers=1, hidden_size=4, num_attention_heads=2,
tensor_model_parallel_size=2, params_dtype=torch.float32,
perform_initialization=False, gradient_accumulation_fusion=False,
)
common = dict(config=cfg, init_method=nn.init.zeros_, bias=False)
first = ColumnParallelLinear(4, 8, gather_output=False, **common).to(device)
second = RowParallelLinear(
8, 4, input_is_parallel=True, skip_bias_add=False, **common
).to(device)
dense = nn.Sequential(nn.Linear(4, 8, bias=False), nn.ReLU(),
nn.Linear(8, 4, bias=False)).to(device)
shards = [(first.weight, dense[0].weight, 0),
(second.weight, dense[2].weight, 1)]
with torch.no_grad():
eye = torch.eye(4, device=device)
dense[0].weight.copy_(torch.cat([eye, 2 * eye], dim=0))
dense[2].weight.copy_(torch.cat([eye, eye], dim=1))
for local, full, axis in shards:
local.copy_(full.chunk(2, dim=axis)[rank])
# 形状为 (两个词元,一个样本,四个特征)。
x = torch.tensor([[[1., -2., 3., 0.]], [[0., 1., -1., 2.]]],
device=device, requires_grad=True)
x_ref = x.detach().clone().requires_grad_()
local_hidden, _ = first(x)
output, _ = second(local_hidden.relu())
expected = dense(x_ref)
torch.testing.assert_close(output, expected)
loss = output.square().mean()
torch.testing.assert_close(loss, loss.new_tensor(16.875))
loss.backward()
expected.square().mean().backward()
torch.testing.assert_close(x.grad, x_ref.grad)
for local, full, axis in shards:
torch.testing.assert_close(local.grad, full.grad.chunk(2, dim=axis)[rank])
torch.optim.SGD([first.weight, second.weight], lr=0.01).step()
torch.optim.SGD(dense.parameters(), lr=0.01).step()
for local, full, axis in shards:
torch.testing.assert_close(local, full.chunk(2, dim=axis)[rank])
dist.barrier()
if rank == 0:
print(f"loss={loss.item():.3f}, 两张卡的梯度和更新均一致")
if __name__ == "__main__":
device = torch.device("cuda", int(os.environ["LOCAL_RANK"]))
torch.cuda.set_device(device)
dist.init_process_group("nccl")
try:
assert dist.get_world_size() == 2, "这个算例需要两个进程"
parallel_state.initialize_model_parallel(tensor_model_parallel_size=2)
train_one_step(device)
finally:
parallel_state.destroy_model_parallel()
dist.destroy_process_group()
gather_output=False leaves the first layer’s four intermediate features on each GPU. input_is_parallel=True tells the second layer it already has the correct four. In the forward pass the second layer sums the two GPUs’ contributions, so both GPUs can read the complete output. In backpropagation the first layer must sum the contributions from its four local outputs to the gradient of the original input. Weight gradients remain on the GPU holding each weight. The example keeps the complete model as dense for element-by-element comparison. When training a real large model, you can remove that reference.2
Is changing the parallel GPU count from 2 to 8 enough to reproduce 2.5D?
The two-GPU example divides eight intermediate features into two groups. With the same one-dimensional split, those eight features could in principle be divided into eight groups of one feature per GPU. A 2.5D layout rearranges the eight GPUs. Suppose the layer now handles four tokens at once. Cut the weight matrix once horizontally and once vertically to obtain four blocks. Each small box in the figure is a GPU labeled with its weight block.
Figure 2. Start with the upper-left corners. In the forward pass both GPU 0 and GPU 4 hold W₀₀ and cooperate with partners in their own grid. A computes outputs for tokens 1 and 2, B for tokens 3 and 4. In backpropagation each grid computes a gradient contribution for that block, which must then be summed across the dashed line. The other three positions synchronize in corresponding pairs. The drawing follows the older Colossal-AI 2.5D layout; GPU numbers are illustrative.3
To compare communication costs for these layouts, see how many bytes the two layouts transfer with a fixed total of 16 GPUs.
| Implementation | What it establishes for trying 2.5D |
|---|---|
| Megatron Core 0.12.0 | The two linear layers and group-size configuration used here provide one-dimensional row and column splitting. Reproducing the grids requires the corresponding process groups, two-dimensional multiplication, and gradient synchronization across planes.24 |
| DeepSpeed 0.17.1 | The training configuration reads tensor-parallel and ZeRO settings separately. Enabling ZeRO changes how parameters and other state are stored. It does not replace Linear with 2.5D matrix multiplication. I found no general switch for reproducing this layout in those entry points.5 |
| Legacy Colossal-AI tensor-parallel examples | The official example provides an eight-GPU entry point: colossalai run --nproc_per_node=8 run.py --config ./configs/tp_2p5d.py. It uses that version’s parallel layers and splits inputs according to the layout. The tutorial marks this as legacy usage, so reproducing it requires the matching old code and dependencies.3 |
To port your own model, start with two neighboring layers. Write down which inputs and outputs each shard owns, as in this example, and keep the original implementation for numerical comparison. That gives you a chance to catch a wrong split axis in the first backward pass even when the shapes match.
References
Footnotes
-
NVIDIA. (2025, May 6). Megatron Core 0.12.0. PyPI. Version and environment requirements ↩ ↩2
-
NVIDIA. (2025). Tensor-parallel layers (core_v0.12.0). GitHub. Column- and row-parallel layers and forward/backward communication ↩ ↩2 ↩3 ↩4
-
HPC-AI Tech. (n.d.). Tensor parallelism examples. GitHub. Model, inputs, and launch command in the legacy eight-GPU example · Version note in the 2.5D tutorial ↩ ↩2 ↩3
-
NVIDIA. (2025). Model parallel configuration and initialization (core_v0.12.0). GitHub. Meaning of the parallel group size · Process group initialization ↩ ↩2
-
DeepSpeed contributors. (2025). DeepSpeedConfig (v0.17.1). GitHub. Tensor parallelism and ZeRO in the training configuration ↩