AI Infra
0%
Part I · Chapter 8

Transformer Architecture and Its Variants

AuthorChangkun Ou
Reading time~28 min

Chapter 7 ended with a stable mapping from text to token ids. This chapter follows those ids through a decoder-only transformer: embedding, a stack of residual blocks, a final normalization, and a vocabulary projection. The 2017 Transformer introduced the attention-and-feed-forward block in an encoder-decoder system (Vaswani et al. 2017). Modern causal language models reuse that basic pattern, but differ in normalization, position handling, feed-forward design, attention heads, and cache representation.

Those choices are not cosmetic. They determine which positions can exchange information, how gradients travel through depth, how many parameters sit in each block, and how much state a serving process retains for every active sequence. A useful architecture description therefore needs tensor shapes, mask semantics, and memory units, not only a box labeled “Transformer.”

Scope: a causal decoder

Here a batch contains BB sequences of length SS, and the model width is dd. The tokenizer emits integer ids T{0,,V1}B×ST\in\{0,\ldots,V-1\}^{B\times S} for a vocabulary of size VV. An embedding table maps them to the initial residual stream X0RB×S×dX_0\in\mathbb{R}^{B\times S\times d}. After LL blocks and a final normalization, an output matrix produces logits over the vocabulary:

X^L=Normf(XL),Z=X^LWU,p(ti+1=vti)=softmax(Zi)v.\widehat{X}_L=\operatorname{Norm}_{f}(X_L), \qquad Z=\widehat{X}_LW_U, \qquad p(t_{i+1}=v\mid t_{\le i})=\operatorname{softmax}(Z_i)_v.

Here XLX_L is the last block's output, Normf\operatorname{Norm}_{f} is the final normalization, WURd×VW_U\in\mathbb{R}^{d\times V} is the output or unembedding matrix, ZiRVZ_i\in\mathbb{R}^{V} contains the logits at position ii, and vv is a candidate next-token id. The causal condition tit_{\le i} means that position ii may depend only on tokens at positions up to ii. Encoder-only models use bidirectional masks; encoder-decoder models also add cross-attention. Those architectures share components with this one, but they do not share its exact information-flow contract.

The input embedding and WUW_U^\top may share parameters, a design called weight tying (Press and Wolf 2017). Tying removes one VdVd matrix, but also forces the input and output roles to use the same rows. It is an architecture choice, not a rule for large or small models.

A block updates one residual stream twice

A common pre-normalized decoder block has two residual updates:

U=X+Attn(Norm,1(X)),X+1=U+FFN(Norm,2(U)).U_\ell=X_\ell+ \operatorname{Attn}_\ell(\operatorname{Norm}_{\ell,1}(X_\ell)), \qquad X_{\ell+1}=U_\ell+ \operatorname{FFN}_\ell(\operatorname{Norm}_{\ell,2}(U_\ell)).

Here {0,,L1}\ell\in\{0,\ldots,L-1\} is the block index; XX_\ell is the block input; UU_\ell is the state after self-attention; and X+1X_{\ell+1} is the block output. Attention mixes information across allowed positions. The feed-forward network (FFN) transforms each position independently. Both return a tensor with the same shape as the residual stream so that addition is defined.

The residual stream is the width-dd state carried through the stack. Calling it a stream is helpful, but it is not a separate memory module. It is the sequence of hidden vectors that every sublayer reads and updates.

block x0 residual X_l n1 Norm x0->n1 update p1 + x0->p1 identity a causal self-attention mix allowed positions n1->a update a->p1 update u residual U_l p1->u n2 Norm u->n2 update p2 + u->p2 identity f feed-forward network transform each position n2->f update f->p2 update x1 residual X_(l+1) p2->x1
Figure 8.1. One pre-normalized decoder block. Attention and the feed-forward network read normalized copies of the residual stream and add same-shaped updates back to its identity path.

This diagram specifies pre-normalization. The original Transformer instead normalized after each residual addition (Vaswani et al. 2017):

U=Norm,1(X+Attn(X)),X+1=Norm,2(U+FFN(U)).U_\ell=\operatorname{Norm}_{\ell,1} \bigl(X_\ell+\operatorname{Attn}_\ell(X_\ell)\bigr), \qquad X_{\ell+1}=\operatorname{Norm}_{\ell,2} \bigl(U_\ell+\operatorname{FFN}_\ell(U_\ell)\bigr).

