Simple Algorithm
Deep Learning · Representation · 24 min

Efficient Transformers

The quadratic cost of attention, inference memory and the ways around them.

A transformer spends its time in three different ways. Training and reading a prompt are large matrix products that keep the arithmetic units busy. Generating text, one token at a time, mostly waits for memory: every new token re-reads every weight and every cached key and value. Each regime has its own bottleneck, so efficient transformers come in families: compute fewer scores, approximate the softmax, move fewer bytes, store less, or produce several tokens per pass.

What you’ll learn

  • Count the FLOPs and the bytes moved by a decoder in training, prefill and decoding, and explain why prefill is compute-bound while decoding is bound by memory bandwidth.
  • Compute the size of a KV cache, 2 L T Hkv dk2\,L\,T\,H_{kv}\,d_k numbers per sequence, and what multi-query and grouped-query attention save.
  • Describe sliding-window, dilated, strided, global and block-sparse attention, and how far information travels through a stack of windows.
  • Derive low-rank and kernelized (linear) attention, implement causal linear attention as a recurrence, and state what these approximations give up.
  • Match IO-aware exact attention, cache compression, batching and speculative decoding to the costs they reduce.

Three regimes, three bottlenecks

Self-Attention & Multi-Head Attention priced one attention sublayer at 8Td2+4T2d8Td^2+4T^2d FLOPs for TT tokens of width dd, and noted that a naive implementation stores a T×TT\times T matrix of weights per head. Those counts describe one pass over whole sequences, which is what training does. A deployed decoder works in two further regimes:

  • Prefill. The prompt's tokens go through the model in one pass, as in training. Every weight matrix multiplies a block of many token vectors, so arithmetic dominates.
  • Decoding. Each new token goes through the model alone and attends to the stored keys and values of everything before it, the KV cache. Every weight matrix now multiplies a single vector.

For a decoder with LL layers and HkvH_{kv} key–value heads of size dkd_k, storing numbers of bb bytes, the cache of one sequence of length TT holds a key and a value per head, per layer and per token:

KV bytes per sequence=2⋅L⋅T⋅Hkv⋅dk⋅b\text{KV bytes per sequence}=2\cdot L\cdot T\cdot H_{kv}\cdot d_k\cdot b
The factor 2 counts keys and values. Classic multi-head attention has one key–value head per query head, Hkv=HH_{kv}=H and Hkvdk=dH_{kv}d_k=d; the variants of the fifth step share them, Hkv<HH_{kv}<H. Queries are never cached, since each is used only once.
Predict before you look

A LLaMA-2-7B-like decoder has L=32L=32 layers and 32 key–value heads of size 128, and caches 16-bit numbers. How many GiB does the KV cache of one 4,096-token sequence occupy?

Show the answer

2 GiB

2×32×4096×32×128×2=2312\times32\times4096\times32\times128\times2=2^{31} bytes =2=2 GiB: keys and values, 32 layers, 4,096 tokens, 32 heads of 128 numbers, 2 bytes each. A batch of 16 such conversations needs 32 GiB, more than twice the 13.5 GB of the model's weights. With 8 key–value heads instead of 32 it would be 0.5 GiB per sequence.

DerivationOne decoding step against the roofline
  1. Ctok≈2N+4Ltd  FLOPs,Qtok≈2N+4Lt Hkvdk  bytesC_{\text{tok}}\approx2N+4Ltd\ \ \text{FLOPs},\qquad Q_{\text{tok}}\approx2N+4Lt\,H_{kv}d_k\ \ \text{bytes}

    Generating one token at context length tt costs 2N2N FLOPs in the weight matrices of an NN-parameter model, plus 2td2td for the scores and 2td2td for the weighted sum in each layer. The step must read every weight once and the sequence's whole cache, in 16-bit numbers:

  2. Qtok/βCtok/Π=Πβ⋅QtokCtok≈333×1\frac{Q_{\text{tok}}/\beta}{C_{\text{tok}}/\Pi}=\frac{\Pi}{\beta}\cdot\frac{Q_{\text{tok}}}{C_{\text{tok}}}\approx333\times1

    With multi-head attention Hkvdk=dH_{kv}d_k=d, so the two counts coincide: one FLOP per byte. For the 7B model (N≈6.74×109N\approx6.74\times10^9) at t=4096t=4096 both are 1.56×10101.56\times10^{10}. On the illustrative accelerator of The Roofline Model & Compute Efficiency (Π=1015\Pi=10^{15} FLOP/s, β=3×1012\beta=3\times10^{12} B/s) the arithmetic would need 0.016 ms and the memory traffic needs 5.2 ms:

  3. Iprefill≈4096×1.35×1010+4.4×10121.56×1010≈3.8×103  FLOPs per byteI_{\text{prefill}}\approx\frac{4096\times1.35\times10^{10}+4.4\times10^{12}}{1.56\times10^{10}}\approx3.8\times10^{3}\ \ \text{FLOPs per byte}

    Prefill of a 4,096-token prompt runs the same weights on all its tokens at once: 4096×2N4096\times2N FLOPs plus causal attention, 2LT2d2LT^2d, for about the same number of bytes. Its arithmetic intensity is in the thousands, far to the right of the ridge at 333:

  4. The same weights are compute-bound in prefill and memory-bound by a factor of hundreds in decoding. A faster decoder must move fewer bytes per generated token (smaller caches, fewer bits, more tokens per pass); doing less arithmetic would not help.

