Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

Parallelization Strategies for LLM Inference: A Comprehensive Guide

This article breaks down five key parallelization strategies for LLM inference: data parallelism, tensor parallelism, pipeline parallelism, context parallelism, and expert parallelism. It analyzes each approach's state partitioning and replication, inter-device communication patterns, and their impact on memory usage, latency, and throughput to help you choose the optimal configuration based on your model size, hardware, and workload.

LLM inferenceparallelization strategiestensor parallelismpipeline parallelismdata parallelism

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

🔗 Original link: Parallelism strategies for LLM inference, clearly explained

Avi Chawla · X · @_avichawla · 2026-10-06 19:07

📌 This article is a reprint. All copyrights belong to the original author. The full text is subject to the original link.

Everything you need to understand how to distribute LLM inference across multiple GPUs without losing performance due to communication. Covers data parallelism, tensor parallelism, pipeline parallelism, context parallelism, and expert parallelism, how to combine them, and the deployment checklist for deciding which layout best suits your model, hardware, and workload.


Four GPUs provide four separate memory spaces and four independent processors. They do not function as a single GPU with four times the capacity.

A kernel running on one GPU cannot access weights or KV cache blocks stored on another GPU unless that data is first transferred over.

Distributed inference therefore begins with data placement. The serving engine assigns weights, activations, requests, and cached keys and values to specific devices.

Any cross-device dependency adds a transfer or collective operation to the request path.

The engineering challenge is to choose a layout that removes the current bottleneck without introducing more communication than the hardware can tolerate. This is exactly what we will solve next.

By the end of this article, you should be able to inspect your model, workload, GPU topology, and latency targets, then select a reasonable first-draft layout.

We will compare each strategy using five questions:

  • Which states are partitioned?
  • Which states remain replicated?
  • What data needs to be transferred across the interconnect?
  • How frequently does this transfer occur?
  • Does this layout primarily improve memory capacity, request latency, or throughput?

Throughout the article, we will assume the same four-GPU server. The model requires at least two of these GPUs. The server simultaneously receives both short chat requests and long-context requests. We will keep the model, workload, and hardware fixed, changing only how the inference work is distributed across the GPUs.

We will use the term “collective operation” in this article. A collective operation is when multiple GPUs, acting as a group, exchange or combine data. For example, two GPUs may each compute a portion of a layer’s output. An all-reduce operation adds those portions together and delivers the complete result to both GPUs simultaneously. Other collective operations move different pieces of data among the participating GPUs. Every participating GPU must finish its portion before the collective can complete. Therefore, a slow GPU or slow link can delay the entire group. This differs from a direct transfer, in which one GPU simply sends data to another.


How LLM Inference Works

Before we can understand how to optimize LLM inference, we first need to understand how LLM inference actually works.

LLM inference consists of two distinct phases.

  • Prefill: Processes the prompt and builds its key-value (KV) cache. It handles a large number of prompt tokens in parallel, typically using large matrix multiplications. Prefill has a strong impact on the time to the first token, commonly referred to as TTFT (Time To First Token).

  • Decoding: Generates subsequent tokens one by one. At each step, it reads the model weights and the continuously growing KV cache. Decoding strongly affects the time per output token, commonly known as TPOT (Time Per Output Token). Some systems also report inter-token latency.

These two phases utilize hardware in very different ways.

  • Prefill typically performs large matrix multiplications across many prompt tokens at once.
  • Decoding performs smaller operations and repeatedly reads the model weights and KV cache. A memory layout that reduces prefill time may slow down decoding by increasing the number of synchronous operations required for each generated token.

I covered this in detail in the following article if you’d like to dive deeper:

There are typically four resource constraints that determine deployment feasibility:

  1. Parameter memory — determines whether the model can fit in memory at all.
  2. KV cache memory — limits the maximum number of resident tokens and concurrent requests.
  3. GPU compute time — covers local matrix operations.
  4. Communication time — covers data transfer and collective operations between devices.