Here the symbols have the same shapes as in the pre-normalized block, but the normalizers now act after each addition. Xiong et al. showed why pre-normalization has better-behaved gradients at initialization and can reduce reliance on learning-rate warmup (Xiong et al. 2020). That evidence does not make post-normalization invalid: initialization, residual scaling, depth, and optimizer settings change the comparison. Record the exact block equation rather than relying on the labels “pre-norm” or “post-norm.”

Normalization controls scale

LayerNorm centers a hidden vector and divides by its standard deviation (Ba et al. 2016). root mean square layer normalization (RMSNorm), introduced by Zhang and Sennrich in 2019, omits mean subtraction and normalizes by root mean square (Zhang and Sennrich 2019):

RMSNorm(x)=γx1dj=1dxj2+ε.\operatorname{RMSNorm}(x) =\gamma\odot \frac{x}{\sqrt{\frac{1}{d}\sum_{j=1}^{d}x_j^2+\varepsilon}}.

Here xRdx\in\mathbb{R}^{d} is one token's hidden vector; xjx_j is its jj-th component; γRd\gamma\in\mathbb{R}^{d} is a learned element-wise scale; ε>0\varepsilon>0 prevents division by zero; and \odot denotes element-wise multiplication. Implementations must pin ε\varepsilon, accumulation precision, and whether a learned bias is present. These details can affect checkpoint compatibility and low-precision stability.

Some architectures also normalize queries and keys before their dot product. That QK normalization solves a different problem from normalizing the residual stream: it bounds attention-score scale. A model manifest should state both locations independently.

The feed-forward network supplies per-position capacity

The original block used two matrices with a ReLU between them. A common gated alternative is Swish-gated linear unit (SwiGLU) (Shazeer 2020):

SwiGLU(x)=(SiLU(xWg)(xWu))Wd.\operatorname{SwiGLU}(x) =\bigl(\operatorname{SiLU}(xW_g)\odot(xW_u)\bigr)W_d.

Here xRdx\in\mathbb{R}^{d} is one residual vector; Wg,WuRd×dfW_g,W_u\in\mathbb{R}^{d\times d_f} are the gate and value projections; WdRdf×dW_d\in\mathbb{R}^{d_f\times d} projects back to model width; dfd_f is the FFN hidden width; and SiLU(z)=z/(1+ez)\operatorname{SiLU}(z)=z/(1+e^{-z}) is applied element-wise. Ignoring biases, this gated FFN has 3ddf3dd_f parameters. A plain two-matrix FFN has 2ddf2dd_f.

That count explains the often-quoted “two-thirds” adjustment. A plain FFN with hidden width 4d4d has 8d28d^2 parameters. Matching it with a three-matrix gated FFN requires df=8d/3d_f=8d/3, before rounding to a hardware-friendly multiple. The ratio is a budgeting rule, not an intrinsic property of SwiGLU. Actual models choose different expansion ratios, and equal matrix counts do not guarantee equal wall-clock time across kernels or hardware.

Attention and the FFN play different roles, but claims that one stores “knowledge” while the other only “routes” it are interpretations, not tensor invariants. Ablations can localize behavior; the forward equations alone do not assign semantic ownership.

Causal self-attention with explicit shapes

Here, for one sequence, let XRS×dX\in\mathbb{R}^{S\times d}. Assume equal query, key, and value head widths. Let HqH_q be the number of query heads, HkvH_{kv} the number of distinct key-value heads, and dhd_h the width of one head. Learned projections produce

QRS×Hq×dh,K,VRS×Hkv×dh.Q\in\mathbb{R}^{S\times H_q\times d_h}, \qquad K,V\in\mathbb{R}^{S\times H_{kv}\times d_h}.

Each query head aa is assigned to a key-value head g(a)g(a). For query position ii, its output is

αij(a)=softmaxj(qi(a)kj(g(a))dh+Mij),zi(a)=j=1Sαij(a)vj(g(a)).\alpha_{ij}^{(a)} =\operatorname{softmax}_{j} \left( \frac{q_i^{(a)\top}k_j^{(g(a))}}{\sqrt{d_h}}+M_{ij} \right), \qquad z_i^{(a)}=\sum_{j=1}^{S}\alpha_{ij}^{(a)}v_j^{(g(a))}.

