Attention

Attention computes context-dependent interactions between elements. It is the core mixing mechanism in Transformers and appears in graph, multimodal, retrieval, and agent systems.

Scaled dot-product attention is:

Here contains queries, contains keys, contains values, and is the key dimension. The softmax term defines which elements are mixed.

The score is a batched dot-product similarity between query and key vectors.

For an input sequence , self-attention first projects tokens into queries, keys, and values:

The attention logits and weights are:

Here is an optional mask. In causal attention, future positions receive before softmax so each token only attends to previous tokens.

Additive attention bias is another common way to inject structure:

The bias can encode relative position, graph relation, distance bucket, or a fixed linear distance prior. ALiBi is the canonical linear-bias paper note in this wiki.

Some architectures do more than add a bias. DeBERTa decomposes attention scores into content-content and content-position terms, which is useful when position should not be collapsed into the same embedding vector as token identity.

Shape Contract

For batched multi-head attention:

The attention weights have shape:

and the output is:

The softmax axis is the key axis . This means each query distribution sums to one over candidate keys:

Multi-head attention repeats this with separate projections:

Key-Value Head Sharing

Modern decoder-only models often keep many query heads but use fewer key/value heads to reduce KV-cache cost during autoregressive decoding. The canonical paper note here is GQA.

Let be query heads and be key/value heads:

VariantHead ContractMain Effect
MHAeach query head has its own key/value head
MQAall query heads share one key/value head
GQAgroups of query heads share key/value heads

The attention formula is still dot-product attention, but the tensor shape changes:

This is an architecture decision because it changes the KV cache:

Mask Semantics

The mask changes the allowed information flow:

MaskAllowsTypical Use
noneevery query attends to every keybidirectional encoder
causalonly current and previous positionsautoregressive decoder
paddingignores padded keysvariable-length batches
local/windowattends only nearby positionslong sequence efficiency; see Longformer
block/sparseattends selected blocks or patternsscalable long context; see BigBird
hash bucketattends to tokens sharing approximate similarity bucketsefficient approximate attention; see Reformer
low-rank projectioncompresses keys and values along the sequence axislinear attention through compression; see Linformer
disentangled content-positionscores content and relative position with separate termsposition-aware encoder attention; see DeBERTa
graph/structureattends only permitted neighbors or relationsgraph and structure models

Masking is part of the task contract. A model with future-token access is not solving the same autoregressive task as a causal model.

Local attention can also be used as one part of a hybrid recurrent backbone. Griffin mixes gated linear recurrence with local attention:

This gives nearby tokens explicit softmax interaction while recurrent state carries compressed context.

Compute and Memory

Dense attention forms a score matrix. For self-attention with :

and the dominant attention score cost is:

This is why long-context models use sparse attention, chunking, recurrence, state-space models, retrieval, or KV caching.

Sparse attention changes which entries of the attention graph are computed. For a window size , a local attention pattern has the rough cost:

which is linear in if is fixed. Longformer is the canonical local-plus-global sparse attention paper note, while BigBird is the canonical local-plus-global-plus-random sparse attention paper note.

Hash-based attention chooses candidates by approximate similarity rather than fixed position:

Reformer is the canonical LSH attention note here.

Low-rank attention compresses the sequence axis before attention:

Then the score matrix changes from to :

Linformer is the canonical low-rank attention paper note here.

Kernel linear attention avoids the matrix by rewriting attention through feature maps:

Performer is the canonical random-feature approximation note. Gated Linear Attention is the canonical hardware-aware gated linear attention note; it reads linear attention as a parallel training form and a recurrent inference form:

DeltaNet is the canonical delta-rule linear Transformer note. It changes the recurrent memory update from simple additive writing toward error-correcting memory updates:

Gated and Moving-Average Attention

Some attention variants keep content-dependent mixing but add a local sequential bias before or inside the attention block. Mega is the canonical paper note here.

An exponential moving average gives each token a decayed local memory:

Mega combines this moving-average path with gated attention:

This differs from a pure attention bias. A bias changes attention scores, while EMA adds a stateful local sequence operator.

Attention and State-Space Duality

Some modern sequence papers compare attention and state-space models through the matrix they apply over sequence positions:

In attention, is usually a content-dependent token-token matrix. In SSMs, can arise from expanding a recurrent state update across the whole prefix. Mamba-2 is the canonical note here for structured state space duality, which relates SSMs and attention-like mixers through structured semiseparable matrices.

This does not mean every Transformer is literally the same as every SSM. It means the right comparison often starts with:

Vision Attention Papers

PaperWhy It Matters
Vision Transformerapplies Transformer self-attention to image patches
Swin Transformeruses shifted local windows and hierarchy for vision attention
CoAtNetstages convolution and relative attention to balance bias and capacity

Attention Is Not Explanation

Attention weights show how values are mixed in a particular layer and head:

They do not by themselves prove causal importance. Value vectors, later layers, residual paths, normalization, and MLP blocks can all change the final behavior.

Key Ideas

  • Queries ask what information is needed; keys decide what can be matched; values carry the mixed information.
  • Self-attention mixes elements within one set, such as tokens in a sequence or nodes in a graph.
  • Cross-attention mixes information across two sets, such as encoded inputs and generated outputs.
  • Attention weights are useful debugging signals, but they are not always faithful explanations.
  • Positional or structural encodings matter because plain attention is permutation-aware but not order-aware by itself.
  • Attention biases are part of the architecture contract: a causal mask, relative position bias, ALiBi bias, graph mask, or structure mask changes which interactions are easy or possible.

Practical Checks

  • Check whether attention is full, causal, local, sparse, or cross-modal.
  • Track tensor shapes: batch, heads, query length, key length, and head dimension.
  • Watch memory cost when sequence length, graph size, or pair count grows.
  • For papers, identify what is being attended over: tokens, residues, atoms, edges, retrieved chunks, or tools.
  • Check which axis softmax normalizes over.
  • Confirm whether masks are additive, multiplicative, causal, padding, graph, or learned.
  • Separate attention weights from causal explanation.