Service metrics must align with the underlying product goals:

  • TTFT measures how quickly the initial response appears.
  • TPOT measures the speed of streaming output.
  • Request throughput counts the number of completed requests.
  • Token throughput distinguishes between input and output workloads.
  • Goodput (effective throughput) only counts requests that meet the service-level objectives.

Averaging any of these metrics inevitably hides tail latency. This is why median and high-percentile values (p95, p99, etc.) must be reported.

For example, a p95 TTFT represents the threshold that 95% of requests meet. It should be compared against the service target under the same request distribution.

Note: Tokens-per-second numbers without latency constraints can be misleading. A fully loaded server may report high throughput while violating its tail latency targets.

These metrics tell us which service goals are not being met. Resource measurements then tell us whether the bottleneck is memory, compute, or communication.

The next decision is how to distribute inference work across GPUs to address that specific constraint.

This is exactly what parallelization strategies do. Each approach partitions different parts of the workload and introduces different communication overheads. The comparison table below serves as a roadmap for the techniques we will examine next.

The Communication column in the table above is particularly important. While the size of the transferred data matters, the frequency of transfers is equally critical. For instance, small all-reduce operations repeated in every decoder layer can cost more than a single larger activation transfer between pipeline stages.

We will start with data parallelism, because it keeps each forward pass within a single model replica. The other methods split a single forward pass across multiple GPUs, placing communication directly on the critical execution path.

1) Data Parallelism

Data parallelism splits incoming requests across multiple model replicas.

Each replica stores a complete copy of the model. It also maintains its own scheduler and KV cache. A router forwards each request to one of the replicas.

This differs from data parallelism used during training.

Because the inference phase does not require gradient synchronization after each forward pass, a request stays local to the replica it was assigned to.

Suppose a two-GPU replica meets the latency target but cannot keep up with the incoming request rate.

On our four-GPU server, data parallelism allows us to launch a second two-GPU replica. The two replicas process different requests concurrently. This configuration therefore targets higher throughput rather than lower latency for a single request.

  1. The first deployment check is memory capacity.

Each replica must hold the full two-GPU model layout, which means the four-GPU server needs to store the model twice.

Therefore, data parallelism is only viable after a complete replica already fits in memory. It cannot solve model placement issues by itself.

  1. The second check is request routing.

Once both replicas are active, the router decides which queue and KV cache pool each request should enter.

Round-robin routing treats the two replicas as equally available, even if one has a longer queue, less free KV capacity, or already holds cached prefixes that could be reused.

  1. The third check is admission capacity.

A request consumes very little KV memory upon arrival, but consumption grows as tokens are added during decoding.

The router must reserve capacity for this growth. Otherwise, a replica might accept a request that fits during the prefill phase but runs out of KV space during generation.

Here is a practical engineering rule: After adding a replica, route requests based on queue latency, available KV capacity, and prefix cache hit rate. Before accepting a request, reserve KV space for its expected decode length.

This also explains when data parallelism provides no benefit.

At low traffic levels, the second replica remains idle and cannot reduce the latency of any individual request. Data parallelism is only useful when the full model replica fits in memory and the request concurrency is high enough to keep multiple replicas busy.

2) Tensor Parallelism (Tensor Parallelism)

Suppose the model does not fit on a single GPU, but can fit when its largest weight matrices are split across two GPUs.

Data parallelism cannot solve this problem, because each replica still requires a complete copy of the model. Tensor parallelism can, because it allows multiple GPUs to work together on the same Transformer layer and the same request.

This makes tensor parallelism first and foremost a model placement tool. It can also reduce the computation time of large operations, but only when the compute saved exceeds the cost of inter-GPU communication.

The original Megatron-LM paper explains the common two-projection structure. We can see this dependency through a feed-forward block.

The first projection creates intermediate activations. The second projection restores them to the hidden width.

The diagram below labels the input, the two weight matrices, the activation function, the intermediate tensor, and the output.