Here qi(a)q_i^{(a)} is the query for head aa at position ii; kj(g(a))k_j^{(g(a))} and vj(g(a))v_j^{(g(a))} are the selected key and value at position jj; αij(a)\alpha_{ij}^{(a)} is their normalized attention weight; and MM is the mask. For ordinary causal attention, Mij=0M_{ij}=0 when jij\le i and Mij=M_{ij}=-\infty when j>ij>i. The -\infty entries become zero probability after softmax. Padding, packed documents, sliding windows, and prefix-language models require different masks.

The dh\sqrt{d_h} divisor keeps score variance from growing with head width under common initialization assumptions (Vaswani et al. 2017). Concatenating the HqH_q head outputs and applying an output projection returns a width-dd update for the residual addition.

When Hqdh=dH_qd_h=d and biases are omitted, the query and output projections hold 2d22d^2 parameters. The key and value projections hold 2dHkvdh2dH_{kv}d_h. Standard MHA with Hkv=HqH_{kv}=H_q therefore uses 4d24d^2 projection parameters. GQA and MQA reduce the K/V term as well as the cache, while dense query-key interaction still scales with S2HqdhS^2H_qd_h.

Start with one width-d residual vector at every token position.
Learned projections form query heads and the distinct key-value heads.
Each query scores allowed keys; the causal mask assigns future positions negative infinity.
Softmax turns each unmasked score row into non-negative weights that sum to one.
Each head takes a weighted sum of values, then all query heads are concatenated and projected.
Figure 8.2. The mathematical stages of causal self-attention. The mask is part of the operation, not cleanup applied after attention.
Figure 8.3. Illustrative weights for one causal attention head. Rows are queries, columns are keys, and each row is normalized over its allowed keys. These values are not measurements from a trained model and do not by themselves explain the model's decision.

A dense attention layer forms S2S^2 query-key relationships across a full sequence. The arithmetic is therefore quadratic in SS. A naive implementation also materializes an S×SS\times S score matrix, but that temporary storage is not required by the mathematical definition.

Position enters through queries and keys

Unmasked content-only self-attention is permutation-equivariant: permuting the input positions permutes its outputs. A causal mask already imposes a direction, but it does not give equal content vectors an explicit distance representation. rotary position embedding (RoPE) applies a position-dependent rotation to pairs of query and key coordinates (Su et al. 2024). For an even rotated width dRd_R, define

ωr=θ2r/dR,Rp(r)=[cos(pωr)sin(pωr)sin(pωr)cos(pωr)],0r<dR/2.\omega_r=\theta^{-2r/d_R}, \qquad R_p^{(r)}= \begin{bmatrix} \cos(p\omega_r)&-\sin(p\omega_r)\\ \sin(p\omega_r)&\cos(p\omega_r) \end{bmatrix}, \quad 0\le r<d_R/2.

Here θ>0\theta>0 is the frequency base; rr indexes a pair of rotated coordinates; ωr\omega_r is that pair's angular frequency; and pp is token position. Let RpR_p be the block-diagonal matrix made from all Rp(r)R_p^{(r)}. Then

qi=Riqi,kj=Rjkj,qikj=qiRjikj.q_i'=R_iq_i, \qquad k_j'=R_jk_j, \qquad q_i'{}^\top k_j'=q_i^\top R_{j-i}k_j.

Here qiq_i and kjk_j are unrotated query and key vectors; RiR_i and RjR_j use the configured frequency schedule; and the last identity shows that the positional part of their dot product depends on relative offset jij-i. RoPE does not make the complete attention score a function of distance alone; the content vectors still matter.

The frequency base, the fraction of dimensions rotated, and any scaling used for context extension belong in the checkpoint contract. Changing them after training is an adaptation experiment, not a metadata edit. RoPE is common, but it is not the only valid scheme. ALiBi instead adds a head-specific linear distance penalty to each causally valid score (Press et al. 2022):

sij(a)=qi(a)kj(a)dhma(ij)+Mij.s_{ij}^{(a)}= \frac{q_i^{(a)\top}k_j^{(a)}}{\sqrt{d_h}} -m_a(i-j)+M_{ij}.

Here ma>0m_a>0 is a fixed slope for head aa; iji-j is non-negative for an allowed past position; and MijM_{ij} is the causal mask defined earlier. ALiBi introduces no learned position vectors. Long-context behavior under either method depends on training length, frequency or slope configuration, later adaptation, and the evaluation distribution.

