Back to paper library
Paper notesarXiv 2022MLSys 2023

Scaling Inference

Fast or Cheap?

Original paper

Efficiently Scaling Transformer Inference

Paper authors

Reiner Pope · Sholto Douglas · Aakanksha Chowdhery …

Show all 10 authors

Reiner Pope · Sholto Douglas · Aakanksha Chowdhery · Jacob Devlin · James Bradbury · Anselm Levskaya · Jonathan Heek · Kefan Xiao · Shivani Agrawal · Jeff Dean

Publication
MLSys 2023Conference
First submitted to arXiv
arXiv:2211.05102
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{transformersscalinginference2022,
  title = {{Efficiently Scaling Transformer Inference}},
  author = {Reiner Pope and Sholto Douglas and Aakanksha Chowdhery and Jacob Devlin and James Bradbury and Anselm Levskaya and Jonathan Heek and Kefan Xiao and Shivani Agrawal and Jeff Dean},
  year = {2022},
  eprint = {2211.05102},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2211.05102}
}
On this page

In April 2022, Google released PaLM, a 540-billion-parameter dense language model trained on 6,144 TPU v4 chips. During training, the whole text is available up front, so thousands of chips can each take different sequences and different positions and push forward together.

Once the model is trained and put to work, things change. A user sends in a passage, and the model can emit only one token at a time; the next token can't start until the previous one is finished. And for every token it emits, all 540 billion parameters have to be run through in full.

In November of the same year, ten Google authors wrote up their experience serving models like this in this paper; seven of them are also on the PaLM author list. The abstract and introduction give two numbers. On 64 TPU v4 chips, PaLM 540B takes just 29 ms per generated token (with weights quantized to int8); when it processes a large batch of inputs at once, the hardware's FLOPs utilization (MFU) reaches 76%.

How fast is 29 ms? In June 2023, gwern quoted the number on Hacker News, asked how many tokens per second a person speaks, guessed it was probably fewer than 34 (1,000 ms divided by 29 ms), and then said the real question was who would be willing to pay for it. (HN comment)

That remark goes straight to the heart of this paper. The 29 ms and the 76% were measured under two completely different settings. The first trades a small batch for low latency; the second trades a large batch for high utilization. Same model, same 64 chips, and the way you split the model depends on whether you want it fast or cheap. The paper sets out to answer how to choose between the two, and why.

Defining the problem

Two phases

First, split one generation run into two parts. The paper calls the part that processes the input prefill. Each of the BB sequences has LinputL_\text{input} tokens, all of which are available from the start, so they can be computed in parallel in a single forward pass. Then comes decode (the paper also calls it generation). Each step runs one forward pass and samples one new token for each sequence, for LgenL_\text{gen} steps in total, one after another.

The two parts have very different workload shapes. Prefill feeds in B×LinputB\times L_\text{input} tokens at once, so its matrix multiplications are wide and fat; decode has only one token per sequence at each step, so along the token dimension the matrix multiplication shrinks to BB. The paper therefore analyzes and measures the two parts separately, and even chooses how to partition the model separately for each.

Three yardsticks

The paper measures inference with three metrics:

  • Latency: the total time of one inference, split into prefill and decode; decode is also often divided by the number of generated tokens to give a “per-step” latency.
  • Throughput: how many tokens are processed or generated per second.
  • MFU (model FLOPs utilization): the actual throughput divided by the theoretical throughput the hardware would reach running at peak compute with no memory or communication overhead at all.

To compare different models and chip counts, the paper also expresses cost as the chip-seconds spent per token:

cost=nchips×timeBL\text{cost}=\frac{n_\text{chips}\times\text{time}}{BL}

This number is proportional to operating cost and inversely proportional to MFU. Latency is how fast things feel to the user; cost is how expensive they feel to whoever pays. gwern was asking about the latter.

Where the time in each step goes

The paper splits the time of one forward pass into three parts:

  • Memory time: the weights and the KV cache sit in the chip's high-bandwidth memory (HBM), and every forward pass has to move them from HBM to the compute cores once. The KV cache holds the keys and values each attention layer has already computed; it stays around for the whole generation, because later tokens need to read it.
  • Compute time: for a decoder model with NN parameters, each token's forward pass takes 2N2N matmul FLOPs, one multiply and one add per parameter per token. Attention's own FLOPs are relatively small in large models and can often be ignored; but the KV cache is one copy per sequence, and in memory capacity and bandwidth it is anything but small.
  • Communication time: when a model is too big for one chip, it has to be split across many chips, and the chips must exchange intermediate results.

Memory time for reading weights and compute time outside attention are roughly proportional to model size and inversely proportional to chip count, so adding chips makes them faster; the time to read the KV cache grows with batch and context length, B×LB\times L. Communication time falls more slowly, and with some partitionings it doesn't fall at all, so as chips are added it becomes the bottleneck.

Running the numbers

Definitions alone don't give much sense of which part is bigger, so let's work it out with the paper's own numbers. The hardware is TPU v4:

  • 275 TFLOPS bf16 peak per chip
  • 32 GiB HBM per chip, with 1,200 GB/s bandwidth

The model is PaLM 540B, split across 64 chips, running one decode step. The batch holds BB sequences, each generating one token.