When using two ranks, we split the first weight matrix along the column dimension. Each rank computes a different set of intermediate features.

We split the second matrix along the row dimension, so each rank consumes the matching slice of features. The two ranks then produce partial output tensors.

Each GPU computes a matrix multiplication using its local weight shard. An all-reduce then sums these partial tensors. Until this collective communication completes, neither GPU has the correct layer output.

python
import numpy as np

def tensor_parallel_output(x, a_shards, b_shards, activation=np.tanh):

    partials = []

    for a_shard, b_shard in zip(a_shards, b_shards, strict=True):
        hidden_shard = activation(x @ a_shard)
        partials.append(hidden_shard @ b_shard)

    return np.sum(partials, axis=0)

This function follows the two-rank data dependency. Each rank uses matching matrix shards. Since each local result contains only a portion of the output, a reduction is required.

Running the test example produces the following output:

tensor_parallel_output = [[-3.294438, 1.406896]]

The unsharded MLP produces the same two values. The test checks each output element within NumPy’s floating-point tolerance.

The attention mechanism follows the same general idea.

  • Query, key, and value projections can be split across attention heads.
  • The output projection then merges the partial results.
  • The exact layout depends on multi-head attention, grouped-query attention, and model-specific kernel implementations.

Before choosing a tensor parallelism degree, two terms need to be clarified.

  • A tensor parallel group refers to a set of GPUs that collectively process one request.
  • A rank is one GPU process within that group. TP2 has two ranks, while TP4 has four.

Increasing the TP degree splits each sharded matrix into more pieces. Consider a matrix with 8192 output columns.

  • TP2 assigns 4096 columns to each rank.
  • TP4 assigns 2048 columns to each rank.

As a result, each GPU stores fewer weights and performs smaller matrix multiplications.

This may sound like a straightforward improvement, but the layer cannot continue with separated partial results.

The ranks must exchange or combine them.

Therefore, although TP4 gives each rank less local work, it involves twice as many ranks as TP2. Whether TP4 is faster depends on the balance between compute savings and increased communication.

This leads us to three deployment checkpoints.

  1. The first check is whether the model actually fits.

Sharding reduces memory for the split weight matrices. Other allocations may remain replicated on every rank.

These include some parameters, temporary buffers, CUDA graphs, and KV cache allocations. Always measure peak memory on each GPU. Do not assume TP2 will halve every allocation.

  1. The second check is how much time each rank spends on communication.

Tensor-parallel collective operations merge partial results inside many Transformer layers. Slow links can cause GPUs to wait after every local computation. This waiting occurs during both prefill and every decoding step.

  1. The third check is whether each rank still receives enough work.

GPUs run large matrix multiplications efficiently because they inherently expose massive parallelism.

Raising the TP degree makes each local matrix smaller. At some point, the smaller computation under-utilizes the GPU while the collective operations still occur.

Attention heads and quantization layouts introduce additional constraints. For example, a head or quantization group may need to remain intact on a single rank. Therefore, the model shape and serving engine determine which TP degrees are valid.

TP2 can outperform a single GPU on large prefills, because both ranks receive substantial work.

TP4 may help further while compute still dominates. It can also become slower once smaller local operations no longer hide the increased communication.

Decoding reaches this point earlier, because a single token provides far less matrix work than a long prompt.

A common engineering rule is to use the smallest tensor parallelism degree that satisfies both memory and latency requirements. Re-measure after every increase.

The links between ranks determine communication cost. NVLink and NVSwitch differ significantly from inter-node networks in both latency and bandwidth.

For our four-GPU server, start with TP2, since the model requires two GPUs.

If that layout meets the latency target, the remaining two GPUs can form a second TP2 replica to increase throughput.

Only move to TP4 if TP2 still cannot satisfy memory or single-request latency requirements. TP4 uses all four GPUs for every request and eliminates the possibility of running a second replica.

