Sub topic 12
Scaling across GPUs with tensor parallelism
This chapter assumes you can start a server with vllm serve, and that you know what the KV cache is and how gpu_memory_utilization and max_model_len affect it. You also need a basic idea of what a GPU interconnect is (PCIe, NVLink). By the end you should be able to decide when a model needs several GPUs, launch it, and diagnose the usual startup failures.
Why one GPU is sometimes not enough
Model weights must sit in GPU memory for every forward pass. A rough estimate for 16-bit weights is two bytes per parameter. A 32-billion-parameter model needs about 65 GB for weights alone, before any KV cache. No 24 GB or 40 GB card holds that.
You have three ways out. Quantization shrinks the weights (see the previous chapter). A bigger GPU holds more. Or you split the model across several GPUs. Tensor parallelism is vLLM's main way to do the third.
How tensor parallelism works
Tensor parallelism (TP) splits each layer's weight matrices across GPUs. Every GPU holds a slice of every layer. For one transformer layer:
- The attention projections are split by attention head, so each GPU computes its own subset of heads.
- The feed-forward matrices are split by column in the first matrix and by row in the second.
- After the attention output projection and after the feed-forward block, the GPUs combine their partial results with an all-reduce. This is a collective operation, run by NCCL, that sums partial results from all GPUs and gives every GPU the total.
Each GPU also stores only its share of the KV cache, because it only computes its own heads. So TP divides both weights and cache.
The all-reduce runs twice per layer, so a 64-layer model does 128 of them for every generated token. That is the cost of TP. Its speed depends on the interconnect, which is why TP across NVLink-connected GPUs in one machine performs far better than TP over PCIe.
Launching a TP server
The --tensor-parallel-size flag sets how many GPUs share the model. This command is the one from the spine:
vllm serve Qwen/Qwen2.5-32B-Instruct \
--tensor-parallel-size 4 \
--max-model-len 8192 \
--enable-prefix-cachingvLLM starts one worker process per GPU. The API stays the same, so the OpenAI client code from earlier chapters works unchanged. The Python API takes the same setting:
from vllm import LLM, SamplingParams
def main():
llm = LLM(
model="Qwen/Qwen2.5-32B-Instruct",
tensor_parallel_size=4,
max_model_len=8192,
gpu_memory_utilization=0.90,
)
params = SamplingParams(temperature=0.2, max_tokens=64)
outputs = llm.chat(
[{"role": "user", "content": "Name one benefit of tensor parallelism."}],
params,
)
print(outputs[0].outputs[0].text)
if __name__ == "__main__":
main()The if __name__ == "__main__": guard matters. vLLM may start worker processes with the spawn method, which imports your script again. Without the guard, each worker would try to build its own LLM.
How memory changes with TP
gpu_memory_utilization applies per GPU, not to the total. With four GPUs and a value of 0.90, vLLM budgets 90% of each card.
The per-GPU arithmetic is simple. Weights per GPU are roughly total weights divided by TP size. The KV budget per GPU is what remains of the 90% after weights and activation memory. The next script estimates it. It uses approximate numbers and ignores activation overhead, so treat the result as an upper bound.
def per_gpu_budget(params_billion, bytes_per_param, gpu_gb, tp, util=0.90):
weights_gb = params_billion * bytes_per_param / tp
budget_gb = gpu_gb * util
return weights_gb, budget_gb - weights_gb
for gpu_gb in (24, 40, 80):
w, kv = per_gpu_budget(32.5, 2, gpu_gb, tp=4)
print(f"{gpu_gb} GB GPU: weights {w:.1f} GB, left for KV and activations {kv:.1f} GB")On 24 GB cards the result is about 16 GB of weights and 5 GB left. That is enough to start, but only for a small number of concurrent sequences. On 80 GB cards you get roughly 56 GB per GPU for the cache. This shows a side effect of TP: the weights get cheaper per GPU, so the freed memory becomes KV cache, and throughput can improve more than the GPU count alone suggests.
Rules and constraints
The TP size must divide the number of attention heads. Qwen2.5-32B has 40 query heads and 8 key/value heads. Sizes 1, 2, 4, and 8 all work, because 40 and 8 are both divisible by each of them. A size of 3 fails, because 40 is not divisible by 3. vLLM reports an error at startup in that case.
When the TP size exceeds the number of KV heads, vLLM replicates KV heads across GPUs. This works but wastes some cache memory.
Other practical rules:
- Use GPUs of the same type. The slowest or smallest card sets the pace and the memory budget for all of them.
- Keep TP inside one machine when you can. Across machines, the all-reduce goes over the network and latency rises sharply. For multi-node setups vLLM also offers pipeline parallelism (
--pipeline-parallel-size), which splits the model by layers and sends less data between stages. Use TP within a node and pipeline parallelism across nodes. - Choose the smallest TP size that fits the model with room for KV cache. More GPUs do not make a single request proportionally faster.
Choosing between TP, quantization and prefix caching
| Situation | First choice |
|---|---|
| Weights do not fit on one GPU | Quantization if quality loss is acceptable, otherwise TP |
| Weights fit, but KV cache is small | Raise `gpu_memory_utilization`, lower `max_model_len`, or add TP to free memory |
| Many requests share a long system prompt | `--enable-prefix-caching` |
| Latency per token is the target and GPUs have NVLink | TP, measured with a benchmark |
These options combine. A quantized model can also use TP, and prefix caching works with both.
Common errors
- Not enough GPUs. If
--tensor-parallel-sizeis larger than the visible device count, startup fails. Checknvidia-smiand theCUDA_VISIBLE_DEVICESvariable, which limits which GPUs the process sees. - Head count not divisible. Pick a size that divides the model's attention head count. Read
num_attention_headsin the model'sconfig.json. - Out of memory on one GPU. Another process may already hold memory on one card. vLLM checks free memory per device, so one busy GPU can fail the whole launch.
- Hangs or NCCL errors at startup. Often caused by blocked peer-to-peer access or too little shared memory. In Docker, pass
--ipc=hostor a larger--shm-size, as in the container chapter. SettingNCCL_DEBUG=INFOprints what NCCL is doing. - Duplicate
LLMcreation in scripts. Missing the__main__guard, described above.
After launch, confirm that every GPU is used and that the cache sizes look right. The startup log reports the number of GPU blocks available for the KV cache, and the vllm: metrics from /metrics show running and waiting requests. A benchmark run at your target concurrency tells you whether the TP size was worth it.
Exercise
You want to serve a model with 48 attention heads on a machine with 6 GPUs, and you plan to set --tensor-parallel-size 6. Is that valid? Give one other TP size that definitely works on this machine, and say what changes in memory per GPU when you use it.
Show answer
Yes, it is valid. 48 is divisible by 6, so each GPU gets 8 heads (assuming the number of KV heads also fits, or vLLM replicates them). Sizes 1, 2, and 4 also divide 48 and fit within six GPUs; with 4, each GPU holds one quarter of the weights and one quarter of the KV cache instead of one sixth, so weights use more memory per GPU and less is left for the cache. Remember that the all-reduce cost grows with GPU count, so the smallest size that leaves enough KV cache is usually best.