Phase 05/Splitting a model across GPUs/Tensor parallelism
PHASE 05 · Splitting a model across GPUs

Tensor parallelism

0%
9 h5 subtopics3 lessons · 2 required
In plain English

Tensor parallelism slices every big multiplication inside the model across several GPUs. Imagine a huge spreadsheet multiplication that is too wide for one desk. You tear the sheet into vertical strips, hand one strip to each worker, and each works on their strip at the same time. The catch is that some steps need the whole row, so the workers must stop and add up their partial sums before continuing. In a transformer this adding-up happens twice per layer, after attention and after the feed-forward block. On a fast in-box connection like NVLink that pause is tiny; over an ordinary network it can take longer than the maths itself, which is why tensor parallelism is kept inside a single machine.

Why it matters

TP is the default way serving engines fit large models and cut per-token latency. Understanding exactly where the all-reduces sit lets you predict scaling, debug numerical mismatches, and read the sharded-layer code in vLLM and Megatron.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Databricks, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Implement column-parallel and row-parallel linear layers with torch.distributed and verify them against a single-process reference.
  • Place the two all-reduces per transformer layer and explain why the MLP needs only two instead of four collectives.
  • Shard attention heads across ranks and reason about KV cache memory per rank.
  • Measure how communication volume scales with hidden size, batch size, and TP degree.

Key concepts

Column-parallel linear
The weight matrix is split along output features; each rank produces a slice of the output and no communication is needed on the forward path.
Row-parallel linear
The weight matrix is split along input features; each rank produces a partial sum and an all-reduce sums them.
Megatron MLP pattern
Column-parallel first linear, local activation, row-parallel second linear, one all-reduce; the standard TP block.
Head-parallel attention
Attention heads are divided among ranks so QKV projections and the KV cache are naturally sharded.
All-reduce
A collective where every rank ends up with the sum of all ranks' tensors.
Sequence parallelism
Sharding the sequence dimension for the layer norm and dropout regions to remove redundant activation memory in TP.
Weight sharding at load time
Reading only the slice of each checkpoint tensor that a rank owns rather than loading the whole file on every rank.

Subtopics

  1. 1. Column and row parallel linear layers

    Derive the math of splitting Y = XW along output or input features, and where the all-reduce or all-gather must go.

  2. 2. The MLP block under TP

    Column-parallel up-projection, local GELU/SiLU, row-parallel down-projection, single all-reduce; why the element-wise nonlinearity is the key that allows this.

  3. 3. Attention under TP

    Shard heads across ranks, local softmax per head, row-parallel output projection; grouped-query attention and KV head replication when n_kv_heads is less than TP.

  4. 4. Communication cost model

    Two all-reduces per layer of size batch * seq * d_model; ring all-reduce moves 2(n-1)/n of the tensor per rank; latency-bound in decode, bandwidth-bound in prefill.

  5. 5. TP in real engines

    How vLLM's ColumnParallelLinear and RowParallelLinear and the tensor_parallel_size flag map to this topic; sharded checkpoint loading.

Resources

repo
tutorial

Hands-on lessons

L1

Hand-rolled TP MLP on two CPU processes

CPU · your Macscript150 minrequired

Goal · Implement ColumnParallelLinear and RowParallelLinear with gloo all-reduce and show a two-rank TP MLP matches a single-process MLP bit-for-bit within float tolerance.

  1. 1Create tp_mlp.py; init_process_group(backend="gloo") and read rank/world_size from torchrun environment variables.
  2. 2On rank 0 build a reference nn.Sequential(Linear(d, 4d), GELU(), Linear(4d, d)) with a fixed seed and broadcast its weights to all ranks.
  3. 3Implement ColumnParallelLinear that keeps columns [rank*4d/ws, (rank+1)*4d/ws) of W1 and the matching bias slice.
  4. 4Implement RowParallelLinear that keeps the matching rows of W2, computes a partial product, then calls dist.all_reduce(out, op=SUM) and adds the bias only on one rank or divides it by world_size.
  5. 5Run the sharded forward and compare with the reference forward on rank 0 using torch.allclose(atol=1e-5).
  6. 6Count bytes passed through all_reduce per forward and print them; vary d in {256, 1024, 4096} and batch in {1, 8, 64}.
  7. 7Launch with torchrun --nproc_per_node=2 tp_mlp.py and then with 4 processes.
Deliverable
tp_mlp.py and a table of (d, batch, world_size, bytes communicated, max abs error).
Check
allclose passes for all configurations; bytes communicated equal batch * d * 4 per all-reduce for fp32 and are independent of world_size.
L2

Shard attention heads and the KV cache

CPU · your Macscript120 minrequired

Goal · Extend l1 to a full TP transformer block with head-parallel attention and verify that per-rank KV cache size shrinks by the TP factor.

  1. 1Add a single-head-per-rank attention where each rank owns n_heads/world_size heads of the fused QKV projection (column-parallel) and the output projection (row-parallel).
  2. 2Keep a per-rank KV cache tensor of shape (batch, local_heads, seq, head_dim) and report its numel after a 64-token decode loop.
  3. 3Wire pre-norm, attention, residual, pre-norm, MLP, residual into one block and count the all-reduces per forward (expect exactly two).
  4. 4Compare the block output with a non-sharded reference block that uses the same broadcast weights.
  5. 5Handle the GQA case where n_kv_heads is 2 and world_size is 4 by replicating KV heads; document the memory cost.
Deliverable
tp_block.py plus a short note on where the two all-reduces live and the measured KV cache numel per rank for world_size 1, 2, 4.
Check
Output matches reference within 1e-4; KV cache numel per rank is exactly reference/world_size when n_kv_heads is divisible by world_size.
L3

