Pidoku

Parallelism: TP, PP, DP, EP and CP

Module 19 Lesson 19.a 55 min Difficulty 4/5

Prerequisites 14.b, 14.c, 14.d, 14.e, 14.f, 16.d, 17.h


Before you start: words you need#

WordPlain meaning
RankOne GPU’s process inside a parallel group, numbered 0, 1, 2, …
ReplicaOne complete, independent copy of the model that can serve requests on its own.
Engine corevLLM’s scheduling process: one scheduler, one block pool, one prefix cache (16.d).
WorkerThe process that drives one GPU and runs the model on it (18.a).
All-reduce / all-to-allCollectives (9.f). All-reduce: every GPU ends with the sum of everyone’s data. All-to-all: every GPU sends a different piece to every other GPU.
Mixture of experts (MoE)A model whose feed-forward layers are many small “expert” networks; each token uses only a few (14.g).
KV headOne key/value head of attention. Grouped-query models have few of them, often 4 or 8 (12.g).
NVLinkNVIDIA’s fast GPU-to-GPU link inside a server or rack (9.c).

1. What is it?#

When one GPU is not enough, vLLM can use more GPUs in two very different ways:

  • spread one copy of the model across them, because it does not fit or to make each step faster; or
  • run several copies, to serve more requests at once.

vLLM names five strategies with two-letter abbreviations. They are easiest to remember by what they split:

StrategySplitsFlag
TP tensor parallelismeach layer’s weights--tensor-parallel-size N (-tp)
PP pipeline parallelismthe stack of layers--pipeline-parallel-size N (-pp)
DP data parallelismthe requests--data-parallel-size N (-dp)
EP expert parallelisman MoE model’s experts--enable-expert-parallel (with DP or TP)
CP context parallelismone long sequence--decode-context-parallel-size (-dcp), --prefill-context-parallel-size

The ideas behind each one live in Module 14 (14.b–14.f). This lesson is about what vLLM does with them: how many engine cores and workers each creates, what talks to what, and which flags and defaults matter. Facts checked on 12 November 2026 against vLLM v0.32.0.


2. Why does it matter?#

The layout decides three things you care about in production:

  • Whether the model starts at all. Weights plus a useful KV cache must fit.
  • Throughput per GPU. Eight replicas of a small model serve far more than one model split eight ways.
  • Latency per request. Splitting a model makes each step shorter, but costs communication.

The flags are easy to set and easy to set wrongly. -tp 8 on a model that fits on one GPU works, and quietly gives up most of the throughput you paid for.


3. Simple analogy#

A restaurant with eight cooks.

  • TP: all eight cooks work on every dish together, each chopping part of each ingredient. Fast per dish, but they must keep passing things across the counter.
  • PP: an assembly line. Cook 1 does starters, cook 2 mains. Little talking, but each dish waits for its turn at each station.
  • DP: eight separate kitchens, each cooking whole dishes for its own customers.
  • EP: eight kitchens that share specialists. The pastry chef works in kitchen 3, so every dessert order from every kitchen goes there and back.
  • CP: one enormous order (a banquet) split across cooks so it fits on the counters.

4. Tiny example: eight GPUs, three layouts#

An 8-billion-parameter model (15 GiB at 16 bits) on a server with eight 80 GiB GPUs:

-dp 8   8 engine cores, 8 workers   8 replicas, no communication between them
-tp 8   1 engine core,  8 workers   1 replica, 2 all-reduces per layer on every step
-tp 2 -dp 4   4 engine cores, 8 workers   4 replicas, each split over 2 GPUs

-dp 8 gives roughly eight times one GPU’s throughput. -tp 8 gives perhaps twice, but each request’s steps are about half as long. The program in section 6 works the numbers.


5. Technical explanation#

The five, side by side#

Engine coresWorkersCommunicationUse it when
TP1NAn all-reduce after every attention block and every MLPThe model does not fit on one GPU, and the GPUs share NVLink
PP1NActivations to the next stage, once per stepThe model does not fit on one node; uneven GPU counts; no fast link
DPNN × TPNone for dense modelsThe model fits; you want throughput
EPas DPas DPAll-to-all: tokens sent to the GPU holding their expertLarge MoE models
DCP1no extra GPUs: inside the TP groupPartial attention results combined across GPUsLong contexts where TP has duplicated the KV cache

