# Search results for: "how does attention work"

## Count the attention work for 100 generated tokens (score: 1.000)

Source: https://aiengineeringfromscratch.com/interviews/transformers/count-attention-ops-with-cache
Kind: interview

A decoder generates 100 tokens one at a time from an empty prompt. Count the token states each loop computes for the prefix: a naive loop, and a loop that caches the key and value vectors of earlier tokens. Then count the query-key comparisons that remain with the store, and name what the store deliberately leaves out.

---

## Multi-Head Self-Attention: Attention weight inspection (score: 0.978)

Source: https://aiengineeringfromscratch.com/learn/capstone-projects/multihead-self-attention
Kind: lesson

The lesson exposes a return_weights=True flag on the forward pass. When set, the block returns the per-head attention weights of shape (B, H, T, T) alongside the output. The demo prints a heatmap of one head's weights on a short input so you can see the causal-triangle structure and the per-position focus.
In a trained model, different heads learn different patterns. Some heads attend to the immediately previous token. Some heads attend to the start of the sequence. Some heads spread attention almost uniformly. The inspection hook is the entry point for that interpretability work.

---

## Native Sparse Attention (DeepSeek NSA) (score: 0.941)

Source: https://aiengineeringfromscratch.com/learn/llms-from-scratch/native-sparse-attention
Kind: lesson

Native Sparse Attention (DeepSeek NSA)
At 64k tokens, attention eats 70-80% of decode latency. Every open-model lab has a plan to fix it. DeepSeek's NSA (ACL 2025 best paper) is the one that stuck: three parallel attention branches — compressed coarse-grained tokens, selectively retained fine-grained tokens, and sliding windows for local context — combined through a learned gate. It is hardware-aligned (kernel-friendly), natively trainable (works in pre-training, not bolted on at inference), and on 64k decodes it runs faster than FlashAttention while matching or beating full attention quality. This lesson builds the three branches end-to-end and shows why the sparsity is end-to-end differentiable.
Type: Build
Languages: Python (stdlib), Rust
Prerequisites: Phase 7 · 12 (KV cache, flash-attention), Phase 7 · 15 (attention variants), Phase 10 · 16 (differential attention)
Time: ~60 minutes

---

## Multi-Head Self-Attention: The frame (score: 0.941)

Source: https://aiengineeringfromscratch.com/learn/capstone-projects/multihead-self-attention
Kind: lesson

Attention is the function that lets a token's representation pull information from other tokens in the same sequence. Self-attention means queries, keys, and values are all derived from the same input. Multi-head means the projection is split into H parallel attention problems whose outputs are concatenated and projected back.
The efficient implementation pattern is one linear layer that projects from D to 3 * D and gets sliced into three views, then reshaped into H heads of size D // H each. The matmul, softmax, and weighted sum happen as batched tensor operations so the heads run in parallel on the accelerator.
This lesson builds that block. It also adds the causal mask so the same code works as the attention layer in a decoder-only language model. The next lesson stacks the block into a full transformer and the lesson after trains it.

---

## Native Sparse Attention (DeepSeek NSA): The Concept (score: 0.914)

Source: https://aiengineeringfromscratch.com/learn/llms-from-scratch/native-sparse-attention
Kind: lesson

The selection step (top-k blocks) is discrete. Discrete operations break gradient flow. Prior sparse-attention work either skipped backprop through selection (limiting training) or used continuous relaxations that did not give real sparsity at inference.
NSA sidesteps this: the compressed-branch attention IS a differentiable coarse-grained attention on the whole sequence. The top-k operation just reuses the top attention scores from the compressed branch to pick which fine-grained blocks to load. Gradients reach the compressed-branch scores through the compressed branch's own output, not through the choice of blocks. Inside the chosen blocks, attention over the selected keys and values is ordinary attention, so their contribution to the final output is differentiable too. The top_k index choice itself gets no gradient: it only controls which blocks get loaded from memory.
This is why NSA can be used in pre-training end to end. The model learns to route information through the three branches jointly, producing a sparse pattern that at inference actually delivers the promised speedup.
Hardware-aligned kernel

---

## How vLLM picks an attention backend (score: 0.902)

Source: https://aiengineeringfromscratch.com/manual-vllm-101/how-vllm-picks-an-attention-backend
Kind: manual

Manuals / vLLM 101 / Part 8 · How vLLM Works
8.4
How vLLM picks an attention backend
This page explains the selection order for each GPU class and what vLLM picks when the first choice cannot run.
The attention kernel is the one part of the forward pass that changes most between GPUs. When you finish this section, you can predict the backend vLLM picks on your GPU, and explain why one flag change can swap it.

---

## Flamingo and Gated Cross-Attention for Few-Shot VLMs: The Problem (score: 0.877)

Source: https://aiengineeringfromscratch.com/learn/multimodal-ai/flamingo-gated-cross-attention
Kind: lesson

BLIP-2 feeds 32 visual tokens into a frozen LLM's input layer. Works for one image per prompt. But what if you want to feed many images interleaved with text, as in "here is image A, caption it; here is image B, caption it; now here is image C, caption it"? The LLM's self-attention would need to handle image tokens and text tokens in a single stream, and the question of which positions can attend to which images gets fussy.
Flamingo's answer: do not change the LLM's input stream at all. Insert extra cross-attention layers between existing LLM blocks. Text tokens still flow through the LLM's causal self-attention as always. Between every few LLM blocks, text tokens also cross-attend to image features via a new gated layer. The gate (initialized to zero) means at step zero the new layers are no-ops — the model behaves exactly like the pretrained LLM. As training progresses the gate opens and visual information starts flowing.

---

## KV Cache, Flash Attention & Inference Optimization: The Problem (score: 0.876)

Source: https://aiengineeringfromscratch.com/learn/transformers-deep-dive/kv-cache-flash-attention
Kind: lesson

A naive autoregressive decoder does $O(N^2)$ work to generate $N$ tokens: at each step it recomputes attention over the full prefix. For a 4K-token response that is 16M attention operations, most of them redundant. Every hidden state of a prefix token is deterministic once computed — you only need to run the new token's query against the cached keys and values of everything before.
On top of that, attention itself moves a lot of data. Standard attention materializes an N×N score matrix, N×d softmax output, N×d final output — too many reads and writes to HBM. For N≥2K, attention becomes memory-bound before it becomes FLOP-bound. Classic attention kernels underuse modern GPUs by 4–10×.
Two optimizations, both from Dao et al., pushed frontier inference from "slow" to "fast":
KV cache. Store the K and V vectors of every prefix token. Each new token's attention is one query against the cached keys. Inference reduces from $O(N^2)$ to $O(N)$ per generation step.
Flash Attention. Tile the attention computation so the full N×N matrix never hits HBM. All of softmax + matmul happens in SRAM. 2–4× wall-clock speedup on A100; 5–10× on H100 with FP8.
By 2026 both are universal. Every production inference stack (vLLM, TensorRT-LLM, SGLang, llama.cpp) assumes them. Every frontier model ships with Flash Attention enabled.