Start with reading the weights. 540B parameters stored in bf16 take 2 bytes each, 1.08 TB in total, or 16.9 GB per chip on average:

Tweights=N×2 bytesnchips×1.2 TB/sT_\text{weights}=\frac{N\times 2\ \text{bytes}}{n_\text{chips}\times 1.2\ \text{TB/s}} =1.08 TB64×1.2 TB/s≈14.1 ms=\frac{1.08\ \text{TB}}{64\times 1.2\ \text{TB/s}}\approx 14.1\ \text{ms}

This time doesn't depend on batch size. A step reads the weights only once, and all BB sequences share them.

Next, the matrix computation:

Tcompute=2NBnchips×275 TFLOPST_\text{compute}=\frac{2NB}{n_\text{chips}\times 275\ \text{TFLOPS}} ≈0.061 ms×B\approx 0.061\ \text{ms}\times B

At B=1B=1, the computation takes only 0.061 ms, while reading the weights takes 14.1 ms, a 230× gap. The chip spends most of its time waiting for data to arrive from HBM.

Divide one expression by the other, and both NN and the chip count cancel out:

TcomputeTweights=B275/1.2≈B229\frac{T_\text{compute}}{T_\text{weights}}=\frac{B}{275/1.2}\approx\frac{B}{229}

Only when the batch reaches about 229 does compute time catch up with weight-reading time. This threshold depends only on the hardware's ratio of compute to bandwidth and on how many bytes each parameter takes; model size and chip count make no difference. The paper's end-to-end experiments also find that decode's per-token cost reaches its minimum only once the batch exceeds about 512, the same order of magnitude as this threshold.

Looking only at the weights, it seems you could just make the batch big and be done. The trouble is the KV cache. All sequences share the weights, but each sequence has its own KV cache, so as the batch grows, the amount of KV to read grows with it.

PaLM 540B uses multi-query attention (MQA), in which all attention heads share a single set of keys and values. Using the formula “K and V × layers × KV heads × dimensions per head × bytes per value,” with 118 layers, 1 KV head, 256 dimensions per head and bf16, each token needs:

2×118×1×256×2 bytes≈118 KiB\begin{aligned} &2\times118\times1\times256\times2\ \text{bytes}\\ &\quad\approx118\ \text{KiB} \end{aligned}

With a 2,048-token context, one sequence takes about 247 MB.

Section 2 of the paper gives a point of comparison. For a 500B-class model with ordinary multi-head attention, at batch 512 and context 2,048, the KV cache totals 3 TB, three times the model's parameters, or 5.9 GB per sequence on average.

Here are the parts of each step side by side:

Table: this note's estimate, based on the definitions in Sections 2 and 4 of the paper and the TPU v4 specs. 64 chips, context 2,048, assuming weights and KV are spread evenly across the chips, communication not counted.
Per stepB=1B=1B=512B=512
Read weights (bf16)14.1 ms14.1 ms
Matrix computation0.06 ms31.4 ms
Read KV (multi-head, 3 TB)0.08 ms39.1 ms
Read KV (MQA)0.003 ms1.65 ms

Look at the last two rows. With multi-head attention, each sequence reads 5.9 GB of KV per step, about 0.076 ms, which is longer than the compute that sequence gets (0.061 ms). However large the batch, KV reading time grows in proportion and never drops below compute time. On top of that, 3 TB by itself exceeds the total HBM of 64 chips (2 TiB), so it simply doesn't fit.

With MQA, each sequence's KV is only 247 MB, and reading it takes about 5% of the compute time. Once the batch grows, compute finally takes center stage.

This is what MQA is worth with long contexts and large batches. The table assumes the KV really is spread evenly across the 64 chips; as we'll see later, with the wrong partitioning, all the memory MQA saved goes right back.

Where it gets stuck

Put these numbers together, and the paper faces two requirements that pull against each other:

  • Fast: chatbots, for example. Use small batches and many chips to spread out each step's memory time; but with small batches MFU is low and per-token cost is high, and with many chips, communication starts eating into the time.
  • Cheap: offline scoring or distillation, for example, where only per-token cost matters. The bigger the batch the better, but a big batch makes the KV cache overflow memory; and some partitionings that do badly at small batches turn out to be the best at large ones.

So with a 540B model on 64 chips, how should the weights, activations and KV cache each be partitioned to get close to the limit under each of these two requirements?

Solving the problem

Some notation first

The paper runs on TPU v4, whose chips are connected as an X×Y×ZX\times Y\times Z 3D torus. The notation for sharding tensors follows GSPMD, with subscripts showing which axes a dimension is split across. For example, BLExyzBLE_{xyz} is a tensor of shape [B,L,E][B,L,E] (batch, sequence length, model dimension) whose last dimension EE is split into X×Y×ZX\times Y\times Z pieces, so each chip gets [B,L,E/(XYZ)][B,L,E/(XYZ)]; axes that aren't written are fully replicated. In addition, “partialsum-x” means each chip has already summed its own share, but the result only means something once it is summed with the other chips along the x axis.

Chips exchange data through a few kinds of collective communication (collectives):