Use tensor parallelism to solve per-replica fitting problems or measured single-request compute limits. Do not increase the degree simply because more GPUs are available.


3) Pipeline Parallelism

When the per-layer collective operations of tensor parallelism span slow interconnects, they become very costly.

If the model must run across GPUs with weaker connectivity, pipeline parallelism offers an alternative layout: the model is partitioned by depth, with each stage keeping a contiguous group of layers. Activations are transferred only when execution moves between stages.

Thus, stage zero runs the first group of layers and sends its hidden states to stage one. The final stage runs the last group and produces the logits.

Requests still visit each stage sequentially, but the weights of any given stage remain local to its GPU or tensor-parallel group.

This is different from traditional training pipelines.

Inference has no backward pass. Continuous batching allows multiple groups of requests to stay in flight. An autoregressive sequence still depends on its preceding tokens.

Therefore, pipeline parallelism solves the model placement problem with lower communication frequency than tensor parallelism.

This makes it a useful candidate when spanning nodes or GPUs without fast point-to-point links. It does not automatically reduce latency for an individual request, because that request must still pass through all stages.

Micro-batching provides each stage with independent work.

During online serving, these micro-batches may contain different requests. Continuous batching changes membership as requests complete. The scheduler must preserve pipeline ordering while filling newly available slots.

The first deployment check is whether the workload can supply enough independent requests to keep all stages busy.

Stages sit idle during warmup and drain phases. Too few micro-batches increase this idle fraction, so lightly loaded online services may effectively use only one stage at a time.

The second check is stage balance.

An 80-layer model with PP4 would suggest 20 layers per stage, but equal layer counts do not guarantee equal execution time or memory usage. Embedding layers, output layers, and heterogeneous blocks all distort the split. The slowest stage determines throughput while faster stages wait.

A practical engineering rule is to balance stages using measured execution time and memory usage. Equal layer counts are only a starting placement.

The third check is activation buffering and operational cost. Activations remain live while requests travel through the pipeline. The scheduler must maintain ordering; a failure in any stage affects the entire model instance.

For our four-GPU server, PP4 only makes sense when the model requires all four GPUs and the number of in-flight requests is large enough to fill all four stages.

If the hardware consists of two pairs of fast GPUs connected by a slower path, then using PP2 + TP2 within each pair keeps the frequent tensor collective communication inside each pair, while activations cross the slower boundary.

Use pipeline parallelism when model depth must cross devices and stage-boundary transfers better match the topology than per-layer tensor collectives. It should be avoided for low-concurrency traffic unless the model leaves no other choice.


4) Context Parallelism

Assume the weights are now properly placed, yet long-context requests still fail one of two tests.

A large prompt may miss the TTFT target during the prefill phase, or its KV cache may consume so much memory that too few requests can stay active during decoding.

Context parallelism addresses these issues by partitioning sequence positions rather than model weights.

The two failure modes require different mechanisms:

  • Prefill Context Parallelism (PCP) splits the work of the incoming prompt.
  • Decode Context Parallelism (DCP) partitions the stored KV history used by subsequent tokens.

Prefill Context Parallelism (PCP)

Prefill context parallelism divides the prompt tokens across ranks. Each rank computes query, key, and value tensors for its local token chunk. The attention algorithm must still expose every query to the required keys and values.

One implementation is to all-gather the keys and values on each rank. Each rank then evaluates the full history against its local queries.

This only works when the gathered tensors fit in memory.

Another family of approaches circulates partial key-value blocks. Ring-attention-style algorithms incrementally combine partial attention results.

They avoid materializing the full sequence everywhere but require multiple communication rounds.

The practical question is where the crossover point lies—when PCP turns from overhead into a net win. Measure TTFT by prompt-length buckets rather than only at maximum context length.

Long prompts may contain enough attention work to amortize the communication cost. Short prompts usually do not. Therefore, a mixed service may route only long-context requests to PCP-enabled workers.

Decode Context Parallelism (DCP)

