Home Knowledge Base The Attention Mechanism

The Attention Mechanism is the core computational primitive of the Transformer architecture that enables each token in a sequence to dynamically gather information from all other tokens based on learned relevance scores — computing a weighted combination of value vectors where the weights are determined by the compatibility between query and key vectors, forming the foundation of virtually all modern language models, vision models, and multimodal AI systems.

Scaled Dot-Product Attention

Given input embeddings X, three linear projections produce:

Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V

The dot product Q*K^T computes pairwise compatibility scores. Division by sqrt(d_k) prevents the softmax from saturating into one-hot vectors for large dimension d_k. The softmax normalizes scores into a probability distribution. Multiplying by V produces a weighted sum of value vectors.

Multi-Head Attention

Instead of computing a single attention function, the model runs H parallel attention heads (typically 8-128), each with its own Q/K/V projections of dimension d_k = d_model/H. Each head can attend to different aspects of the input (syntactic relationships, semantic similarity, positional patterns). The head outputs are concatenated and linearly projected.

Causal (Autoregressive) Attention

For language generation, a causal mask prevents each token from attending to future positions — token i can only see tokens 1 through i. This is implemented by setting the upper-triangular entries of the attention matrix to -infinity before softmax.

KV Cache

During autoregressive generation, previously computed key and value vectors don't change as new tokens are generated. The KV cache stores all past K and V vectors, so each new token only computes its own Q and attends to the cached K/V. This reduces per-token computation from O(n²) to O(n) but requires memory that grows linearly with sequence length.

Efficiency Optimizations

The Attention Mechanism is the algorithm that taught neural networks to focus — replacing fixed-pattern information routing with dynamic, content-dependent communication that adapts to every input, enabling the unprecedented generality of modern AI.

attention mechanism transformerself attention multi headscaled dot product attentionkv cache attentionattention optimization flash

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.