Editing
Attention Mechanisms
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
<div style="background-color: #4B0082; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;"> {{BloomIntro}} Attention mechanisms are the computational building blocks that allow neural networks to dynamically focus on the most relevant parts of their input when producing each output. Introduced in the context of machine translation to help encoder-decoder RNNs align source and target words, attention was then generalized into the self-attention mechanism at the core of the Transformer architecture β the technology underlying GPT, BERT, DALL-E, AlphaFold, and virtually every frontier AI system. Understanding attention is understanding the engine of modern AI. </div> __TOC__ <div style="background-color: #000080; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;"> == <span style="color: #FFFFFF;">Remembering</span> == * '''Attention''' β A mechanism that computes a weighted combination of input elements, where weights represent how relevant each element is to the current computation. * '''Self-attention''' β Attention applied to a single sequence where each element attends to all other elements of the same sequence. * '''Cross-attention''' β Attention where queries come from one sequence and keys/values from another; used in encoder-decoder models. * '''Query (Q)''' β A vector representing "what I am looking for" at the current position. * '''Key (K)''' β A vector representing "what I offer" for each position in the sequence. * '''Value (V)''' β A vector representing "what I give if selected" for each position. * '''Attention weight''' β The scalar importance assigned to each key-value pair given the query; computed via softmax of scaled dot products. * '''Attention head''' β One parallel attention operation; multi-head attention runs H heads simultaneously. * '''Multi-head attention''' β Running H attention operations in parallel with different projections, then concatenating outputs. * '''Scaled dot-product attention''' β The standard attention formula: Attention(Q,K,V) = softmax(QKα΅/βd_k)V. * '''Causal (masked) attention''' β Self-attention where each position can only attend to positions before it; used in autoregressive decoders. * '''Positional encoding''' β Information added to embeddings indicating each token's position, since attention is permutation-invariant. * '''Attention sink''' β The empirical phenomenon where early tokens attract disproportionate attention mass in LLMs. * '''Flash Attention''' β A memory-efficient, hardware-optimized implementation of exact attention using tiling and recomputation. * '''Sparse attention''' β Attention variants that restrict which positions can attend to which, reducing O(nΒ²) complexity. </div> <div style="background-color: #006400; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;"> == <span style="color: #FFFFFF;">Understanding</span> == Standard neural networks apply fixed weights regardless of input context. Attention is dynamic β the weights change with every input. This is its power: the network can decide, for each output token, which parts of the input are most relevant. '''The intuition''': imagine reading a sentence and being asked "Who did John see?" Your brain attends to "John" and the verb "see" and its object β not to articles and prepositions. Attention gives neural networks this selective focus ability. '''The math''': For a query q and a set of key-value pairs (k''i, v''i): - Compute compatibility score: s''i = q Β· k''i / βd_k - Normalize: Ξ±''i = softmax(s''i) - Output: o = Ξ£ Ξ±''i v''i The output is a weighted sum of values, where the weights reflect how compatible each key is with the query. Scaling by βd_k prevents dot products from growing too large, which would push softmax into saturation. '''Multi-head attention''' allows different heads to capture different types of relationships simultaneously β one head might track syntactic dependencies, another semantic similarity, another coreference. The outputs are concatenated and linearly projected. '''The O(nΒ²) problem''': Full self-attention computes all pairwise attention scores, requiring O(nΒ²) memory and compute in sequence length n. For a 100k-token context, this is 10^10 scores β impractical. Solutions: Flash Attention (IO-aware exact attention), sliding window attention (Longformer), linear attention approximations, and GQA (Grouped Query Attention) for inference efficiency. </div> <div style="background-color: #8B0000; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;"> == <span style="color: #FFFFFF;">Applying</span> == '''Implementing scaled dot-product attention from scratch:''' <syntaxhighlight lang="python"> import torch import torch.nn as nn import torch.nn.functional as F import math class MultiHeadAttention(nn.Module): def __init__(self, d_model=512, n_heads=8, dropout=0.1): super().__init__() assert d_model % n_heads == 0 self.d_k = d_model // n_heads self.n_heads = n_heads self.W_q = nn.Linear(d_model, d_model) self.W_k = nn.Linear(d_model, d_model) self.W_v = nn.Linear(d_model, d_model) self.W_o = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout) def split_heads(self, x): B, T, D = x.shape return x.view(B, T, self.n_heads, self.d_k).transpose(1, 2) # (B, H, T, d_k) def forward(self, query, key, value, mask=None): B, T, _ = query.shape Q = self.split_heads(self.W_q(query)) K = self.split_heads(self.W_k(key)) V = self.split_heads(self.W_v(value)) # Scaled dot-product attention scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k) if mask is not None: scores = scores.masked_fill(mask == 0, float('-inf')) attn = self.dropout(F.softmax(scores, dim=-1)) out = torch.matmul(attn, V) # (B, H, T, d_k) out = out.transpose(1, 2).contiguous().view(B, T, -1) return self.W_o(out), attn </syntaxhighlight> ; Attention variant selection guide : '''Standard self-attention''' β Transformers, BERT, GPT (seq len β€ 4096) : '''Flash Attention 2''' β Any modern transformer; same output, 2-4Γ faster, O(n) memory : '''Grouped Query Attention (GQA)''' β LLaMA 2/3, Mistral β reduces KV cache in inference : '''Sliding window attention''' β Longformer, Mistral β O(nΒ·w) complexity for long docs : '''Cross-attention''' β Encoder-decoder models (T5, Whisper, LLaVA projection) : '''Linear attention''' β Mamba alternative, sub-quadratic, trades quality for speed </div> <div style="background-color: #8B4500; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;"> == <span style="color: #FFFFFF;">Analyzing</span> == {| class="wikitable" |+ Attention Complexity Comparison ! Variant !! Time Complexity !! Memory !! Quality vs. Full Attention |- | Full attention || O(nΒ²) || O(nΒ²) || Reference |- | Flash Attention || O(nΒ²) compute || O(n) memory || Identical (exact) |- | GQA (G groups) || O(nΒ²) || O(nΒ²/G) KV || Near-identical |- | Sliding window (w) || O(nΒ·w) || O(nΒ·w) || Degrades for long-range deps |- | Linear attention || O(n) || O(n) || Significant quality loss |} '''Failure modes''': Attention sinks β first token receives excess attention mass, distorting representations. Position generalization failure β models trained with absolute PE fail on sequences longer than training. Quadratic blowup β naive attention on 100k tokens requires TB of memory. Uniform attention distribution in early training destabilizes gradients. </div> <div style="background-color: #483D8B; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;"> == <span style="color: #FFFFFF;">Evaluating</span> == '''Attention visualization''' (BertViz, TransformerLens) reveals what each head attends to β essential for understanding model behavior. Expert practitioners perform '''attention head ablation''': zero out individual heads and measure performance impact, identifying which heads are critical. '''Context utilization benchmarks''' (RULER, NIAH β Needle in a Haystack) test whether long-context models actually use information at all positions. Many models with 128k context fail to retrieve information from the middle. </div> <div style="background-color: #2F4F4F; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;"> == <span style="color: #FFFFFF;">Creating</span> == Designing attention for a specific long-context use case: # Use Flash Attention 2 as the default β same quality, O(n) memory. # For inference serving, switch to GQA (group K/V heads) to reduce KV cache size by 4-8Γ. # For documents >32k tokens, implement sliding window attention for local context + full attention every N layers for global context (like Mistral). # Use RoPE (Rotary Position Embeddings) for better length generalization. # Monitor KV cache size as the dominant memory cost at inference scale. [[Category:Artificial Intelligence]] [[Category:Deep Learning]] [[Category:Transformer Architecture]] </div>
Summary:
Please note that all contributions to BloomWiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
BloomWiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Template used on this page:
Template:BloomIntro
(
edit
)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information