Prefill creates the cache; decode reuses it

Autoregressive serving exposes a distinction that a full-sequence training diagram hides. The first pass is prefill: it reads the entire prompt under the causal mask, produces logits at its positions, and populates keys and values for the prompt. The logits at the last prompt position predict the first generated token. The positions can run in parallel, although serving systems may split a long prefill into chunks. The second phase is decode: it processes one new position per sequence, attends from that new query to stored past keys and values, selects or samples a token, appends that position's keys and values, and repeats.

In standard causal self-attention with a fixed prefix, a past position's key and value at a given layer do not change during later decode steps. Reusing them avoids projecting the whole prefix again. A dense decode step still reads the retained cache, making it a bandwidth cost as well as a capacity cost. For a ragged batch, the persistent key-value (KV) tensor payload is

MKV=br=1BSr=1LHkv,(dk,+dv,)bytes.M_{\mathrm{KV}} =b\sum_{r=1}^{B}S_r \sum_{\ell=1}^{L}H_{kv,\ell}(d_{k,\ell}+d_{v,\ell}) \quad\text{bytes}.

Here BB is the number of resident sequences; SrS_r is the cached length of sequence rr; LL is the number of attention layers; Hkv,H_{kv,\ell} is the number of distinct KV heads in layer \ell; dk,d_{k,\ell} and dv,d_{v,\ell} are the key and value elements per head; and bb is bytes per cached element. For uniform length SS and equal dk=dv=dhd_k=d_v=d_h, this reduces to 2LBSHkvdhb2LBSH_{kv}d_hb. Real servers also have allocation blocks, metadata, padding or fragmentation, quantization scales, speculative or beam state, prefix sharing, and possible offload. The formula is the dense tensor payload, not total process memory.

With cache reuse, dense attention for one new token is linear in retained length SS per layer, omitting head and dimension factors. Generating TT new tokens after a prompt of length PP therefore performs attention work proportional to TP+T2TP+T^2 across decode. Cache reuse prevents repeated prefix projection; it does not make long decode constant-time.

The cache scales linearly with resident tokens. Whether it exceeds model weights depends on all the quantities above, plus weight and cache precision. It is therefore incorrect to present one crossover as a property of Transformers in general.

Figure 8.4 uses explicit assumptions: 32 layers, 128-wide heads, two bytes per KV element, batch size one, and 7 billion two-byte weight parameters. The plotted MHA, GQA, and MQA lines differ only in HkvH_{kv}, so every value follows directly from the cache equation.

2026-08-03T21:01:02.271680 image/svg+xml Matplotlib v3.11.0, https://matplotlib.org/ 0 50 100 150 200 250 context length (thousands of tokens) 0 20 40 60 80 100 120 KV payload (GiB) MHA (32 KV heads) GQA (8 KV heads) MQA (1 KV head) 7B weights at 2 bytes / parameter
Figure 8.4. Exact KV payload under a stated 7B-class configuration. MHA uses 32 KV heads, GQA uses eight, and MQA uses one. The horizontal line is 7 billion two-byte weight parameters; allocator overhead and runtime workspace are excluded.

The runnable cell prints the cache payload per token and the context length at which that payload equals the stated weight bytes. Change batch size, precision, or KV-head count to test a different deployment.

layers = 32
head_width = 128
bytes_per_kv_element = 2
batch_size = 1
parameter_count = 7_000_000_000
bytes_per_weight = 2
weight_bytes = parameter_count * bytes_per_weight

def kv_payload_bytes(sequence_length, kv_heads):
    return (
        2
        * layers
        * batch_size
        * sequence_length
        * kv_heads
        * head_width
        * bytes_per_kv_element
    )

for name, kv_heads in [("MHA", 32), ("GQA", 8), ("MQA", 1)]:
    bytes_per_token = kv_payload_bytes(1, kv_heads)
    crossover_tokens = weight_bytes / bytes_per_token
    cache_at_128k_gib = kv_payload_bytes(128_000, kv_heads) / 2**30
    print(
        f"{name}: {bytes_per_token / 1024:.0f} KiB/token; "
        f"128k cache={cache_at_128k_gib:.2f} GiB; "
        f"equals weight bytes at {crossover_tokens:,.0f} tokens"
    )