Tensor parallelism#

Each layer’s weight matrices are cut by columns or rows across the GPUs, following the Megatron scheme (14.c). Each GPU computes a partial result and an all-reduce sums them: two per transformer layer, so a 32-layer model performs 64 all-reduces per forward pass.

What that means in vLLM:

  • One engine core, one scheduler, one block table. Every worker receives the same SchedulerOutput each step and computes the same sampled tokens; only rank 0’s answer is returned.
  • Each GPU holds its share of the KV heads — up to a point. With 8 KV heads and -tp 8, each GPU stores one head and the cache per token per GPU falls eightfold. With 4 KV heads and -tp 8, two GPUs must hold a copy of each head: the cache is duplicated twice. That duplication is what decode context parallelism (below) removes.
  • Speedup is sub-linear. The arithmetic divides by N; the all-reduces do not. The vLLM documentation advises that on GPUs without NVLink (it names the L40S) pipeline parallelism gives higher throughput.
  • vLLM ships its own all-reduce kernels for the small messages inference produces (custom_all_reduce.py, a symmetric-memory path, FlashInfer variants, and a quantised “quick” all-reduce on AMD MI300), and at the default -O2 it fuses the all-reduce with the following RMSNorm into one kernel (fuse_allreduce_rms: on with TP > 1 on Hopper or Blackwell when FlashInfer is installed, or with AITER on ROCm). v0.32.0 removed the older torch.compile sequence-parallel and AsyncTP passes.

Pipeline parallelism#

The first GPU runs the first group of layers and passes the activations to the next. That is one transfer per stage per step instead of two collectives per layer, so the link matters far less.

Its problem is idle stages: while stage 2 computes a batch, stage 1 has nothing to do. vLLM fills the gap with the engine core’s batch queue (16.g): with -pp 2 the engine keeps two batches in flight, so each stage is always working on a different one. A single request still advances only once per full trip, so PP raises throughput, not per-request speed (14.d).

The documentation’s recipe for a model too big for one node: “Set tensor_parallel_size to the number of GPUs per node and pipeline_parallel_size to the number of nodes.” Multi-node runs use Ray (--distributed-executor-backend ray) or vLLM’s own multiprocessing launcher (--nnodes, --node-rank, --master-addr).

Data parallelism#

--data-parallel-size 4 starts four complete engine cores, each with its own scheduler, block pool, prefix cache and workers, behind one HTTP endpoint. In internal load-balancing mode vLLM v0.32.0 also defaults --api-server-count to the DP size, so -tp 2 -dp 4 is 4 API servers, 4 engine cores, 8 workers and a DP coordinator process (16.d).

Properties that follow from “N independent engines”:

  • --max-num-seqs is per rank. Four ranks at 256 can run 1,024 requests in total.
  • Admission limits are per server. --max-num-queued-reqs and --max-num-queued-tokens count across all the ranks an API server routes to.
  • Each rank has its own prefix cache. A request benefits from a cached prefix only if it lands on the rank that holds it.

How the API server picks a rank. get_core_engine_for_request in vllm/v1/engine/core_client.py scores every engine and picks the lowest. The score is the larger of the engine’s waiting-plus-running count (from the coordinator’s snapshot, refreshed about every 100 ms) and this client’s own in-flight count, plus a penalty for waiting requests that grows once KV cache usage passes 50%. A client can force a rank with data_parallel_rank, and a streaming-input session stays on the engine that started it. There is no prefix-aware routing inside vLLM; that is the job of an external router (21.h).

Three deployment shapes:

ModeShapeBalancing
InternalOne vllm serve exposes one endpoint for all ranks. Ranks on other nodes start with --headless.vLLM’s API servers, by the score above
Hybrid (--data-parallel-hybrid-lb)One endpoint per node, each serving only that node’s ranksAn upstream load balancer across nodes, vLLM within a node
External (--data-parallel-external-lb or --data-parallel-rank)Each rank is its own server on its own portYour router or gateway

The external DP flags are for MoE deployments only. For a dense model, just run independent vllm serve processes.

Expert parallelism#

Is DP different from just running N servers? For a dense model, barely. For a mixture-of-experts model it is very different, and that is what vLLM’s DP was built for.