Attend to fewer pairs

The most direct saving computes only some of the scores. A sparsity pattern fixes which pairs (t,j)(t,j) may interact, and every other score is masked to −∞-\infty before the softmax:

  • Sliding window (local attention): position tt attends to itself and the ww positions before it. Scores cost O(Twd)\order{Twd} instead of O(T2d)\order{T^2d}, and the cache keeps only the last ww entries per layer.
  • Dilated window: the same number of keys spaced δ\delta apart, spanning δw\delta w positions; different heads can use different dilations.
  • Strided patterns: a local band plus every ℓ\ell-th position. With ℓ≈T\ell\approx\sqrt T every token reaches every other in two hops, at O(TT)\order{T\sqrt T} cost (Child et al., 2019).
  • Global tokens: a few positions, such as a classification token or the question in question answering, attend to everything and are attended by everything (Longformer: Beltagy, Peters & Cohan, 2020). BigBird adds a few random links per token (Zaheer et al., 2020).

A window does not cut a token off from the distant past. The output of layer ℓ\ell at position tt depends on layer ℓ−1\ell-1 at positions back to t−wt-w, each of which depended on ww positions before it, so LL stacked windows can carry information LwLw positions back (LδwL\delta w with dilation), the way stacked convolutions grow a receptive field.

Think first Mistral 7B uses sliding-window attention with W=4,096W=4{,}096 in each of its 32 layers. In principle, how many positions back can information reach the top layer, and how much smaller than a full cache can its cache be at 32,768 tokens?

Each layer moves information at most WW positions, so 32 layers reach 32×4,096=131,07232\times4{,}096=131{,}072, the "approximately 131K tokens" of Jiang et al. (2023). That bounds the path, not what survives it: distant information has to be relayed through intermediate tokens in every layer. The cache needs only the last WW entries per layer, so a rolling buffer that stores position tt in slot t mod Wt\bmod W is 32,768/4,096=832{,}768/4{,}096=8 times smaller than a full cache.

Sparsity saves time only when whole blocks of the score matrix can be skipped: masking scattered entries inside a dense product costs as much as computing them. The causal mask is the simplest block pattern, and skipping the blocks above the diagonal made FlashAttention-2 1.7–1.8 times faster than unmasked attention (Dao, 2024). Among open models of the mid-2020s, the sparse pattern seen most often is the plain sliding window, in every layer or interleaved with full-attention layers: Mistral 7B combines W=4,096W=4{,}096 windows in all its layers with grouped-query attention (Jiang et al., 2023), and Gemma 2 alternates sliding-window and global layers (Gemma Team, 2024).

Approximate the softmax

A second family keeps every pair but approximates the weights, so that the T×TT\times T matrix is never formed.

Low rank. If the weights A=softmax⁡(QK⊤/dk)A=\softmax(QK^\top/\sqrt{d_k}) are close to a low-rank matrix, the sequence axis of the keys and values can be compressed. Linformer (Wang et al., 2020) learns E,F∈Rk×TE,F\in\R^{k\times T} with k≪Tk\ll T and computes

softmax⁡ ⁣(Q (EK)⊤dk) (FV),scores of size T×k instead of T×T\softmax\!\Big(\frac{Q\,(EK)^\top}{\sqrt{d_k}}\Big)\,(FV),\qquad\text{scores of size }T\times k\ \text{instead of}\ T\times T
Cost O(Tkd)\order{Tkd}. Every row of EE mixes keys from the whole sequence, and its width fixes TT.