MHA, GQA, and MQA change KV-head sharing

Multi-head attention (MHA) uses Hkv=HqH_{kv}=H_q: every query head has its own key and value head (Vaswani et al. 2017). Multi-query attention (MQA) uses Hkv=1H_{kv}=1, so all query heads share one key and value head (Shazeer 2019). Grouped-query attention (GQA) chooses an intermediate 1<Hkv<Hq1<H_{kv}<H_q and assigns several query heads to each KV head (Ainslie et al. 2023).

Under the dense-payload formula, changing MHA to GQA reduces cache bytes by Hq/HkvH_q/H_{kv} when all other dimensions stay fixed. Changing MHA to MQA reduces them by HqH_q. These are exact storage ratios, not quality claims. Ainslie et al. reported that an MHA checkpoint could be uptrained into GQA using 5% of its original pretraining compute, with quality close to MHA and speed comparable to MQA in their experiments (Ainslie et al. 2023). The result supports GQA as a useful design point; it does not prove one KV-head count is optimal for every model and context length.

kv cluster_mha MHA: H_q=4, H_kv=4 cluster_gqa GQA: H_q=4, H_kv=2 cluster_mqa MQA: H_q=4, H_kv=1 mq1 Q1 mk1 KV1 mq1->mk1 mq2 Q2 mk2 KV2 mq2->mk2 mq3 Q3 mk3 KV3 mq3->mk3 mq4 Q4 mk4 KV4 mq4->mk4 gq1 Q1 gk1 KV1 gq1->gk1 gq2 Q2 gq2->gk1 gq3 Q3 gk2 KV2 gq3->gk2 gq4 Q4 gq4->gk2 qq1 Q1 kk1 KV1 qq1->kk1 qq2 Q2 qq2->kk1 qq3 Q3 qq3->kk1 qq4 Q4 qq4->kk1
Figure 8.5. Four query heads under MHA, two-group GQA, and MQA. Cached payload is proportional to the number of distinct blue KV boxes, not to the number of query heads that read each box.

MLA changes the cached representation

Multi-head latent attention (MLA), introduced in DeepSeek-V2, does not obtain its main saving by sharing a conventional KV head (DeepSeek-AI 2024). It projects each residual vector into a low-dimensional latent ciKVRdcc_i^{KV}\in\mathbb{R}^{d_c}, from which content keys and values are derived. A separate small RoPE key component is retained because applying a position-dependent rotation prevents the full key projection from being absorbed into later matrix multiplications.

In the DeepSeek-V2 construction, the per-position payload is

MMLA=LBS(dc+dhR)bbytes.M_{\mathrm{MLA}}=LBS(d_c+d_h^R)b\quad\text{bytes}.

Here dcd_c is the joint KV latent width; dhRd_h^R is the decoupled RoPE-key width; and LL, BB, SS, and bb have the meanings defined for the dense cache. DeepSeek-V2 sets dc=4dhd_c=4d_h and dhR=dh/2d_h^R=d_h/2, or 4.5dh4.5d_h cached elements per position and layer. A conventional equal-width MQA cache stores 2dh2d_h elements, so MLA is not generically “smaller than MQA.” During optimized decode, the up-projection matrices can be absorbed into the query and output projections; full per-head K and V need not be explicitly reconstructed.

DeepSeek reported lower cache requirements than its MHA baseline and better results on most listed metrics in its controlled ablations. That is evidence for the reported architecture and training recipe, not a general theorem that latent attention dominates GQA.

Separate arithmetic, temporary memory, and persistent state

Several techniques called “efficient attention” act on different resources:

Technique Changes attention result? Main resource changed What remains
FlashAttention No; exact dense attention up to numerical ordering HBM traffic and temporary score storage Dense quadratic attention arithmetic and the persistent KV cache
MQA / GQA Yes; query heads share K and V projections KV parameters, cache payload, and decode bandwidth Every query still attends to every allowed cached position
MLA Yes; K/V content uses a latent factorization Cached representation and associated bandwidth Dense position coverage unless combined with sparsity
Trained sparse attention Yes; only selected positions or blocks enter the main attention Main score/value arithmetic and memory traffic Selector work and cache footprint depend on the design

FlashAttention tiles exact attention so the full score matrix need not be written to high-bandwidth memory (Dao et al. 2022). It reduces IO and temporary activation memory during training and prefill. It does not by itself change the number of past key/value elements retained for decode.