Original Figure A.1: three collectives, each drawn with three devices 0, 1 and 2 in an upper and a lower row. Left, AllGather: in the upper row each device has one colored block (red, green, blue); arrows cross to the lower row, where every device has all three blocks, red, green and blue. Middle, ReduceScatter: in the upper row every device has three segments numbered 1, 2 and 3, all sent into a box in the middle labeled “Reduction e.g. +, x, max”; in the lower row, device 0 gets the combined result r(1,1,1) of segment 1 from all three devices, device 1 gets segment 2, and device 2 gets segment 3. Right, AllToAll: each device in the upper row has segments 1, 2 and 3; after the arrows cross, device 0 in the lower row has segment 1 from all three devices, device 1 has segment 2, and device 2 has segment 3.
Original Figure A.1, Pope et al., from PDF page 16, CC BY 4.0.
  • all-gather: each chip has one piece; after the exchange, every chip has the full concatenated result, so the output is KK times larger than the input (KK is the number of participating chips).
  • reduce-scatter: each chip has a full tensor holding only partial sums; after the exchange, each chip gets one segment of the finished sum.
  • all-to-all: moves the sharding from one dimension to another, for example from sharding by head to sharding by batch.

One all-reduce (sum, then every chip gets the full result) equals one reduce-scatter plus one all-gather. The approximation used in the appendix is that all-gather time is proportional to each chip's output size, and reduce-scatter time to each chip's input size.

Feed-forward layer: 1D weight-stationary

In its figures the paper simplifies each layer's feed-forward layer (FFN) to two matrix multiplications (the SwiGLU that PaLM actually uses has three matrices). It first uses WinW_\text{in} (shape E×FE\times F) to expand dimension EE to FF, applies GELU, then uses WoutW_\text{out} (F×EF\times E) to bring it back down to EE. For PaLM 540B, EE is 18,432 and FF is 73,728. The paper draws all three partitionings in one figure:

Original Figure 2: feed-forward partitioning flows in three columns side by side, each marked with the three torus axes X, Y and Z in the upper right. (a) 1D weight-stationary: the activation BLE_xyz goes through a green all-gather(xyz) to become the full BLE; an einsum with the weight W_in (EF_xyz) gives BLF_xyz, which goes through gelu and then an einsum with W_out (F_xyzE) to give BLE (partialsum-xyz); a red reduce-scatter(xyz) takes it back to BLE_xyz, which is finally added to the residual. (b) 2D weight-stationary: BLE_xyz goes through all-gather(yz) to become BLE_x; an einsum with W_in (E_xF_yz) gives BLF_yz (partialsum-x), which reduce-scatter(x) turns into BLF_xyz; after gelu, all-gather(x) turns it into BLF_yz; an einsum with W_out (F_yzE_x) gives BLE_x (partialsum-yz), and reduce-scatter(yz) takes it back to BLE_xyz. (c) Weight-gathered: a thick black line marks the activation path. B_xyLE_z goes through all-gather(z) to become B_xyLE; the weight W_in (E_xF_yz) goes through all-gather(xy) to become EF_z; their einsum gives B_xyLF_z, which after gelu goes into an einsum with W_out, gathered by all-gather(xy) into F_zE, to give B_xyLE (partialsum-z); reduce-scatter(z) takes it back to B_xyLE_z. Legend at lower right: B is batch, L is sequence length, E is hidden dimension, F is feed-forward dimension.
Original Figure 2, Pope et al., from PDF page 5, CC BY 4.0.

The most direct option is Megatron's partitioning, shown in (a). Both weight matrices are split along FF into 64 pieces, and each chip keeps its own piece for good. The weights never move; that's what weight-stationary means. Let's follow one set of activations through it:

  1. The incoming activations are BLExyzBLE_{xyz}, with the EE dimension spread across the chips. First, an all-gather(xyz) gives every chip the full BLEBLE.
  2. Multiplying by WinW_\text{in}'s EFxyzEF_{xyz} gives BLFxyzBLF_{xyz}, so each chip computes one segment of the FF dimension.
  3. GELU is elementwise and is done locally.
  4. Multiply by WoutW_\text{out}'s FxyzEF_{xyz}E. Each chip holds only one segment of FF, so the BLEBLE it produces is only a partial sum (partialsum-xyz).
  5. reduce-scatter(xyz) adds up the partial sums and at the same time splits the result back into BLExyzBLE_{xyz}, which then joins the residual.

Steps 2 through 4 need no communication at all. This is Megatron's neat trick. The first matrix is split along its output axis and the second along its input axis, so the segment each chip is left holding after the first multiplication is exactly the one the second multiplication needs.

The price is the two collectives at the start and the end, where each chip's output or input is the full BLEBLE:

Tcomm=2BLEnetwork bandwidthT_\text{comm}=\frac{2BLE}{\text{network bandwidth}}

The chip count doesn't appear in this expression. Double the chips, and memory time and compute time both halve, while communication time stays exactly where it was.

In February 2024, someone commented on Hacker News that no amount of parallel compute can reduce latency. Another user replied, “You literally can, in fact that's the entire reason to use multiple chips,” and linked this very paper. (HN comment) Adding chips really does lower latency; it's just that with 1D partitioning, once you have many chips, communication quickly becomes the part that won't come down.