Kernels. Write the softmax weight as a similarity, κ(q,k)=exp⁡(q⋅k/dk)\kappa(\mathbf q,\mathbf k)=\exp(\mathbf q\cdot\mathbf k/\sqrt{d_k}), and replace it by a product of feature maps, ϕ(q)⊤ϕ(k)\phi(\mathbf q)^\top\phi(\mathbf k) with ϕ:Rdk→Rr\phi:\R^{d_k}\to\R^r. The sum over keys then factors, because matrix products are associative: (ϕ(Q)ϕ(K)⊤)V=ϕ(Q)(ϕ(K)⊤V)\big(\phi(Q)\phi(K)^\top\big)V=\phi(Q)\big(\phi(K)^\top V\big), and the right-hand side costs O(Trdv)\order{Trd_v}. Under a causal mask the sums run over j≤tj\le t and become running totals, so causal linear attention is a recurrent network whose state is a matrix (Katharopoulos, Vyas, Pappas & Fleuret, 2020):

St=St−1+ϕ(kt) vt⊤,ut=ut−1+ϕ(kt),zt=St⊤ϕ(qt)ut⊤ϕ(qt)S_t=S_{t-1}+\phi(\mathbf k_t)\,\mathbf v_t^\top,\qquad\mathbf u_t=\mathbf u_{t-1}+\phi(\mathbf k_t),\qquad\mathbf z_t=\frac{S_t^\top\phi(\mathbf q_t)}{\mathbf u_t^\top\phi(\mathbf q_t)}
The state St∈Rr×dvS_t\in\R^{r\times d_v} replaces the KV cache, so each generated token costs the same time and memory at any length. Katharopoulos et al. used ϕ(x)=elu⁡(x)+1\phi(\mathbf x)=\operatorname{elu}(\mathbf x)+1, which is positive, so the denominator never vanishes.
python
import torch
import torch.nn.functional as F

def phi(x):                                    # a positive feature map (Katharopoulos et al., 2020)
    return F.elu(x) + 1

def linear_attn_parallel(q, k, v):             # causal; q, k: (T, r), v: (T, dv)
    q, k = phi(q), phi(k)
    S = torch.cumsum(k[:, :, None] * v[:, None, :], dim=0)   # S_t for every t at once
    u = torch.cumsum(k, dim=0)                                # u_t for every t
    return torch.einsum('tr,trd->td', q, S) / (q * u).sum(-1, keepdim=True)

def linear_attn_recurrent(q, k, v):            # the same layer as an RNN with an r x dv state
    q, k = phi(q), phi(k)
    S, u, out = torch.zeros(k.shape[1], v.shape[1]), torch.zeros(k.shape[1]), []
    for t in range(q.shape[0]):
        S, u = S + torch.outer(k[t], v[t]), u + k[t]          # constant memory per new token
        out.append(q[t] @ S / (q[t] @ u))
    return torch.stack(out)

q, k, v = torch.randn(8, 4), torch.randn(8, 4), torch.randn(8, 3)
assert torch.allclose(linear_attn_parallel(q, k, v), linear_attn_recurrent(q, k, v), atol=1e-5)

The parallel form trains on whole sequences; the recurrent form generates. This parallel version materializes every StS_t, T⋅r⋅dvT\cdot r\cdot d_v numbers, for clarity; practical kernels process the sequence in chunks.

Random features. The Performer (Choromanski et al., 2021) keeps the softmax kernel itself. With random Gaussian vectors ω1,…,ωr\boldsymbol\omega_1,\dots,\boldsymbol\omega_r and ϕ(x)=r−1/2(eωl⊤x−∥x∥2/2)l=1r\phi(\mathbf x)=r^{-1/2}\big(e^{\boldsymbol\omega_l^\top\mathbf x-\norm{\mathbf x}^2/2}\big)_{l=1}^r, the estimate ϕ(x)⊤ϕ(y)\phi(\mathbf x)^\top\phi(\mathbf y) is positive and unbiased for ex⊤ye^{\mathbf x^\top\mathbf y}; the Artificial Intelligence course's lesson Efficient Attention & Long Context derives its variance.

Check your understanding

Why can't Linformer's compression of the keys along the sequence, EKEK with E∈Rk×TE\in\R^{k\times T}, be used in a decoder that generates text?

  1. Each compressed key mixes all TT positions, future ones included, and EE is tied to one sequence length
  2. It needs more memory than standard attention
  3. It removes the softmax, so the weights no longer sum to one
  4. It works only with a single head