With --enable-expert-parallel, an MoE layer’s experts are spread across the GPUs instead of each GPU holding a slice of every expert. vLLM computes the size for you: EP = TP × DP. With -tp 2 -dp 4 on eight GPUs, attention runs as four TP-2 groups while the experts form one EP group of eight. Without the flag, the expert layers form a TP group of size TP × DP.

So the layers of one model use different strategies:

attention layers   data parallel (and TP inside each rank)   each rank handles its own requests
expert layers      expert parallel across all EP ranks      all ranks cooperate on every step

The ranks are no longer independent. From the documentation: “Forward passes must be aligned, and expert layers across all ranks are required to synchronize during every forward pass, even when there are fewer requests to be processed than DP ranks.” A rank with nothing to do runs an empty dummy forward pass so its experts are available to the others. The DP coordinator tracks when all ranks are idle so they can pause together; it is why the engine core’s has_work() also checks engines_running: someone else having work counts as work.

The token exchange is an all-to-all with selectable kernels, --all2all-backend:

BackendFor
allgather_reducescatter (default)Any EP + DP setup
deepep_high_throughputPrefill-heavy, multi-node (DeepEP)
deepep_low_latencyDecode-heavy, multi-node, CUDA-graph friendly
flashinfer_nvlink_one_sided, flashinfer_nvlink_two_sidedMulti-node NVLink systems such as GB200/GB300 NVL72
mori_*, nixl_ep, moonepAMD MoRI, NIXL-based and other EP libraries

Three more tools for MoE at scale:

  • EPLB (--enable-eplb, tuned with --eplb-config): measures how many tokens each expert receives and periodically moves or replicates hot experts. Defaults: a 1,000-step window, rebalancing every 3,000 steps, no redundant experts. Redundant experts cost memory; the documentation estimates about 2.4 GB for one per rank on DeepSeek-V3. The load-imbalance problem itself is explained in 14.e.
  • Dual batch overlap (--enable-dbo): splits a batch in two so one half’s all-to-all overlaps the other half’s compute.
  • --prefill-schedule-interval N: because every rank steps together, one rank’s big prefill slows everyone. This admits new prefills only every Nth step, aligned across ranks. Default 1.

“Wide EP” is the name for this pattern at its largest: DP attention plus EP over dozens of GPUs across nodes, usually combined with prefill/decode disaggregation (19.b), where the prefill pool uses deepep_high_throughput and the decode pool deepep_low_latency. Elastic EP (--enable-elastic-ep) can change the number of ranks while serving; in v0.32.0 it arrived in Model Runner V2.

Context parallelism#

For very long sequences (14.f). vLLM has two halves:

  • Decode context parallelism (DCP), -dcp N. It shards the KV cache along the token dimension inside an existing TP group. It does not add GPUs; it removes the duplication that TP causes when TP is larger than the KV-head count. The DCP size must lie between 1 and TP ÷ KV heads. DeepSeek-R1 with MLA has effectively one KV head, so -tp 8 duplicates its cache eight times and -dcp 8 removes that. Tokens are interleaved across ranks so new tokens spread evenly; the interleave size is cp_kv_cache_interleave_size. This is why block-size arithmetic contains a dcp_world_size factor: one physical block of 16 tokens with DCP 4 stands for 64 tokens (17.h).
  • Prefill context parallelism (PCP), --prefill-context-parallel-size. Spreads a long prompt’s queries across GPUs to shorten time to first token. The documentation still describes both prefill strategies as “under active development”; v0.32.0 added PCP with PP for MLA models and decode requests sharded across PCP ranks.

Choosing#

Does the model fit on one GPU, with room for a useful KV cache?
├── yes → one replica per GPU: independent servers, or -dp for MoE
└── no  → Does it fit on one node?
          ├── yes → -tp = GPUs needed (pipeline parallel instead if there is no NVLink)
          └── no  → -tp = GPUs per node, -pp = number of nodes
                    (MoE: DP attention + --enable-expert-parallel)
Is the KV cache duplicated because TP > KV heads? → add -dcp

Use the smallest TP that fits the model and meets your latency target, and spend the remaining GPUs on DP.


6. Under the hood: comparing layouts#

Given a model, a GPU and eight of them, which layouts fit, how many tokens of KV cache does each replica get, and how do throughput and step time compare? The communication cost per doubling of TP is an assumption; change it.