Feed-forward layer: 2D weight-stationary

(b) splits each weight matrix along both EE and FF, so that each block is close to square. The weight layout is written ExFyzE_xF_{yz}: EE is split into XX pieces and FF into Y×ZY\times Z pieces.

The paper's example uses E=1,024E=1{,}024, F=4,096F=4{,}096 and 64 chips. EE is split 4 ways and FF 16 ways, so each chip stores a 256×256 block of weights. Applied to PaLM 540B, the same partitioning gives each chip a 4,608×4,608 block.

Walk through (b) once to see how it differs from (a):

  1. The initial all-gather runs only along the y and z axes, giving BLExBLE_x; the EE dimension stays split along the x axis.
  2. Multiply by ExFyzE_xF_{yz}. Each chip holds only one segment of EE, so the result is a partial sum along x, which takes one extra reduce-scatter(x) to sum into BLFxyzBLF_{xyz}.
  3. After GELU, an all-gather(x) goes back to BLFyzBLF_{yz}, which is multiplied by WoutW_\text{out}'s FyzExF_{yz}E_x.
  4. Finally, reduce-scatter(yz) goes back to BLExyzBLE_{xyz}.

The collectives go from two to four, but each one moves much less, and a full copy of the activations never appears on any chip at any point. The appendix solves for the best axis lengths, X=0.5nchipsX=0.5\sqrt{n_\text{chips}} and YZ=2nchipsYZ=2\sqrt{n_\text{chips}} (assuming F=4EF=4E), and the total communication time becomes:

Tcomm=8BLEnchips×network bandwidthT_\text{comm}=\frac{8BLE}{\sqrt{n_\text{chips}}\times\text{network bandwidth}}

The chip count finally appears in the denominator, though under a square root. Compared with 1D's 2BLE2BLE, 2D is cheaper when 8/n<28/\sqrt{n}<2, that is, when n>16n>16. At 64 chips its communication is half of 1D's, and at 256 chips a quarter.

Feed-forward layer: weight-gathered

Both partitionings above keep the weights still and move the activations. In decode, that makes sense. With PaLM 540B's dimensions, batch 512 and one token per sequence, one layer's activations BLEBLE in bf16 are only about 19 MB, while a single WinW_\text{in} is 2.7 GB.

Prefill turns this around. With batch 512 and 2,048 tokens per sequence, there are a million tokens in total, and the same layer's activations come to about 39 GB, more than ten times the size of one WinW_\text{in}.

At that point, moving the weights is cheaper than moving the activations. The weight-gathered layout in (c) keeps the activations as still as possible and all-gathers the weights just before the matrix multiplication. Depending on how many axes the weights are gathered along, the paper distinguishes X-, XY- and XYZ-weight-gathered; the figure shows XY:

  1. The activations are BxyLEzB_{xy}LE_z, with the batch split over the x and y axes and EE over the z axis.
  2. The weights start in the same layout as 2D weight-stationary, ExFyzE_xF_{yz}, and are all-gathered along x and y before the multiplication, becoming EFzEF_z.
  3. The activations need only an all-gather and a reduce-scatter along the z axis.

The starting layout is deliberately the same as 2D weight-stationary. With a single copy of the weights in memory, prefill can use weight-gathered and decode weight-stationary, and switching between them doesn't require moving the weights around.

Let NN be the number of chips the weights are gathered across. The paper finds that total communication time is smallest at N=BLnchips/FN=\sqrt{BLn_\text{chips}/F}:

Tcomm=4EBLFnchips×network bandwidthT_\text{comm}=\frac{4E\sqrt{BLF}}{\sqrt{n_\text{chips}}\times\text{network bandwidth}}

Weight-stationary communication is proportional to the number of tokens per batch, BLBL, while weight-gathered communication is proportional only to BL\sqrt{BL}. The more tokens, the more weight-gathered pays off:

Original Figure 3, titled Communication Volume Comparison, on log-log axes. The horizontal axis is tokens per batch, from 2,000 to over 2,000,000; the vertical axis is communication volume (GB), from 0.1 to over 100. The blue Weight-stationary line is the steepest straight line, rising from about 0.07 GB all the way to several hundred GB; the orange X-weight-gathered line starts at about 0.3 GB with a gentler slope; the red XY-weight-gathered line starts at about 1 GB, almost flat at first and rising only later; the green XYZ-weight-gathered line is horizontal at about 4 GB. The black dotted Min volume line marks the minimum at each point, following the blue, orange and red lines in turn and finally settling on the green line.
Original Figure 3, Pope et al., from PDF page 6, CC BY 4.0.

This figure uses a setting close to PaLM scale (X=Y=Z=4X=Y=Z=4, E=16,384E=16{,}384, F=65,536F=65{,}536). The vertical axis is the communication volume of one feed-forward layer, and both axes are logarithmic. Weight-stationary (blue) has the steepest slope; XYZ-weight-gathered (green) is a horizontal line, because it moves only weights, regardless of the token count. The black dotted line is the minimum at each point. Below roughly 20,000 tokens, weight-stationary is cheapest; above that, X and then XY take over, and past about a million tokens XYZ does.

Attention layer: shard MQA by batch