Sparse attention changes the mathematical connectivity. Native sparse attention jointly trains three gated branches: compressed coarse-grained tokens, selected fine-grained blocks, and a local sliding window (Yuan et al. 2025). DeepSeek Sparse Attention (DSA) is a distinct later design. Its low-dimensional lightning indexer ranks past tokens, after which the main MLA path attends to a selected top-kk subset (DeepSeek-AI 2025). The main attention work moves from all SS past positions toward kSk\ll S, but the indexer reported for DeepSeek-V3.2 still scores all query-key pairs and remains quadratic at a smaller dimension. Selector error, continued-training cost, and retained cache state also count. Sparse selection does not automatically delete the full cache.

What's contested

There is no single efficiency frontier independent of workload. GQA has a simple dense computation and an exact head-count storage formula. MLA changes the factorization and may reduce cache further under a matched recipe. Learned sparsity attacks position coverage, but adds a selector whose recall and hardware efficiency must be measured. Training loss, long-context task quality, prefill throughput, decode latency, resident batch size, and implementation maturity can rank the same candidates differently.

Constraint arrow

The tokenizer fixes vocabulary size VV and the sequence lengths presented to this architecture. This chapter then fixes model width, block count, head dimensions, mask semantics, position scheme, and cache representation. Those choices become tensor shapes and memory demand for Chapter 10 and Chapter 31. A serving kernel may implement the equations more efficiently, but it cannot silently change their mask, head mapping, or checkpoint row meanings.

Record the architecture as a contract

A reproducible decoder specification should name at least:

  • vocabulary size, embedding width, output projection shape, and weight tying;
  • block count, model width, FFN width, activation, and all bias settings;
  • residual ordering, normalization locations, type, epsilon, and precision;
  • query-head count, KV-head count, head width, and query-to-KV mapping;
  • attention mask, document-boundary behavior, and any local or sparse pattern;
  • position mechanism, RoPE base and rotated dimensions, plus scaling rules;
  • cache representation, element type, quantization scale granularity, and payload bytes per token;
  • final normalization and any logit scaling or clipping.

Names such as “LLaMA-like” or “GQA” leave several of these fields undefined. The serialized model configuration, checkpoint tensors, training code, and serving engine must agree on the same contract.

Validate before the full training run

  1. Check shapes and parameter counts. Derive every projection shape and reconcile the total with serialized tensors, including tied parameters.
  2. Test causality. Perturb future tokens and confirm earlier logits do not change. Include padding, packed documents, and prefix masks where used.
  3. Compare a reference attention path. On small tensors, compare the optimized kernel with a straightforward high-precision implementation and declare numerical tolerances.
  4. Test cached equivalence. Confirm token-by-token decode logits match a full-prefix forward pass within tolerance at every position.
  5. Measure cache bytes. Compare allocated and payload memory against the declared formula across batch sizes and sequence lengths.
  6. Exercise position boundaries. Test the trained length, the deployed maximum, and offsets used by prefix caching or sequence packing.
  7. Ablate architecture choices. Compare normalization, FFN, head sharing, and position candidates under matched parameter, token, and compute budgets.
  8. Benchmark end to end. Report training throughput, prefill latency, decode latency, maximum resident batch, and quality on the target workload.

The block is compact enough to draw on one page, but its contract reaches from token ids to serving memory. Precision comes from keeping the mathematical operation, its tensor layout, and its runtime representation distinct.