Go
// layouts.go — which -tp/-dp layouts fit, how much KV cache each replica gets,
// and a rough throughput and step-time comparison.
package main

import (
	"fmt"
	"math"
)

const GiB = 1 << 30

type layout struct{ tp, dp int }

type model struct {
	name        string
	weightGiB   float64 // 16-bit weights
	kvPerTokKiB float64 // KV bytes per token for the whole model, 16-bit cache
	kvHeads     int     // KV heads per layer: TP beyond this duplicates the cache
}

func main() {
	const (
		gpuGiB     = 80.0
		util       = 0.92 // --gpu-memory-utilization
		otherGiB   = 3.0  // activations, CUDA graphs, NCCL buffers (assumed)
		gpus       = 8
		tpOverhead = 0.12 // fraction of a step lost to communication per doubling of TP (assumed)
	)
	models := []model{
		{"8B dense", 15, 128, 8},     // Llama-3-8B shape: 32 layers, 8 KV heads
		{"70B dense", 131.5, 320, 8}, // Llama-3-70B shape: 80 layers, 8 KV heads
		{"235B MoE", 438, 188, 4},    // Qwen3-235B-A22B shape: 94 layers, 4 KV heads
	}
	layouts := []layout{{1, 8}, {2, 4}, {4, 2}, {8, 1}}

	for _, m := range models {
		fmt.Printf("%s (%.0f GiB of weights) on %d x %.0f GiB GPUs\n", m.name, m.weightGiB, gpus, gpuGiB)
		fmt.Printf("  %-12s %4s %14s %5s %11s %10s\n", "layout", "fits", "KV tokens/rep", "dup", "throughput", "step time")
		for _, l := range layouts {
			free := gpuGiB*util - m.weightGiB/float64(l.tp) - otherGiB
			name := fmt.Sprintf("-tp %d -dp %d", l.tp, l.dp)
			if free <= 0 {
				fmt.Printf("  %-12s %4s\n", name, "no")
				continue
			}
			// Each GPU stores max(1, kvHeads/tp) heads' worth of the cache.
			headsPerGPU := math.Max(1, float64(m.kvHeads)/float64(l.tp))
			perGPUKiB := m.kvPerTokKiB * headsPerGPU / float64(m.kvHeads)
			tokens := free * GiB / (perGPUKiB * 1024)
			dup := math.Max(1, float64(l.tp)/float64(m.kvHeads)) // copies of each KV head

			step := 1/float64(l.tp) + tpOverhead*math.Log2(float64(l.tp)) // relative to tp=1
			throughput := float64(l.dp) / step

			fmt.Printf("  %-12s %4s %14.0f %4.0fx %10.1fx %9.2fx\n", name, "yes", tokens, dup, throughput, step)
		}
		fmt.Println()
	}
	fmt.Println("throughput and step time are relative to one GPU at -tp 1 (hypothetical when it does not fit)")
}

Output:

8B dense (15 GiB of weights) on 8 x 80 GiB GPUs
  layout       fits  KV tokens/rep   dup  throughput  step time
  -tp 1 -dp 8   yes         455475    1x        8.0x      1.00x
  -tp 2 -dp 4   yes        1033830    1x        6.5x      0.62x
  -tp 4 -dp 2   yes        2190541    1x        4.1x      0.49x
  -tp 8 -dp 1   yes        4503962    1x        2.1x      0.48x

70B dense (132 GiB of weights) on 8 x 80 GiB GPUs
  layout       fits  KV tokens/rep   dup  throughput  step time
  -tp 1 -dp 8    no
  -tp 2 -dp 4   yes          31785    1x        6.5x      0.62x
  -tp 4 -dp 2   yes         494469    1x        4.1x      0.49x
  -tp 8 -dp 1   yes        1419837    1x        2.1x      0.48x

235B MoE (438 GiB of weights) on 8 x 80 GiB GPUs
  layout       fits  KV tokens/rep   dup  throughput  step time
  -tp 1 -dp 8    no
  -tp 2 -dp 4    no
  -tp 4 -dp 2    no
  -tp 8 -dp 1   yes         353616    2x        2.1x      0.48x

throughput and step time are relative to one GPU at -tp 1 (hypothetical when it does not fit)

