🤖 AI/ML

Attention Mechanism

Attention Mechanism

A mechanism that assigns different weights to each part of the input. The core of the Transformer.

📖 Detailed Explanation

The Attention Mechanism is a technique that assigns different levels of importance (weights) to each part of an input sequence, so that a model "attends" to the most relevant information. Just as a person reading a long sentence does not pay equal attention to every word but focuses on the key words, AI also assigns more weight to the important parts.

Self-Attention, introduced in Google's 2017 paper "Attention Is All You Need," is the core of the Transformer architecture and computes the relationships between all positions in a sequence in parallel. Each Token is converted into Query (Q), Key (K), and Value (V) vectors; the similarity between Q and K is calculated to obtain attention scores, which are then applied to V to produce an output that reflects the context.

Multi-Head Attention performs multiple attention operations in parallel to capture relationships from various perspectives. For example, one head can learn grammatical relationships while another learns semantic similarity. GPT-4 uses dozens of attention heads to understand complex language patterns.

With the emergence of the attention mechanism, the sequential-processing limitations of RNN/LSTM were overcome, and it became possible to learn long-range dependencies effectively even in long sequences. Today, it is used as a core component in almost all modern language models such as GPT, BERT, and Claude, as well as in vision models such as Vision Transformer (ViT).

💻 Code Example

This is an example of Scaled Dot-Product Attention and Multi-Head Attention implemented in PyTorch.

import torch
import torch.nn as nn
import torch.nn.functional as F
import math

# Scaled Dot-Product Attention
def scaled_dot_product_attention(Q, K, V, mask=None):
    """
    Q, K, V: (batch, seq_len, d_k)
    """
    d_k = Q.size(-1)
    # Attention Score: Q와 K의 내적 후 스케일링
    scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)

    if mask is not None:
        scores = scores.masked_fill(mask == 0, -1e9)

    # Softmax로 가중치 정규화
    attention_weights = F.softmax(scores, dim=-1)

    # V에 가중치 적용
    output = torch.matmul(attention_weights, V)
    return output, attention_weights

# Multi-Head Attention 클래스
class MultiHeadAttention(nn.Module):
    def __init__(self, d_model=512, num_heads=8):
        super().__init__()
        self.num_heads = num_heads
        self.d_k = d_model // num_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)

    def forward(self, Q, K, V, mask=None):
        batch_size = Q.size(0)

        # Linear projection + reshape to heads
        Q = self.W_q(Q).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        K = self.W_k(K).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        V = self.W_v(V).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)

        # Attention 적용
        x, attn = scaled_dot_product_attention(Q, K, V, mask)

        # Concat heads + final linear
        x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.d_k)
        return self.W_o(x)

# 사용 예시
mha = MultiHeadAttention(d_model=512, num_heads=8)
x = torch.randn(2, 10, 512)  # (batch=2, seq_len=10, d_model=512)
output = mha(x, x, x)  # Self-Attention
print(f"Output shape: {output.shape}")  # (2, 10, 512)

📊 Comparison of Attention Variants

Attention Type Time Complexity Features Applicable Models
Full Attention O(n²) Computes relationships between all tokens BERT, GPT-3
Sparse Attention O(n√n) Computes only some patterns GPT-3 (partial)
Flash Attention O(n²) memory efficiency IO optimization, memory reduction LLaMA, Mistral
Linear Attention O(n) Uses kernel approximation Performer
Multi-Query Attention O(n²) KV reduction Shares K,V heads PaLM, Falcon

🗣️ Say It Like This in Practice

When Discussing Model Architecture

"To process 128K tokens, standard attention will run out of memory. We need to apply Flash Attention 2 or Sliding Window Attention."

When Debugging/Analyzing

"I visualized the attention map, and the model is ignoring the negation word 'not.' Let's revise the prompt."

In a Performance Optimization Meeting

"The reason inference is slow is the attention computation. Applying a KV cache and switching to Multi-Query Attention will make it 30% faster."

⚠️ Common Mistakes & Cautions

💾
Memory Explosion (OOM)

Attention uses O(n²) memory. For long sequences, apply Flash Attention or gradient checkpointing.

🔢
Missing Scaling

Without dividing by √d_k, the softmax converges to extreme values. Always use Scaled Dot-Product.

🎭
Masking Mistakes

If the Decoder sees future tokens, training breaks down. Be sure to apply a causal mask.

📊
Too Many Heads

With too many heads, each head's dimension (d_k) shrinks and expressiveness decreases. Keep d_model/num_heads at 64 or higher.

🔗 Related Terms

📚 Learn More