Decode Context Parallelism partitions the stored KV cache by sequence position.

Each rank is responsible for its local history. The ranks then merge partial attention outputs and softmax statistics.

python
import numpy as np

def merge_attention_partials(partials):
    global_max = max(part.maximum for part in partials)
    scales = [np.exp(part.maximum - global_max) for part in partials]
    denominator = sum(
        scale * part.exponential_sum
        for scale, part in zip(scales, partials, strict=True)
    )
    numerator = sum(
        (
            scale * part.weighted_value
            for scale, part in zip(scales, partials, strict=True)
        ),
        start=np.zeros_like(partials[0].weighted_value),
    )
    return numerator / denominator

Each rank reports its local maximum, exponential sum, and weighted value sum.

The global maximum is used to rescale every contribution before the final reduction. This ensures a numerically stable softmax across KV shards. The project files include tests that compare the result against un-sharded attention.

Running locally produces the following merged attention output:

merged_attention_output = [0.769627, 0.779901]

The complete attention computation yields the same result. This confirms that splitting the KV history does not change the attention output for the test input.

The maximum is required because the exponentials can overflow. Subtracting the global maximum ensures that every exponential is at most 1.

The scaled denominator and weighted value sums then reconstruct the un-sharded attention result within normal floating-point tolerance.

  1. The first DCP check is memory.

Record the number of resident KV tokens and maximum concurrency before and after sharding.

  1. The second is decode cost.

Every decoder layer must merge partial attention results, which can increase TPOT. DCP is only worthwhile when the extra KV capacity or supported context length justifies this repeated merging.

Sequence parallelism is related but not identical.

Megatron-style sequence parallelism typically shards activations around normalization and similar operations. Context parallelism, on the other hand, partitions attention across context positions. Frameworks sometimes use these labels differently.

For our four-GPU server, keep normal chat traffic on the baseline TP2 replicas. If prompt-length testing shows improved TTFT, route occasional long prompts to the group with PCP enabled.

Add DCP only when KV memory (rather than weight memory or compute) is the limiting factor on the number or length of active requests.

PCP solves the compute problem for long prompts. DCP solves the storage problem for long histories. Treat them as independent decisions—do not enable either without prompt-length or KV-capacity measurements to support the choice.


5) Expert Parallelism (EP)

Expert parallelism applies only to models that contain Mixture-of-Experts (MoE) layers.

In this case, even if each token uses only a small number of experts, storing every expert on every GPU can still dominate parameter memory usage.

Expert parallelism places different experts on different ranks, allowing a single model instance to distribute this portion of expert weight memory.

At runtime, the router selects experts for each token. The system sends each token’s representation to the ranks that hold the chosen experts, runs the local expert networks, and returns their outputs.

This placement saves memory but introduces all-to-all communication traffic that depends on data along the request path.

The first deployment checkpoint is placement. Count the expert weight memory per rank and verify that the shared attention, embeddings, buffers, and KV cache still fit. Expert parallelism does not dictate how the dense parts of the model are placed.

The second checkpoint is routing traffic. Unlike dense tensor parallelism, the number of bytes transferred depends on which experts the router selects. Measure the bytes sent per rank and the all-to-all time using real prompt distributions.

The third checkpoint is load imbalance. The number of tokens per expert can be skewed, and collective communication only completes when the heaviest rank finishes.

Average load can hide these stragglers. Measure the maximum number of tokens per expert, local expert execution time, and post-computation wait time. Expert capacity, padding, and load-balancing strategies can affect both runtime and (if tokens are dropped) model behavior.

On four GPUs, an MoE model can assign one-quarter of its experts to each GPU while using TP or DP for attention and other dense operations.

This layout is attractive when expert weights are the limiting factor and routing remains balanced. It becomes unattractive when the expert set already fits comfortably or when all-to-all communication dominates layer time.

Attention and expert layers do not need to use the same sharding strategy. Dense attention can use DP or TP, while the MoE layer uses EP.