How to read it:

  • 8B: eight replicas win on throughput by a wide margin. Higher TP only shortens the step, and beyond TP 4 barely that.
  • 70B: -tp 2 fits but leaves only about 32,000 tokens of cache per replica, a handful of long conversations. -tp 4 -dp 2 is the practical choice. Fitting decides first; preference comes second.
  • 235B: only -tp 8 fits, and with 4 KV heads the cache is held twice. That 2x is what -dcp 2 would remove. (A real deployment of this MoE model would more likely use -dp 8 --enable-expert-parallel, or quantise.)

7. Performance implications#

  • Communication grows with TP. Two all-reduces per layer per step. On NVLink inside one node they are cheap; across nodes over InfiniBand they dominate, which is why TP stays inside a node and PP or EP crosses nodes (14.m).
  • PP adds no per-request speed. It adds throughput by keeping stages busy, and costs a little latency per stage hop.
  • DP is close to linear for dense models. The only shared cost is the API server, which --api-server-count scales out.
  • EP’s cost is the all-to-all and the slowest rank. Every rank waits for the most-loaded expert. EPLB and --prefill-schedule-interval exist to even this out.
  • KV duplication wastes memory silently. TP larger than the KV-head count stores the same cache several times; check before adding GPUs, and use DCP.

8. Production implications#

  • CPU cores. At least one physical core per process: API servers + engine cores + workers (+1 for the coordinator) (16.d).
  • Startup. Every worker loads its shard, compiles and captures graphs. Persisted compile caches and vllm preload (19.e) matter more as N grows.
  • Failure. By default, one worker dying takes down its engine core, and with one engine the whole server. An opt-in fault-tolerance mode for multi-engine deployments exists (--enable-fault-tolerance); treat it as new.
  • Multi-node hygiene. Every node needs the same container image, model path and package versions. Set VLLM_HOST_IP to an address on a private network on each node: the traffic between nodes is unencrypted, and the documentation warns it can be exploited to run code if an attacker reaches that network. On InfiniBand clusters, GLOO_SOCKET_IFNAME=eth0 avoids a known start-up hang.
  • EP kernels need extra installs. DeepEP, DeepGEMM and, for disaggregation, gdrcopy; see the expert-parallel deployment guide.

9. Common mistakes#

  1. Using TP for a model that fits on one GPU when the goal is throughput. Use replicas.
  2. TP across nodes. Two all-reduces per layer over the network; use PP or EP across nodes.
  3. Forgetting --max-num-seqs is per DP rank, then setting --max-num-queued-reqs to the same number and rejecting requests while ranks sit half empty. Size the queue cap at roughly dp × max_num_seqs plus the queue depth you want.
  4. Expecting DP to share a prefix cache. Each rank has its own; route related requests to the same rank or replica.
  5. Raising TP past the KV-head count for more cache. It duplicates the cache instead; use DCP.
  6. Mismatched flags across nodes for a multi-node EP run. --enable-expert-parallel, --all2all-backend and the DP sizes must agree on every node.

10. Hands-on exercise#

  1. Run layouts.go. Set tpOverhead to 0.02 (an excellent interconnect) and to 0.4 (none). How does the best layout for the 8B model change?
  2. Change gpuGiB to 48 (an L40S-class card). Which layouts fit the 70B model now?
  3. Add a field for DCP and divide the 235B model’s per-GPU cache by it when dup > 1. How many tokens does -tp 8 -dcp 2 give?
  4. On a two-GPU machine, benchmark -tp 2, -dp 2 (or two independent servers) and -pp 2 with the same load (19.d). Record throughput and time per output token for each.
  5. Start vllm serve with -tp 2 -dp 2 and list the processes. Match each to a row of section 5.

11. Interview questions#

  1. Under tensor parallelism of 4, how many schedulers and how many block pools exist? Under -dp 4?
  2. Why must an idle DP rank still run forward passes for an MoE model with expert parallelism?
  3. Eight GPUs, a model that fits on one. Which layout maximises throughput, and what do you give up?
  4. A model has 8 KV heads and you run it at -tp 16. What happens to the KV cache, and what flag helps?
  5. How does vLLM’s internal DP load balancer choose a rank, and what does it not take into account?
  6. When would you choose deepep_low_latency over deepep_high_throughput?

12. Further reading#

Checked on 12 November 2026 against vLLM v0.32.0.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in