Multi-head attention is partitioned almost exactly like the feed-forward layer, with the number of heads in place of FF. Each chip handles a few heads, and those heads' Q, K, V and KV cache all stay local.

MQA drops the head dimension from K and V, shrinking the KV cache to 1/(number of heads) of its original size, but it also loses an axis to split along:

Original Figure 4, in an upper and a lower part. The upper part shows tensor shapes. Multi-head attention's Q is a thin slab with dimensions batch, heads and length 1; K/V is a box with dimensions batch, heads and time. Multi-query attention's Q is the same as multi-head, but the heads dimension of K/V is down to 1, leaving a thin, long strip. The lower part has three panels, each with two boxes, Device 1 and Device 2, labeled Q ⊙ K/V on the left. (a) Multi-head attention, sharded over heads: each device stores the Q and K/V of some of the heads, light green on one and dark green on the other; the caption says multi-head attention can be sharded over heads without replication. (b) Multi-query attention, sharded over heads: Q is split by head across the two devices, but both devices store a full strip of K/V; the caption says the single K head has to be fully replicated, increasing memory-access cost. (c) Multi-query attention, sharded over batch: Device 1 stores the dark red Q and K/V, and Device 2 the light red part of the batch; the caption says that after switching to sharding over batch, the einsum needs only one slice of K, reducing memory-access cost.
Original Figure 4, Pope et al., from PDF page 6, CC BY 4.0.

The upper part shows tensor shapes. Multi-head attention's K/V has three dimensions: batch, head and time (sequence length). In MQA the head dimension is down to 1, so the whole block becomes a thin, long strip. The lower part shows three partitionings, with the two boxes standing for two chips:

  • (a) Multi-head, sharded by head: each chip takes some of the heads; dark green and light green each stay on their own chip, with no replication at all.
  • (b) MQA, sharded by head: Q is still split by head, but every head has to read the same K/V head, so each chip ends up storing a full copy of the KV cache. With 64 chips, that's 64 copies, and every chip reads the entire cache at every step. All the memory MQA saved goes right back.
  • (c) MQA, sharded by batch: instead, each chip takes care of some of the sequences and stores only their KV. Each chip now has 1/64 as much KV to read, and memory time drops by a factor of 64 as well.

The price is an all-to-all. The projection matrices before attention are still split by head, the same way as in the feed-forward layer. After Q, K and V are computed, an all-to-all first moves the sharding from heads to batch, and once attention is done, another moves it back.

In decode, this exchange is a bargain. Each sequence's Q, K and V cover only the single position of the new token, while the KV cache holds over two thousand positions. You move the small thing to save on the big one. Prefill is different. Q itself has over two thousand tokens, all querying the same K and V, so the cost of reading KV is already spread out, and prefill therefore still shards by head.

Parallel layers, low-level optimizations and int8

The remaining three items are supporting pieces that make the partitionings above run faster.

Parallel attention and feed-forward layers. A standard Transformer block computes attention first and the feed-forward layer second; PaLM follows GPT-J's formulation, where both read the same normalized input and their results are added. At inference time, this brings three benefits. Each layer has only one LayerNorm, which lowers latency at small batches. The feed-forward input matrix can be fused with WQW_Q, WKW_K with WVW_V, and the feed-forward output matrix with WOW_O, and the bigger matrices run more efficiently on accelerators. The third benefit has the biggest impact. Each layer saves one all-reduce, which halves the communication time along the FF/heads axis.

Low-level optimizations. The authors use Looped CollectiveEinsum to run communication concurrently with matrix multiplication, hiding most of the all-gather and reduce-scatter time behind computation, and they wrote several variants for latency, throughput and different numbers of torus axes. These optimizations are about 1.4× faster than the version they started with, which left automatic partitioning and scheduling to the compiler; without them, some weight-gathered layouts simply run out of memory. Other optimizations include tensor layouts that reduce padding and copies, faster top-k/top-p sampling, and base-2 implementations of softmax and Swish.

int8 weights. The authors use the AQT library to convert 16-bit weights to int8. The paper says there is no noticeable quality loss but gives no numbers. With weights half the size, the memory time for reading them halves too, which helps most at small batches; weight-gathered layouts also have fewer weights to move. Activations aren't quantized, and matrix multiplications still run in bf16.

Discussion

Experimental setup

The inference framework is built on JAX and XLA, originally adapted from T5X, and uses up to 256 TPU v4 chips. The models are PaLM 8B, 62B and 540B, which already used MQA and parallel layers.

PaLM 540B has 118 layers and 48 attention heads. To partition cleanly across 64 or more chips, the authors padded the head count to 64. That adds 18 billion parameters and costs 3% MFU, but the gain in partitioning efficiency is enough to make up for it.

Feed-forward layer: how 2D and weight-gathered divide the work

Start with decode. The batch is fixed at 512, and the chip count goes from 64 to 256:

Original Figure 6, titled Weight Stationary: 2D vs. 1D. The horizontal axis is chip count, 64, 128 and 256; the vertical axis is per-step latency (ms), from 60 to 120. The orange 1D Weight Stationary line falls gently from about 96 ms to about 94 ms and about 89 ms; the blue 2D Weight Stationary line falls from about 92 ms to about 73 ms and about 67 ms.
Original Figure 6, Pope et al., from PDF page 8, CC BY 4.0.