Further reading

  • Vaswani et al., “Attention Is All You Need,” 2017. arXiv:1706.03762
    The Transformer replaces recurrence with multi-head attention and position-wise feed-forward blocks, enabling substantially more parallel sequence training.
  • Ba et al., “Layer Normalization,” 2016. arXiv:1607.06450
    Layer normalization computes normalization statistics across all hidden units within a single layer and training case, eliminating batch-size constraints and stabilizing recurrent neural network training.
  • Zhang & Sennrich, “Root Mean Square Layer Normalization” (RMSNorm), 2019. arXiv:1910.07467
    RMSNorm replaces LayerNorm's mean-and-variance normalization with RMS-only scaling, achieving comparable accuracy while reducing per-step runtime by 7 to 64 percent.
  • Xiong et al., “On Layer Normalization in the Transformer Architecture,” 2020. arXiv:2002.04745
    This paper uses mean field theory to show that placing layer normalization inside residual blocks (Pre-LN) yields well-behaved gradients at initialization, allowing Transformer training without learning rate warm-up.
  • Hendrycks & Gimpel, “Gaussian Error Linear Units (GELUs),” 2016. arXiv:1606.08415
    This paper introduces GELU, an activation function defined as x times the Gaussian CDF, which outperforms ReLU and ELU across vision, NLP, and speech tasks.
  • Shazeer, “GLU Variants Improve Transformer” (SwiGLU), 2020. arXiv:2002.05202
    This paper proposes GLU variants such as SwiGLU and GEGLU as replacements for the ReLU activation in the Transformer FFN sublayer, finding they improve perplexity and downstream task quality.
  • Su et al., “RoFormer: Enhanced Transformer with Rotary Position Embedding” (RoPE), 2024. arXiv:2104.09864
    RoFormer introduces RoPE, which encodes token positions as rotation matrices in self-attention, giving sequence-length flexibility and decaying inter-token dependency with distance.
  • Press et al., “Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation” (ALiBi), 2022. arXiv:2108.12409
    ALiBi replaces positional embeddings with per-head linear distance penalties on attention scores, enabling transformers trained on short sequences to extrapolate to longer ones at inference time with no added runtime cost.
  • Press & Wolf, “Using the Output Embedding to Improve Language Models” (weight tying), 2017. arXiv:1608.05859
    Tying the input and output embedding matrices in neural language models reduces perplexity and can cut translation model parameter count to less than half with no performance loss.
  • Shazeer, “Fast Transformer Decoding: One Write-Head is All You Need” (MQA), 2019. arXiv:1911.02150
    Multi-query attention (MQA) shares keys and values across all attention heads, cutting memory bandwidth for incremental decoding with only minor quality loss.
  • Ainslie et al., “GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints,” 2023. arXiv:2305.13245
    Grouped-query attention uses an intermediate number of KV heads; in the paper's uptraining experiments it approaches MHA quality with MQA-like speed using 5 percent of original pretraining compute.
  • Dao et al., “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness,” 2022. arXiv:2205.14135
    Dense FlashAttention computes exact attention with IO-aware tiling, reducing HBM traffic and avoiding materialization of the full score and probability matrices.
  • DeepSeek-AI, “DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model” (introduces multi-head latent attention (MLA)), 2024. arXiv:2405.04434
    DeepSeek-V2 introduces multi-head latent attention, which caches a compressed joint KV latent plus a decoupled positional key component.
  • Yuan et al., “Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention” (NSA, trainable sparse attention), 2025. arXiv:2502.11089
    NSA trains a gated combination of compressed-token, selected-block, and local-window attention branches end to end, with hardware-aligned kernels for long contexts.
  • DeepSeek-AI, “DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models” (DeepSeek sparse attention (DSA) in production), 2025. arXiv:2512.02556
    DeepSeek-V3.2 introduces DSA: a low-dimensional lightning indexer selects top-k latent entries for the main MLA path, while the indexer itself still performs lower-cost quadratic scoring.
  • Touvron et al., “LLaMA: Open and Efficient Foundation Language Models,” 2023. arXiv:2302.13971
    LLaMA introduces a family of open foundation language models (7B to 65B parameters) trained exclusively on public data, where smaller models trained on more tokens match or outperform larger proprietary models at inference.
  • Bai et al., “Qwen Technical Report,” 2023. arXiv:2309.16609
    Qwen is a family of large language models trained on up to 3 trillion tokens, covering base pretrained models, RLHF-aligned chat models, and specialized coding and mathematics variants.
  • Yang et al., “Qwen2 Technical Report,” 2024. arXiv:2407.10671
    Qwen2 is a series of open-weight LLMs (0.5B to 72B, plus a 57B-A14B MoE) trained on 7T tokens with GQA, RoPE, SwiGLU, DPO, and strong multilingual coverage across  30 languages.
  • Yang et al., “Qwen2.5 Technical Report,” 2024. arXiv:2412.15115
    Qwen2.5 is a family of LLMs trained on 18 trillion tokens with SFT, DPO, and GRPO post-training, spanning dense models from 0.5B to 72B and MoE variants Qwen2.5-Turbo and Qwen2.5-Plus.

Comments

Log in to comment