Show the answer

A. Each compressed key mixes all TT positions, future ones included, and EE is tied to one sequence length

A causal model must let position tt depend only on positions j≤tj\le t, and generation must work at every length. A row of EE mixes keys from the whole sequence and has a fixed width. Kernelized attention has neither problem: its sums over j≤tj\le t are running totals.

Exact attention, fewer bytes

The approximations above cut FLOPs. At the lengths most models are trained on, though, standard attention is slow for another reason: memory traffic. A GPU keeps its tensors in HBM, tens of gigabytes read at a few terabytes per second, and computes out of on-chip SRAM, a few tens of megabytes in total with roughly ten times the bandwidth. A naive implementation runs three kernels: it writes the scores S=QK⊤S=QK^\top to HBM, reads them back to compute P=softmax⁡(S)P=\softmax(S), writes PP, and reads it again to form PVPV. That is Θ(Td+T2)\Theta(Td+T^2) HBM accesses per head, nearly all of them for intermediate results, and PP stays in memory for the backward pass.

FlashAttention (Dao, Fu, Ermon, Rudra & Ré, 2022) computes the same output tile by tile. A block of queries and a block of keys and values are loaded into SRAM, their scores are formed and used there, and the result is folded into a running output with the online softmax: each query row keeps its running maximum mm and its running sum ℓ\ell of es−me^{s-m}, and rescales what it has accumulated by emold−mnewe^{m_{\text{old}}-m_{\text{new}}} whenever a new block raises the maximum. Nothing of size T×TT\times T ever reaches HBM.

Sequence length TTStoring PP for one head (16-bit)FlashAttention's per-row statistic (32-bit)
2,0488 MiB8 KiB
8,192128 MiB32 KiB
131,07232 GiB512 KiB
Per head, per layer and per sequence. FlashAttention keeps the output and one log-sum-exp per query row; the backward pass recomputes the scores tile by tile from them instead of reading PP back.

The forward pass does the same arithmetic and the backward pass does more, since it recomputes the scores, yet the kernel is faster because it moves far fewer bytes: its HBM traffic is Θ(T2d2/M)\Theta(T^2d^2/M) for an SRAM holding MM numbers, many times below Θ(T2)\Theta(T^2) when d2≪Md^2\ll M. It trained GPT-2 up to 3 times faster end to end than the HuggingFace implementation and 1.7 times faster than Megatron-LM's (Dao et al., 2022), and FlashAttention-2 roughly doubled the kernel's speed again (Dao, 2024). Because it changes no number in the model, it can replace standard attention in any network; as of the mid-2020s, kernels of this kind sit behind the fused attention calls of the major frameworks, such as PyTorch's F.scaled_dot_product_attention on supported GPUs. FlashAttention in Depth proves the online softmax correct and derives the IO bound and its optimality.

Storing less: the KV cache

In decoding, every byte of the cache is read once per generated token, so the cache's size sets both the memory per sequence and the time per step. Four levers shrink it:

  • Fewer key–value heads. Multi-query attention shares one key head and one value head among all query heads (Shazeer, 2019); grouped-query attention shares each of HkvH_{kv} key–value heads within a group of H/HkvH/H_{kv} query heads (Ainslie et al., 2023). The cache shrinks by H/HkvH/H_{kv}: Anatomy of a Modern LLM found 128 KiB per token for Llama 3 8B instead of 512 KiB. Multi-head latent attention caches one low-dimensional latent vector per token and layer (plus a small key that carries positions), from which every head's keys and values are reconstructed (DeepSeek-AI, 2024).
  • Fewer bits. Storing keys and values in 8 or 4 bits halves or quarters the cache. With scales per channel for the keys, which have a few large fixed channels, 2 bits have worked for several open models (Liu et al., 2024).
  • Fewer tokens. Eviction keeps only some positions: the most recent ones plus those that have received the most attention so far (H2O: Zhang et al., 2023), or the first few tokens plus a recent window, because the first tokens act as attention sinks (Attention Sinks & Massive Activations). Unlike a rolling buffer for a model trained with windows, eviction changes the computation, and an evicted token cannot be recovered if a later query needs it.
  • Less waste. Allocating each sequence's cache in fixed-size blocks, like pages of virtual memory, avoids reserving space for the longest possible output (Kwon et al., 2023).