Both lines go down, but 1D (orange) is almost flat, dropping from about 96 ms to 89 ms, while 2D (blue) drops from about 92 ms to 67 ms. The paper says both layouts are starting to be limited by communication, and 2D's communication falls as 1/n1/\sqrt{n}, so the more chips there are, the further apart the two lines get.

Next, prefill. PaLM 540B, 64 chips, 2,048 tokens per sequence; the horizontal axis is the total number of tokens per batch:

Original Figure 7, titled 2D Weight Stationary vs. Gathered. The horizontal axis is tokens per batch, 125,000, 250,000, 500,000 and 1,000,000; the vertical axis is MFU, from 0% to 100%. The blue 2D Weight Stationary line stays roughly flat at 40%, with the last point at about 42%; the orange line (labeled 2D Weight Gathered in the legend) rises from about 29% to about 55% and about 74%, ending at about 77%.
Original Figure 7, Pope et al., from PDF page 8, CC BY 4.0.

Weight-stationary (blue) stays around 40% no matter how big the batch is. Weight-gathered (orange) manages only about 29% at 130,000 tokens, worse than weight-stationary; at 260,000 tokens it rises to about 55%, and at a million tokens (512 × 2,048) it reaches 76%, by which point communication overhead is almost negligible. The paper also notes that without MQA, a batch this large would simply run out of memory.

From this, the paper sets a basic rule for choosing a layout. Prefill picks between weight-stationary and weight-gathered based on how many tokens the current batch has; decode never has many tokens per batch, so it always uses 2D weight-stationary.

Attention layer: 32 times the context

Next comes the comparison of attention partitionings. The authors also built a multi-head version of PaLM 540B; to keep the attention layer's parameter count unchanged, the dimension per head shrinks from MQA's 256 to 128. First, how long a context fits in memory:

Table: Table 1 of the paper. PaLM 540B, 64 chips, with 30% of total memory reserved for the KV cache; the numbers are the longest supported context.
AttentionDim per headBatch 128Batch 512
Multi-head1281,320330
MQA, sharded by head256660165
MQA, sharded by batch25643,00010,700

This table can be checked with the formula from earlier. 64 chips at 32 GiB each, and 30% of that comes to 614 GiB:

  • Multi-head: 64 heads × 128 dimensions (the padded version) gives about 3.7 MiB of KV per token, spread evenly across the 64 chips by head. 614 GiB holds about 170,000 tokens; divided among 128 sequences, that's about 1,330.
  • MQA, sharded by batch: 118 KiB per token, also spread evenly, so it holds about 5.46 million tokens; divided by 128, that's about 42,700. The two differ by 32×, exactly the ratio of 64×128 to 256.
  • MQA, sharded by head: every chip has to store a full copy of the cache, so the usable space is only a single chip's 9.6 GiB, which holds about 85,000 tokens; divided by 128, that's about 670. With 256 dimensions per head, replicated 64 times, it ends up at half of multi-head.

The calculated numbers differ from the table by only about 1%, so the 32× can be worked out by hand like this.

Now for speed:

Original Figure 8, titled Multiquery vs. Multihead Attention (8 layers). The horizontal axis is context length, 128, 512, 2048 and 8192; the vertical axis is per-step latency (ms), from 0 to 60. The blue Multiquery (Optimized Layout) line is almost horizontal, at about 4 ms; the orange Multiquery (Inefficient Layout) line rises from about 4 ms to about 8 ms, reaching about 20 ms at 8192; the green Multihead line rises from about 4 ms to about 16 ms, reaching about 55 ms at 8192. The orange and green lines turn dashed after 512.
Original Figure 8, Pope et al., from PDF page 9, CC BY 4.0.

This experiment uses only an 8-layer PaLM 540B, on 64 chips with batch 256. At context 128 the three lines are bunched together at about 4 ms, when almost all the time goes to the feed-forward layers. As the context grows, multi-head (green) climbs to about 55 ms at 8,192 and head-sharded MQA (orange) to about 20 ms, while batch-sharded MQA (blue) stays almost flat at around 4 ms. The dashed segments indicate that with the full 118-layer model, once the context passes 512, multi-head and head-sharded MQA can no longer fit the KV cache.

Batch-sharded MQA can handle 8,192 (batch 512) to 32,768 (batch 128) tokens, with attention taking only 8% to 31% of the total time. In prefill, the two kinds of attention have similar latency, because with many queries computed at once, attention's matrix multiplications are compute-bound on their own.

Serial blocks are 14% slower

Switching PaLM 540B's parallel blocks back to the serial form, attention first and feed-forward second, makes each decode step (2D weight-stationary, 64 chips, batch 512) 14% slower, mostly from the extra activation communication. The gap in prefill is smaller, because weight-gathered layouts already move fewer activations.

End to end: the fast-versus-cheap curve

Finally, the authors sweep everything (model size, weight format, batch, chip count and layout) with the context fixed at 2,048:

Original Figure 1: two log-log plots side by side, both with cost per token (chip-milliseconds) on the vertical axis, from 0.0625 to 128. On the left, Decoding Latency vs. Cost, with latency per generated token (ms) on the horizontal axis, from 2 to 512; on the right, Prefill Latency vs. Cost, with latency per forward pass (seconds) on the horizontal axis, from 0.03 to 256. The six lines are PaLM 540B and 540B-int8 (dark and light green), 62B and 62B-int8 (dark and light blue), and 8B and 8B-int8 (red and orange); points on each line are labeled with chip count C and batch B. In the left plot, the 540B lines sit at the top, starting on the left at C:128, B:64 and, for int8, C:64, B:64, and reaching C:64, B:1024 on the right; 62B runs from C:32, B:32 to C:8, B:1024; 8B runs from C:16, B:32 to C:8, B:1024. All three groups fall from the upper left to the lower right and then level off. The lines in the right plot are roughly horizontal: 540B runs from C:64, B:1 to C:64, B:512, 62B from C:16, B:1 to C:32, B:512, and 8B from C:8, B:1 to C:32, B:512.
Original Figure 1, Pope et al., from PDF page 2, CC BY 4.0.

The left plot is decode. The horizontal axis is the latency per generated token, the vertical axis the chip-milliseconds spent per token, and both axes are logarithmic. Each line is one model's Pareto frontier, with chip count C and batch B labeled next to some of the points. Further left is faster, further down is cheaper; moving along a line from the upper left to the lower right trades latency for cost.

Three points stand out in the left plot:

  1. Decode's per-token cost is lowest when the batch exceeds about 512, where cost is proportional to parameter count. Shrinking the batch lowers latency, and cost rises along with it; the lowest latency is about a third of the latency at batch 512.
  2. The lowest latency comes from int8 (the lighter lines). For PaLM 540B at batch 64, int8 takes 28.5 ms per token and bf16 takes 36.9 ms. At the low-latency end, cost improves by slightly more than 2×, because at small batches cost goes mostly to reading weights; at large batches the two are about the same, because cost is then mostly compute, and the matrix multiplications still run in bf16.
  3. As models grow, low-batch latency grows more slowly than model size. Larger models have more weights to read, but they can also be split across more chips before hitting the communication bottleneck. From the left plot, the authors estimate that latency is roughly proportional to the square root of model size.

The int8 numbers can be checked against the earlier estimate. Switching the weights from bf16 to int8 cuts the weight-reading time per step by about 7 ms (about 7.3 ms for the 558B model after head padding); the paper measures a difference of 36.9 − 28.5 = 8.4 ms, which roughly matches.

The right plot is prefill, measuring the time to process 2,048 input tokens. The tug-of-war between batch and latency is much milder than in decode, and even batch 1 isn't especially expensive. At batch 512, prefill's per-token cost is half that of decode at batch 512, thanks to the higher MFU of the weight-gathered layout.

From the frontier, the paper picks two representative configurations, split into prefill and decode:

Table: excerpt from Table 2 of the paper (prefill). PaLM 540B, 64 chips; latency is the time to process 2,048 tokens. WS is weight-stationary, WG is weight-gathered.
PrefillLow latencyHigh throughput
Batch1512
FFN layout2D WSXYZ WG
Attention shardingBy headBy batch
Weightsint8bf16
MFU43%76%
Latency0.29 s85.2 s
Table: excerpt from Table 2 of the paper (decode), also on 64 chips; latency is the time to generate 64 tokens.
DecodeLow latencyHigh throughput
Batch64512
FFN layout2D WS2D WS
Attention shardingBy batchBy batch
Weightsint8bf16
MFU14%33%
Latency1.82 s6.0 s

The low-latency configuration pairs batch-1 prefill with batch-64 decode. Prefill has the lowest latency at batch 1; for decode, going from batch 1 to 64 adds almost no latency, while MFU gets much better. By the earlier estimate, compute time at batch 64 (3.9 ms) is still below the int8 weight-reading time (about 7 ms), so the extra sequences are almost along for the ride. In practice, you can sample several answers from the same input, or have a batch-1 prefill server hand its results off to a batch-64 decode server.

Decode's MFU can be checked directly with the earlier formulas. At batch 64, each step takes 1.82 s ÷ 64 ≈ 28.4 ms, of which the matrix computation needs only 3.9 ms at peak, a ratio of about 14%; at batch 512, each step takes about 93.8 ms with 31.4 ms of compute, about 33%. Both match the table. Seen another way, even at batch 512, about two-thirds of each step's time doesn't turn into peak compute. The earlier 2D-layout decode experiment had the same setup (2D WS, 64 chips, batch 512) and read about 92 ms, which is close as well. The paper says both layouts were by then starting to be limited by communication; the two-thirds of each step not turned into compute includes inter-chip communication and other overheads, which the paper doesn't break down further.

The high-throughput configuration changes layouts. Prefill uses XYZ-weight-gathered, decode uses 2D weight-stationary, and the weights go back to bf16. The authors' reasoning is that weight-reading time doesn't matter at large batches, and their software still lacked some optimizations for int8 mode at large batches.

