What is a Transformer?
The Transformer is a neural network architecture introduced in Attention Is All You Need. The original machine translation model combined an encoder and decoder with attention, without the recurrent sequence processing characteristic of RNNs. Modern models may use an encoder, a decoder or both. [1]
Instead of passing information exclusively through successive recurrent states, self-attention computes relationships among positions permitted by a mask. This enables parallel processing across positions when the input sequence is known, but does not mean an autoregressive model generates its entire response simultaneously. Transformers are not synonymous with LLMs: Vision Transformer processes representations of image patches. [1][5][12]
From tokens to contextual representations
A tokenizer converts text into token IDs. An embedding table maps IDs to learned vectors of dimension d_model. For n tokens, the input matrix X has shape n × d_model (ignoring the batch dimension). Successive blocks update representations at those positions; the same token can acquire different hidden states depending on context. A hidden state is not automatically a document embedding suitable for retrieval. [1][6]
Attention alone without positional information does not explicitly encode order. The original Transformer added sinusoidal positional encodings to embeddings. RoPE rotates components of Q and K according to their positions, allowing dot products to reflect relative offsets. Learned position embeddings and relative biases also exist. RoPE does not guarantee reliable extrapolation to arbitrary context lengths. [1][7]
Without position encodings and without an order-dependent mask, self-attention is permutation-equivariant: permuting tokens correspondingly permutes its outputs. A causal mask itself introduces an ordering asymmetry, so this statement does not apply unconditionally to decoders. Positional encoding and masking serve different purposes. [1][7]
How does self-attention work?
| Step | Calculation | Result |
|---|---|---|
| Dot products | q·k₁, q·k₂ | (1; 0) |
| Scaling | (1/√2; 0) | (0.707107; 0) |
| Softmax | exp(sᵢ) / Σ exp(sⱼ) | (0.669762; 0.330238) |
| Weighted sum | p₁v₁ + p₂v₂ | (1.339523; 1.320954) |
For one head, form Q = XW_Q, K = XW_K and V = XW_V. The W matrices are learned parameters. A query is compared with keys; values are mixed according to the resulting weights. These are not database queries or internet searches. [1][2]
For one self-attention head, Q and K have shape n × d_k, and V has shape n × d_v. QKᵀ has shape n × n; multiplying weights by V yields n × d_v. Weights depend on the input, unlike projection parameters that remain fixed during inference. Match mask conventions to the library: PyTorch SDPA uses boolean True for allowed positions. [2]
Scaled dot-product attention is Attention(Q,K,V) = softmax(QKᵀ/√d_k + M)V. Here d_k is the key dimension and M is an additive mask: 0 for allowed positions and −∞ for disallowed ones. Softmax runs along the key axis; a row with at least one allowed position has weights summing to one in exact arithmetic. Scaling by √d_k limits the growth of dot-product magnitude under the assumptions in the original paper. [1][2]
For three positions, a causal mask permits keys (1), (1, 2) and (1, 2, 3) for successive queries. A padding mask excludes artificial tokens used to align sequence lengths; both masks may be needed simultaneously. In PyTorch SDPA, True permits a key, whereas in MultiheadAttention.key_padding_mask True excludes it. A row with no permitted keys needs explicit handling, because ordinary softmax over all −∞ is undefined. During evaluation, explicitly pass dropout_p=0.0 to SDPA if dropout is not wanted. [1][2]
In the example below, q = (1,0) is compared with k₁ = (1,0) and k₂ = (0,1), with neither masking nor dropout. Values v₁ = (2,0) and v₂ = (0,4) yield a mixture of approximately (1.339523, 1.320954). These are synthetic inputs, not a model measurement. Attention weights are neither probabilities of truth nor a complete explanation of network decisions. [1][2][16]
What is inside a Transformer block?
Multi-head attention performs multiple learned projections and attention computations, concatenates their outputs and applies an output projection. Heads can learn different relationships but have no predetermined, uniquely identifiable roles. GQA shares each K/V head across several query heads; MQA uses one K/V head. This reduces conventional KV cache size without eliminating attention computations for all query heads. [1][8]
With 32 Q heads and 8 K/V heads (Grouped-Query Attention), each group of four Q heads shares one K/V head. Multi-Head Attention (MHA) uses equal head counts; Multi-Query Attention (MQA) uses one K/V head. MLA (Multi-head Latent Attention) uses a latent K/V representation and is not ordinary GQA. [8][13]
The feed-forward network (FFN) transforms each position independently, sharing parameters across positions within a layer. Residual connections add the input to a sublayer output; normalization helps stabilize computation. The original architecture used post-norm and ReLU. The Llama family uses pre-norm, RMSNorm and gated SwiGLU. A simplified pre-norm block is Y = X + Attention(Norm(X)), Z = Y + FFN(Norm(Y)). [1][6][18]
RMSNorm scales coordinates using their mean square: RMSNorm(x) = γ ⊙ x / √(mean(x²) + ε), where γ is a learned scale vector. Unlike LayerNorm, it does not subtract the mean. SwiGLU can be written as FFN(x) = (SiLU(xW_g) ⊙ (xW_u))W_d, with SiLU(z) = z·sigmoid(z) and elementwise multiplication (⊙). Gate and up projections have independent parameters. For a dense FFN with dimensions d and f this means 3df weights without biases, rather than 2df for a conventional two-layer FFN with the same intermediate width. This does not imply every SwiGLU model has more parameters: f may differ. [18][19][20]
Encoder, decoder and encoder-decoder models
| Architecture | Attention mechanism | Typical task |
|---|---|---|
| Encoder (BERT) | Bidirectional | Classification |
| Decoder (Llama) | Causal | Text generation |
| Encoder-decoder (T5) | Bidirectional encoder, causal and cross-attention in decoder | Translation |
BERT uses bidirectional attention over available input; its training includes masked-token prediction. An autoregressive decoder such as Llama uses a causal mask: position i may attend to positions j ≤ i. A conventional encoder-decoder adds cross-attention, with Q from the decoder and K and V from the encoder output. T5 exemplifies this text-to-text architecture. [1][3][4][6]
Choose according to task and training. Encoders can support classification or retrieval after suitable adaptation, decoders support generation, and encoder-decoder models can transform inputs into outputs, for example translation. Not every encoder is a ready-made embedding model, and decoders can also perform classification. [3][4][6]
Training and text generation
In typical causal language model training, known input tokens allow next-token predictions to be computed in parallel while respecting the causal mask. Logits are transformed into a probability distribution over the vocabulary; loss compares predictions with shifted target tokens. Backpropagation and an optimizer update weights. Other objectives, such as masking or predicting missing spans, use different schemes. [1][3][4]
During conventional autoregressive inference, the model first processes the prompt (prefill), selects a token from logits, then incorporates that token in the next step (decode). Selection can be deterministic or sampling-based. Temperature and top-p affect selection, not learned weights. Generation stops at an end token, limit or application rule. Speculative decoding may verify multiple candidate tokens together, so one token per invocation is not universal across engines. [12][14]
Training example: for tokens A, B, C, the prediction after A targets B, and the prediction after A, B targets C. The mask blocks access to the future target token; actual training computes loss for selected positions and may ignore some targets, such as padding. In ordinary inference the first generated token can be selected from the final prefill logits. Subsequent steps process new tokens and store their K/V. Post-training can change model behavior without changing its underlying architecture. [1][11][12][18]
Computational complexity and KV cache
| Tokens | Explicit FP16 score matrix | Example KV cache (8 K/V heads) | Example KV cache (32 K/V heads) |
|---|---|---|---|
| 4096 | 32 MiB | 512 MiB | 2 GiB |
| 8192 | 128 MiB | 1 GiB | 4 GiB |
| 16384 | 512 MiB | 2 GiB | 8 GiB |
For full attention with fixed head dimensions, the number of QK comparisons grows quadratically with n. A single head's score matrix has n × n elements; explicitly storing it at FP16 requires 32 MiB for 4096 tokens and 128 MiB for 8192 tokens. This is not total model memory. FlashAttention reduces memory transfers and avoids materializing the full score matrix, but does not remove the quadratic arithmetic complexity of full attention. [1][9][10]
Quadratic cost concerns positional interactions, not every operation in a block. For standard dense MHA with total head width d and FFN width f, attention projections cost O(nd²), QKᵀ and AV interactions cost O(n²d), and a dense FFN costs O(ndf). Constants, normalization and other operations are omitted. For m new positions processed one at a time after an initial context of n, with full attention and caching, the sum of attended context lengths over those m steps is mn + m(m+1)/2. This models interaction cost, not response time or total operation count. [1][9][11]
FlashAttention-4 describes optimizations for Blackwell hardware, including computation and data movement pipelining. Performance depends on hardware, kernel version, precision and tensor shapes; do not generalize a particular experiment to all models. [10]
KV cache retains keys and values from previous positions in decoder layers, avoiding repeated calculations. For standard K/V caches with equal dimensions and precision, raw bytes = 2 × L × H_kv × d_head × n × b × S, where L is layer count, H_kv K/V heads, b bytes per coordinate and S independent equal-length sequences. L=32, H_kv=8, d_head=128, n=8192, b=2, S=1 yields exactly 1 GiB, excluding metadata and allocation overhead. With 32 K/V heads it would be 4 GiB. [8][11]
KV cache is not persistent knowledge memory or a vector database. With full attention, a new token still attends to previous keys and values; attention cost per new position grows linearly with history length at fixed dimensions. Local attention, shared prefixes, MLA and hybrid architectures require different memory models. [11][13][17]
A dynamic KV cache can grow with the sequence; a static cache may reserve memory in advance. PagedAttention organizes the cache into blocks, reduces fragmentation and enables block sharing under suitable conditions. It does not by itself turn full attention into local attention and is not synonymous with FlashAttention. Cache quantization, RAM offloading and restricted attention windows are separate strategies with different costs and limitations. Check support for the actual model and runtime. [17][21]
Modern variants and limitations
RoPE addresses positional information, GQA the number of K/V heads, FlashAttention attention implementation, and MoE expert layers that often replace dense FFNs. These are distinct mechanisms that can coexist. DeepSeek-V3 documents MLA and MoE; not all models share that configuration. Weight quantization does not automatically quantize the KV cache. [6][7][8][9][11][13]
Example configuration: hidden_size=4096, num_attention_heads=32, num_key_value_heads=8, head_dim=128, num_hidden_layers=32. These specify hidden width, Q and K/V head counts, head dimension and depth. Total parameter count also requires information such as FFN width, vocabulary and weight sharing. In production, separately establish context limits, hardware compatibility and memory allocation strategy. [6][17]
For this illustrative configuration, with bias-free projections and K and V head dimensions both equal to 128, the Q width is 4096 and K and V each have width 1024. The Q, K, V and O projections contain 2 × 4096² + 2 × 4096 × 1024 = 41,943,040 weights in one layer. MHA with 32 K/V heads would have 67,108,864 weights. With an additional SwiGLU FFN of intermediate width f = 11,008, its three matrices contain 3 × 4096 × 11,008 = 135,266,304 weights. GQA projections and FFN together have 177,209,344 weights, excluding normalization, embeddings, the output head and other parameters. This is hypothetical, not the parameter count of a specific model. [6][8][18][20]
A larger context window does not guarantee effective use of every detail. Models can generate incorrect answers; attention does not verify facts, permissions or application security. Evaluate representative tasks and measure TTFT (time to first token), latency and throughput at the intended input length, concurrency and runtime. Do not infer actual inference speed from parameter count alone. [11][12][15]
