🤖 AI/ML

Attention Mechanism

Attention Mechanism

A mechanism that assigns weights to the important parts of the input. Revolutionized by the paper "Attention Is All You Need."

📖 Detailed Explanation

Attention is a mechanism in deep learning that assigns different levels of importance (weights) to each part of an input sequence. Just as people do not pay equal attention to every word when reading a sentence, it allows a model to "focus" more on the parts that are highly relevant.

The core of attention consists of three elements: Query, Key, and Value. The Query represents "what is being looked for," the Key represents "what each input is," and the Value represents "the actual information of each input." Attention weights are created by calculating the similarity between the Query and the Key, and these are multiplied with the Value to obtain a weighted sum.

Self-Attention, proposed in the 2017 paper "Attention Is All You Need," learns the relationships between all positions within the same sequence. It overcame the limitations of sequential processing in RNNs and enabled parallel computation, becoming the core of the Transformer architecture.

Multi-Head Attention performs multiple attention operations in parallel to capture relationships from various perspectives. Cross-Attention learns the relationships between different sequences (e.g., encoder-decoder). All of the core capabilities of modern LLMs (context understanding, long document processing, relevant information extraction) are based on attention.

💻 Code Example

# Scaled Dot-Product Attention 구현
import torch
import torch.nn.functional as F
import math

def scaled_dot_product_attention(query, key, value, mask=None):
    """
    Scaled Dot-Product Attention 계산

    Args:
        query: [batch, heads, seq_len, d_k]
        key:   [batch, heads, seq_len, d_k]
        value: [batch, heads, seq_len, d_v]
        mask:  선택적 마스크 (패딩, 캐쥬얼 등)

    Returns:
        output: 어텐션 적용된 출력
        attention_weights: 시각화용 어텐션 가중치
    """
    d_k = query.size(-1)

    # 1. Query와 Key의 내적 → 유사도 점수
    scores = torch.matmul(query, key.transpose(-2, -1))

    # 2. 스케일링 (gradient 안정화)
    scores = scores / math.sqrt(d_k)

    # 3. 마스킹 (선택적)
    if mask is not None:
        scores = scores.masked_fill(mask == 0, float('-inf'))

    # 4. Softmax → 확률 분포 (어텐션 가중치)
    attention_weights = F.softmax(scores, dim=-1)

    # 5. Value와 가중 합
    output = torch.matmul(attention_weights, value)

    return output, attention_weights

# 예제: 문장 내 단어 간 어텐션
batch_size, seq_len, d_model = 1, 5, 64

# 가상의 Q, K, V (실제로는 학습된 선형 변환에서 생성)
query = torch.randn(batch_size, 1, seq_len, d_model)
key = torch.randn(batch_size, 1, seq_len, d_model)
value = torch.randn(batch_size, 1, seq_len, d_model)

output, attn_weights = scaled_dot_product_attention(query, key, value)

print(f"Input shape: [{batch_size}, 1, {seq_len}, {d_model}]")
print(f"Output shape: {output.shape}")
print(f"Attention weights shape: {attn_weights.shape}")
print(f"\n어텐션 가중치 (각 행의 합 = 1):")
print(attn_weights.squeeze().numpy().round(3))

🗣️ Examples of Practical Conversations

In an LLM performance analysis meeting

"I visualized the attention map, and the model is properly focusing on the key keywords of the question. However, attention tends to become dispersed as the context gets longer. For longer documents, it would be good to add retrieval augmentation."

During a model optimization discussion

"The O(n²) complexity of attention is the bottleneck. Switching to Flash Attention reduces memory to O(n) and makes it 2-4 times faster. If a long context is needed, Sliding Window Attention or Sparse Attention are also worth considering."

In a technical interview

"The difference between Self-Attention and Cross-Attention is the source of Q, K, and V. In Self-Attention, all of them are generated from the same sequence, while in Cross-Attention, Q comes from the decoder and K and V come from the encoder. Cross-Attention is used in translation models when source sentence information is utilized for target generation."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

📊 Comparison of Attention Types

Type Description Usage Examples
Self-Attention Learning relationships within the same sequence BERT, GPT encoding
Cross-Attention Relationships between different sequences Translation, image captioning
Multi-Head Performing attention from multiple perspectives in parallel Most Transformers
Causal/Masked Preventing reference to future tokens GPT generation, decoder
Flash Attention Memory-efficient implementation Large-scale LLM training/inference

💡 Practical tip: GPT-series models use Causal Self-Attention (referencing only previous tokens), BERT uses Bidirectional Self-Attention (both directions), and T5 uses Cross-Attention between the encoder and decoder.

⚠️ Cautions

1
O(n²) memory/time complexity

Standard attention requires resources proportional to the square of the sequence length. For long documents (tens of thousands of tokens), you must use efficient variants such as Flash Attention, Sparse Attention, or Longformer.

2
Attention != Explainability

A high attention weight does not mean you can conclude that the token is "important" to the result. Attention is only a hint of interpretability and does not guarantee causal relationships. Additional analysis is needed for XAI purposes.

3
KV Cache Memory

Caching Keys and Values during inference speeds things up, but memory surges with long contexts. The cache size can be reduced with GQA (Grouped Query Attention) or MQA (Multi-Query Attention).

🔗 Related Terms

📚 Learn More