The paper's introduction also gives a chatbot example. With PaLM 540B, int8 and 64 chips, a user sends in 64 tokens, which join 1,920 tokens of cached conversation history, and the model then generates a 64-token reply, taking 1.9 seconds in total. In an offline scenario, processing 1,984 input tokens and generating 64 tokens reaches an overall FLOPS efficiency of 73%.

Comparing with FasterTransformer

FasterTransformer is NVIDIA's inference library, and at the time it had published a set of benchmarks for Megatron-Turing NLG 530B. The hardware differs. FasterTransformer uses 16 to 32 A100s with 80 GiB each, and the paper uses 64 TPU v4 chips with 32 GiB each. So the paper compares MFU instead, which normalizes away the differences in chip count and per-chip compute.

The authors implemented both PaLM 540B and Megatron 530B on TPU. Megatron 530B uses multi-head attention and serial blocks, with 105 layers and a model dimension of 20,480. The main comparison uses a setting with 60 input tokens and 20 output tokens.

PaLM 540B gets the lowest absolute latency. For the same Megatron 530B, the TPU implementation has higher MFU than FasterTransformer at every latency target but one. PaLM beats the authors' own Megatron implementation by up to 10% MFU, mostly thanks to parallel layers; MQA shows no advantage in this benchmark, because the context is too short. On scaling, FasterTransformer's 32-way tensor parallelism peaks at only 33% MFU across all benchmarks, and its 16-way at 46%, while the paper's 64-way tensor parallelism still reaches 44%. From this, the authors conclude that 2D weight-stationary scales better across TPU v4's larger high-speed interconnect domain.

Read this comparison with its conditions in mind. The hardware and software stacks both differ, and MFU normalizes compute but not interconnect topology or memory capacity. The inputs are only 20 to 128 tokens, too short to show the effect of MQA or long contexts. The paper itself adds that its other experiments deliberately tested contexts of 1,024 to 4,096 and reported prefill and decode separately.

Limitations

  • All experiments are on TPU v4's 3D torus. The conclusion says these partitionings can generalize to GPU NVLink networks, but the paper never measured them on GPUs.
  • The main experiments are on the PaLM family, which already comes with MQA and parallel layers; multi-head attention appears only in the capacity table, the 8-layer speed experiment, and the very short-context Megatron 530B comparison.
  • int8 quality gets only one line, “no noticeable loss,” with no numbers; activation quantization wasn't attempted.
  • The code wasn't released, and low-level optimizations such as Looped CollectiveEinsum are built on Google's internal inference framework written in JAX/XLA (first, get yourself 64 TPU v4 chips).
  • Decode MFU is still low, about 33% at batch 512, and with more chips, communication remains the main bottleneck. In the conclusion, the authors also note that FLOPs and communication volume may fundamentally limit the inference performance of dense Transformers, and they pin their hopes on MoE, adaptive computation and communication compression.

Conclusion

This paper proposes no new model. It turns “how do you serve a 540B model” into problems you can calculate. Each step's time is split into reading weights, reading KV, matrix computation and inter-chip communication, and the partitioning is then chosen by whether the application needs to be fast or cheap. Decode uses 2D weight-stationary, so communication falls as chips are added; large-batch prefill switches to weight-gathered, moving the weights instead of the activations; MQA is sharded by batch, so the KV cache really is spread across every chip.

The capacity table and the context-length curve are the most solid parts of the paper. With the same MQA, the supported context is half that of the multi-head version when it's sharded the wrong way, and 32 times as long when it's sharded the right way, a ratio you can work out by hand from the size of the KV. The end-to-end 29 ms and 76% MFU each come with clear conditions. The former is int8 decode at batch 64, the latter batch-512 prefill over a million tokens, and no single serving configuration gets both at once. The limitations are just as clear. Everything was measured only on TPU v4, the code wasn't released, and decode MFU at large batches is only around 30%.

If you deploy models yourself, the most useful part of this paper is its way of estimating. Work out how many bytes of weights and KV one step reads and how many FLOPs it performs, compare those with the hardware's bandwidth and compute, and you know whether you're stuck on memory or on compute; work out prefill and decode separately, and tune them separately too. For models with MQA or GQA, remember to check the tensor-parallel degree. If attention is sharded by head and the degree exceeds the number of KV heads, the KV heads have to be replicated across several GPUs, and you run into the same problem as head-sharded MQA above.

The analysis didn't stop with this paper. In February 2025, Jacob Austin, Sholto Douglas and colleagues at Google DeepMind (Anselm Levskaya and Reiner Pope are also on the author list) wrote How to Scale Your Model. Its inference chapter uses the same method to find that bf16 on TPU v5e needs a batch of about 240 tokens before it becomes compute-bound, and H100 about 280, and when it discusses 2D weight-stationary it points directly to this paper. The idea of splitting prefill and decode across different machines was built into complete systems by Splitwise in late 2023 and DistServe in early 2024; back then, this paper mentioned it in a single sentence, saying a batch-1 prefill server could hand off to a batch-64 decode server.

Back to gwern's question of who would be willing to pay for it. The paper doesn't answer for anyone. It draws a curve that shows plainly how many more chip-seconds one step to the left costs, and how many more milliseconds of waiting one step down means. More than two years later, the inference chapter of that textbook also starts its calculations from “is this step stuck on memory, compute or communication?”