Iattn=4 H dk  FLOPs per cached token2⋅2 Hkv dk  bytes per cached token=HHkv  FLOPs per byteI_{\text{attn}}=\frac{4\,H\,d_k\ \ \text{FLOPs per cached token}}{2\cdot2\,H_{kv}\,d_k\ \ \text{bytes per cached token}}=\frac{H}{H_{kv}}\ \ \text{FLOPs per byte}
Per cached token and layer, in 16-bit numbers. Each of the HH query heads still computes a score and adds a weighted value, so sharing leaves the attention FLOPs unchanged and cuts the bytes. Multi-head attention sits at 1, groups of 4 at 4, multi-query attention with 32 heads at 32: all still well below a ridge in the hundreds.
Check your understanding

Which change reduces the bytes a decoding step reads from the cache but leaves the attention FLOPs per generated token unchanged?

  1. A sliding window of ww tokens
  2. FlashAttention
  3. Grouped-query attention
  4. Causal linear attention
Show the answer

C. Grouped-query attention

All HH query heads still score every cached token, so the FLOPs stay at 4Hdk4Hd_k per cached token and layer, while only HkvH_{kv} heads of keys and values are stored and read. A window cuts both bytes and FLOPs; linear attention replaces the cache with a fixed state and computes a different function.

More tokens per pass

Two ideas make each pass over the weights produce more tokens.

Batching. Decoding BB sequences together reads each weight once for all of them, so the weight matrices' intensity rises to about BB (The Roofline Model & Compute Efficiency). Each sequence still reads its own cache, so cache reads do not amortize: at long contexts they dominate, and throughput approaches the bandwidth divided by the cache bytes per sequence. Continuous batching keeps the batch full by letting finished sequences leave and new requests join after any step (Yu et al., 2022), and PagedAttention makes more sequences fit (Kwon et al., 2023).

Speculation. When a step is memory-bound, scoring several tokens costs about as much as scoring one, because the weights are read once either way. In speculative decoding a cheap draft model with next-token distribution qq proposes γ\gamma tokens; the large model, with distribution pp, scores all of them in one pass and accepts each drafted xx with probability min⁡(1,p(x)/q(x))\min\big(1,p(x)/q(x)\big), stopping at the first rejection and resampling that token from (p−q)+(p-q)_+ renormalized. The output is distributed exactly as if the large model had generated it alone, and if each drafted token is accepted independently with probability α\alpha, one pass yields (1−αγ+1)/(1−α)(1-\alpha^{\gamma+1})/(1-\alpha) tokens on average (Leviathan, Kalman & Matias, 2023; Chen et al., 2023).

FamilyExamplesWhat it reducesSame outputs?
Sparse patternssliding, dilated and strided windows; global and random links (Longformer, BigBird)scores computed; with windows, cache sizeno: a different model, trained with the pattern
Low-rank and kernel attentionLinformer, linear attention, Performerthe T2T^2 factorno
IO-aware kernelsFlashAttention and its successorsHBM traffic and activation memoryyes
Fewer or smaller keys and valuesMQA, GQA, latent attention; quantized cachescache size and bytes per steparchitectures are trained in; quantization is lossy
Evictionrecent tokens plus heavy hitters; sinks plus a windowcache sizeno
Scheduling and memory managementcontinuous batching, pagingidle hardware, fragmentationyes
Speculative decodingdraft models, extra prediction headslarge-model passes per tokenyes, in distribution
Open serving stacks of the mid-2020s combine several rows: exact attention kernels, grouped-query or latent attention, paged and often quantized caches, continuous batching and, where latency matters, speculation.

Key takeaways

  • Training and prefill are compute-bound matrix products. Decoding reads every weight and the whole KV cache for each token at about one FLOP per byte, so it is memory-bound by the ridge factor, hundreds on current accelerators.
  • A KV cache holds 2LTHkvdk2LTH_{kv}d_k numbers per sequence (2 GiB at 4,096 tokens for a 7B multi-head model); sharing key–value heads divides it by H/HkvH/H_{kv}, and latent attention, quantization and eviction shrink it further.
  • Sparse patterns compute fewer scores: LL windows of width ww relay information LwLw positions, and global and random links restore universality at a cost in depth. Low-rank and kernel methods approximate the softmax; a fixed-size state limits exact recall.
  • FlashAttention computes exact attention with far less memory traffic and O(T)\order{T} extra memory, changing no number in the model.
  • Batching amortizes weight reads but not cache reads; speculative decoding verifies several drafted tokens per pass, with a rejection rule that leaves the output distribution unchanged.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

