attention mechanism

```svg Attention — Scaled Dot-Product in Detail Attn(Q,K,V) = softmax(QKᵀ/√d_k) · V — every token queries every other for relevance, then reads their values Step-by-Step (one head, seq_len=5, d_k=4) Step 1: project input to Q, K, V X 5×d Q 5×4 K 5×4 V 5×4 Step 2: QKᵀ scores scores (5×5) Step 3: /√d + softmax weights (rows sum=1) Step 4: weights × V out 5×4 context- aware Multi-Head Attention (h heads) Head 0 Head 1 Head 2 ... h-1 Concat → W_O projection output (seq_len × d_model) each head: d_k = d_model / h (e.g., 128 = 12288/96) Causal Mask (decoder) green = can attend black = masked (-inf) token can only see past + self Complexity + Optimizations Naive: O(n²) time and memory 128K context → 128K² = 16B elements Optimizations: FlashAttention: tile in SRAM, no n² mem KV cache: store past K,V for decode Ring attention: shard seq across GPUs Attention Variants Multi-Head (MHA): full K,V per head Multi-Query (MQA): shared K,V Grouped-Query (GQA): groups share Sliding window: local context only Cross-attention: Q from one, K/V other GQA used by Llama-3, Gemma, Mistral Attention = differentiable database lookup. Q is the query, K is the key, V is the value. Soft match by dot product. This single operation — weighted average based on learned relevance — is why transformers can model any sequence. GPT-4: 96 heads × 96 layers, d_k=128, context=128K → attention dominates compute and memory FlashAttention reduced memory from O(n²) to O(n) — enabling 100K+ context without OOM Attention is how a model decides what matters — every token votes on relevance, and the network learns what to attend to. ```ntion is the core operation of the Transformer: it lets every token in a sequence look at every other token and pull in the information most relevant to it. Each token emits three learned vectors — a query, a key, and a value — and attention scores how well one token's query matches every token's key, turns those scores into weights that sum to one, and returns a weighted average of the values. The result is a context-aware representation of each token, computed in a single parallel operation rather than step by step.\n\n**A dot product measures relevance, a softmax turns it into a mixture.** For a given query, the model takes its dot product with every key in the sequence; a large dot product means that token is relevant. Those raw scores are divided by the square root of the head dimension to keep them from growing too large as vectors get wider, then passed through a softmax so they become non-negative weights that add to one. Attention is therefore a soft, differentiable lookup: instead of retrieving one entry from a table, it retrieves a blend of all entries, weighted by learned similarity.\n\n**The output is a weighted sum of values, and that is what makes context flow.** Once the weights are known, the output for each position is the sum of every token's value vector scaled by its weight. A token that needs its subject two words back will place most of its weight there; a token that needs a distant clause will reach across the whole sequence. Because queries, keys, and values are all learned projections, the model discovers on its own which relationships matter — subject-verb agreement, coreference, syntax — without any hard-wired notion of position or distance beyond what the encoding supplies.\n\n| Component | Role | Shape intuition |\n|---|---|---|\n| Query (Q) | what this token is looking for | one vector per token |\n| Key (K) | what each token offers | one vector per token |\n| Value (V) | the content to mix in | one vector per token |\n| QKᵀ | relevance score per pair | sequence × sequence |\n| ÷ √d + softmax | scores → weights (sum to 1) | row-wise distribution |\n| Σ weight·V | context-mixed output | one vector per token |\n\n```svg\n\n \n Attention — each token builds a weighted mix of every token’s value\n\n Scaled dot-product attention, step by step\n QKVlearned projections of the inputscores = QKᵀdot product every query×key÷ √dstabilize the magnitudessoftmaxweights, each ≥0, sum = 1output = Σ weight·Vcontext-mixed vector\n\n \n\n One query attends: weights sum to 1\n query: “sat”The0.05cat0.42sat0.20on0.05the0.06mat0.22keys / values (all tokens)thick arrow = high weightoutput ≈ 0.42·V(cat) + 0.22·V(mat) + …the weights are a probability distribution over context\n\n A token’s query is compared to every token’s key by dot product, giving a raw score per pair; dividing by √d keeps the\n scores in a stable range, and a softmax turns them into weights that sum to one — a soft, learned lookup over the sequence.\n The output is the weighted sum of the value vectors, so each position pulls in exactly the context it needs. Cost grows as the\n sequence squared (every query × every key), which is why the KV cache, Flash Attention, and sparse variants all target it.\n\n```\n\n**Its cost is quadratic in sequence length, and that shapes all of modern LLM hardware.** Because every query compares against every key, both the compute and the score matrix grow with the sequence length squared, and during generation the keys and values of all past tokens must be kept around — the KV cache. This single fact drives a huge amount of systems work: Flash Attention restructures the computation to avoid materializing the full score matrix, multi-query and grouped-query attention shrink the KV cache, and sparse or sliding-window variants skip most of the pairs outright. Self-attention (queries, keys, and values from the same sequence) builds internal context; cross-attention (queries from one sequence, keys and values from another) is how a decoder reads an encoder or a prompt.\n\nRead attention through a quant lens rather than a 'the model focuses' lens: the number that governs it is the sequence-length-squared count of query-key pairs, which sets both the FLOPs and the memory traffic every layer pays, and the KV cache turns that into a per-token memory cost during generation. Almost every attention variant is an attempt to move that number — reduce the pairs scored (sparse, sliding-window), reduce the bytes cached per token (MQA, GQA, MLA), or reduce the passes over memory (Flash Attention) — so the design question is always which part of the quadratic you can drop without losing the context the task actually needs.

Go deeper with CFSGPT

Get AI-powered deep-dives, save terms, and run advanced simulations — free account.

Create Free Account