Use expert parallelism to solve expert weight placement. Validate it with per-rank routing and imbalance measurements, not just average token throughput.


6) Hybrid Parallelism

A single parallelism strategy often solves only part of the deployment problem.

Tensor parallelism can fit the model within a node, pipeline parallelism can scale it across nodes, and data parallelism can then add enough replicas to meet the required request rate.

Hybrid layouts combine these choices, but each added dimension also introduces its own scheduler or communication path.

For independent dense model groups, the total number of workers is the product of data, pipeline, and tensor parallelism degrees.

Some context parallelism methods reuse existing ranks. Expert groups can also interact with data groups in different ways.


Consider eight GPUs spanning two four-GPU nodes. Intra-node links offer higher bandwidth and lower latency. One candidate layout uses TP4 within each node and PP2 across nodes.

This keeps frequent layer collective communication local. Only the activation values at stage boundaries cross the slower network. All eight GPUs form a single model instance.

If the model can fit on four GPUs, another layout becomes attractive: TP4 within each node and DP2 across nodes, creating two replicas. Requests no longer depend on cross-node paths.

Build hybrid layouts in this order. First choose the smallest TP group that makes each stage fit and place it on the fastest links.

Add PP only when the model must cross slower boundaries. Add DP only after a complete model instance fits. Add CP for measured long-context workloads, and add EP only for MoE expert placement.

This order prevents a common mistake: multiplying parallelism degrees before deciding which resource bottleneck each dimension is solving. Every new dimension should have a clear purpose and a measurement that validates it.

Prefill/decode disaggregation is useful when the two phases require different hardware or scaling ratios.

Independent worker pools handle each phase, so the prefill pool can be biased toward large prompt computation while the decode pool is biased toward KV capacity and stable token generation. This introduces KV state transfer and coordination boundaries.

Disaggregation does not replace TP, PP, or CP. Each worker pool still needs its own model placement strategy.

A hybrid layout is successful only when every communication pattern matches the physical network. Place the most frequent collective communication on the fastest links, then validate the complete layout under production request mixes.

A Practical Decision Framework

Use this framework from top to bottom.

After selecting the minimal change that resolves the currently measured bottleneck, stop and benchmark. Only return to the framework if another constraint still exists.

Stacking all available parallel modes simultaneously makes attribution much harder and can increase communication without solving the actual problem.

First determine whether a full copy of the model can fit on a single GPU while still leaving enough KV cache capacity for the target concurrency level.

  • If it fits, start with a single replica. Add data parallelism only when traffic volume requires another scheduler. Preserve prefix locality in the router.

  • If it does not fit, find the smallest effective tensor parallelism degree. Benchmark decoding latency at that degree. Consider pipeline parallelism when layer groups have similar execution times or peer-to-peer links are slow.

If the model must span multiple nodes, keep tensor parallelism within the faster intra-node links. Test pipeline parallelism across nodes. Measure per-stage balance before increasing load.

Long prompts create independent problems. When TTFT fails at large input lengths, evaluate PCP. When KV cache capacity limits concurrency or long-context decoding, evaluate DCP.

MoE models require additional considerations. If expert weights cause fitting issues, test expert parallelism while separately tracking token imbalance and all-to-all communication time. Do not add expert parallelism to dense models, and do not infer its benefit from overall GPU utilization.

Enable a parallel mode only when measurement confirms that it resolves the specific resource constraint.

First identify the constrained resource. Then choose the partitioning scheme whose communication pattern best matches the available interconnects.


Parallelism is usually a layout decision, not a GPU count setting. Start from the resource that is preventing the service from meeting its goals. Then choose the smallest layout change that removes that constraint.

Every split introduces communication, synchronization, or scheduling overhead. The memory or compute savings must outweigh that cost on real hardware and with real request distributions.

The best layout is the simplest one that meets both latency and throughput targets. Everything else still needs to be measured.