On the illustrative accelerator (Π=1015\Pi=10^{15} FLOP/s, β=3×1012\beta=3\times10^{12} B/s), one decoding step of the 7B model at batch 1 and context 4,096 takes at least 5.2 ms. Which change lowers that bound the most?

  1. Doubling the peak FLOP/s
  2. Storing the weights and the cache in 8 bits instead of 16
  3. Restricting attention to a sliding window of 2,048 tokens
  4. Switching to FlashAttention
Show the answer

B. Storing the weights and the cache in 8 bits instead of 16

The step is memory-bound, so its time is bytes over bandwidth: 1.56×1010/(3×1012)1.56\times10^{10}/(3\times10^{12}) s. Halving every byte halves it, to about 2.6 ms. A 2,048-token window halves only the cache, 2.1 of the 15.6 GB, for about 4.9 ms, and more FLOP/s changes nothing.

Question 2

A decoder with L=40L=40 layers and 40 query heads of size 128 caches 16-bit keys and values. It is retrained with grouped-query attention and 8 key–value heads. How large is the cache per token now?

  1. 800 KiB, unchanged
  2. 80 KiB
  3. 160 KiB
  4. 20 KiB
Show the answer

C. 160 KiB

2×40×8×128×2=163,8402\times40\times8\times128\times2=163{,}840 bytes =160=160 KiB, a factor H/Hkv=5H/H_{kv}=5 below the 800 KiB of full multi-head attention. A 4,096-token conversation then needs 640 MiB instead of about 3.1 GiB.

Question 3

A 24-layer decoder uses sliding-window attention with w=1,024w=1{,}024 in every layer. Which statement is correct?

  1. Information can travel up to 24×1,024=24,57624\times1{,}024=24{,}576 positions back, but only by being relayed through intermediate positions, layer by layer
  2. Tokens more than 1,024 positions back can never influence the output
  3. The KV cache still grows with the full length of the text
  4. The attention FLOPs per generated token still grow with the full length of the text
Show the answer

A. Information can travel up to 24×1,024=24,57624\times1{,}024=24{,}576 positions back, but only by being relayed through intermediate positions, layer by layer

Each layer moves information at most ww positions, so LL layers reach LwLw; nothing farther is visible directly, and what arrives has been mixed into intermediate tokens on the way. The cache needs only the last ww entries per layer, and each token's attention costs about 4wd4wd FLOPs per layer.

Question 4

In speculative decoding, a draft model with next-token distribution qq proposes a token xx, and the target model's distribution at that position is pp. Which rule makes the emitted token follow pp exactly?

  1. Accept xx if it is the target's most likely token; otherwise emit the target's most likely token
  2. Accept xx with probability p(x)p(x); on rejection, sample again from qq
  3. Always accept xx, since the draft was trained to imitate the target
  4. Accept xx with probability min⁡(1,p(x)/q(x))\min\big(1,p(x)/q(x)\big); on rejection, sample from (p−q)+(p-q)_+ renormalized
Show the answer

D. Accept xx with probability min⁡(1,p(x)/q(x))\min\big(1,p(x)/q(x)\big); on rejection, sample from (p−q)+(p-q)_+ renormalized

Acceptance gives each token probability q(x)min⁡(1,p(x)/q(x))=min⁡(p(x),q(x))q(x)\min\big(1,p(x)/q(x)\big)=\min\big(p(x),q(x)\big), and the residual supplies the missing p(x)−min⁡(p(x),q(x))p(x)-\min\big(p(x),q(x)\big). Speculative Decoding proves it and counts the tokens each pass yields.

Go deeper

Further reading

  • Y. Tay, M. Dehghani, D. Bahri & D. Metzler, "Efficient transformers: A survey," ACM Computing Surveys (2022).
  • T. Dao, D. Y. Fu, S. Ermon, A. Rudra & C. Ré, "FlashAttention: Fast and memory-efficient exact attention with IO-awareness," NeurIPS (2022).
  • I. Beltagy, M. E. Peters & A. Cohan, "Longformer: The long-document transformer," arXiv:2004.05150 (2020).
  • A. Katharopoulos, A. Vyas, N. Pappas & F. Fleuret, "Transformers are RNNs: Fast autoregressive transformers with linear attention," ICML (2020).
  • R. Pope et al., "Efficiently scaling transformer inference," MLSys (2023).