Measure TP scaling on real GPUs with vLLM

Rented multi-GPUexperiment120 minoptional

Goal · Serve a 7B or 8B model with tensor_parallel_size 1 and 2 on a two-GPU instance and measure decode latency and throughput.

  1. 1Rent a 2x A10G or 2x L4 instance; install vLLM; confirm nvidia-smi topo -m shows the link type between the GPUs.
  2. 2Start vllm serve with --tensor-parallel-size 1 on a model that fits one GPU (Llama-3.1-8B in fp16 or an AWQ variant).
  3. 3Run `vllm bench serve` at concurrency 1 and 32; record TTFT, inter-token latency, and tokens per second.
  4. 4Repeat with --tensor-parallel-size 2 and compare; compute the speedup for each metric.
  5. 5Record NCCL_DEBUG=INFO output to see which algorithm and transport (NVLink, PCIe, SHM) were chosen.
  6. 6Write a paragraph explaining why decode latency improves less than 2x and where the time goes.
Deliverable
A markdown report with the two benchmark tables and the NCCL transport line.
Check
TP=2 shows lower inter-token latency than TP=1 but by less than 2x; the per-request speedup at concurrency 1 is smaller than at concurrency 32.
Fallback
Run the l1 tp_mlp.py under torchrun --nproc_per_node=1, 2, and 4 on the Mac with the gloo backend and time the forward pass with d=4096, batch=64; plot wall time versus world_size and note that gloo over loopback makes communication dominate, which is the same curve shape you would see with TP over a slow interconnect.

Build your own

Build your own tensor-parallel linear layers

PythonCPU · your Mac~8 h

ColumnParallelLinear, RowParallelLinear and head-parallel attention on torch.distributed gloo, loading real GPT-2 weights shard by shard and matching the single-process model token for token.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/linear.py ↗

How you know a stage passes

Write tests/test_tp.py first. Each test launches `torchrun --nproc_per_node=N tp_check.py --stage k` through subprocess for N in 1, 2 and 4, loads the tensors each rank saved to /tmp, and compares them with a single-process reference computed in the test itself (torch.allclose, atol 1e-5). A thin wrapper around dist.all_reduce and dist.all_gather counts calls and bytes so tests can assert communication volume. Run `pytest -q`; a stage is done when its test passes on all three world sizes.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01sharding utilities
    shard(tensor, dim, rank, world) and gather(shards, dim) split and reassemble a weight along rows or columns, with an error when the dimension does not divide evenly.
    test · For a random (64, 96) weight the gathered shards equal the original bitwise for world sizes 1, 2 and 4 on both dimensions; world 3 raises ValueError.
  2. 02ColumnParallelLinear
    Each rank holds out_features / world columns of the weight and bias; forward returns either the local slice or, with gather_output, the all-gathered full output.
    test · Output with gather_output matches nn.Linear with the full weight on 2 and 4 ranks; with gather_output off the communication counter records zero bytes.
  3. 03RowParallelLinear and the TP MLP
    RowParallelLinear takes the already-sharded input, multiplies by its row shard and all-reduces; Column then GELU then Row forms a TP MLP with exactly one all-reduce.
    test · The TP MLP matches a single-process MLP within atol 1e-5 on 2 and 4 ranks; the counter shows exactly one all-reduce per forward of batch * seq * hidden * 4 bytes.
  4. 04head-parallel attention with a sharded KV cache
    Q, K and V projections are column-parallel by whole heads, the output projection is row-parallel, and each rank keeps only its heads in the KV cache.
    test · A full TP transformer block matches the single-process block within atol 1e-5; per-rank KV cache bytes equal the single-process bytes divided by world size.
  5. 05load real GPT-2 small, one shard per rank
    Each rank reads the Hugging Face state dict and keeps only its shard, handling the Conv1D transpose and splitting the fused c_attn weight per head rather than by contiguous columns.
    test · 32 greedy tokens equal Hugging Face generate on 2 and 4 ranks for 3 prompts; per-rank parameter count equals embeddings plus (124,439,808 minus embeddings) / world, and the sum of sharded tensors across ranks equals the single-process count.
  6. 06communication accounting and a benchmark
    A bench script decodes 128 tokens at world sizes 1, 2 and 4, reporting tokens per second, all-reduce count and bytes per step, and the measured share of step time spent inside collectives.
    test · The counter reports 24 all-reduces per decode step (2 per layer) and 24 * batch * 768 * 4 bytes; the README table shows tokens per second and communication share for each world size with a paragraph on why CPU gloo TP does not speed up.

Knowledge check

QWhy does the Megatron MLP need only one all-reduce even though it has two linear layers?

The first linear is column-parallel so each rank gets a complete slice of the hidden activations; the nonlinearity is element-wise and stays local; only the row-parallel second linear produces partial sums that must be summed.

QWhat happens to the KV cache under tensor parallelism?

It is sharded by head, so each rank stores only its heads' keys and values, reducing per-GPU KV memory by the TP degree (unless KV heads must be replicated for GQA).

QWhy is TP across two nodes over 100 Gb Ethernet usually a bad idea?

Two all-reduces per layer per token must cross the network; at roughly 12 GB/s the latency of dozens of small collectives per token dominates the decode step.

QIn a ring all-reduce of n ranks, how much data does each rank send?

About 2(n-1)/n times the tensor size, approaching twice the tensor size as n grows.

Completion

  • All 5 subtopics marked done
  • All 2 required lessons done
  • Lessons l1 and l2 pass their numerical checks on the Mac.
  • Can sketch a TP transformer layer and mark the exact two collective points.
  • Can explain the KV cache memory per rank formula including the GQA replication case.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →