🤖 AI/ML

Self-Attention

Self-Attention

A mechanism in which each element in a sequence computes its relationship to all other elements. The core of the Transformer.

📖 Detailed Explanation

Self-Attention is a mechanism in which each element in a sequence simultaneously computes its relationship with all other elements of the same sequence. As a core component of the Transformer architecture introduced in the 2017 paper "Attention Is All You Need", it overcame the limitations of RNN's sequential processing and made parallel processing possible.

Self-Attention uses three vectors: Query, Key, and Value. Each token of the input sequence is transformed into these three vectors. The attention score is computed as the dot product of Query and Key, softmax is applied, and then a weighted sum with Value produces the output. Through this process, the model learns "which token should pay how much attention to which token."

Expressed as a formula, it is Attention(Q,K,V) = softmax(QK^T / sqrt(d_k)) * V. Scaled dot-product attention, which divides by sqrt(d_k), prevents the problem of dot-product values growing larger as the dimension increases. In practice, Multi-Head Attention, which uses multiple attention heads in parallel, is applied to learn relationships from various perspectives.

The advantage of Self-Attention is that it effectively models long-range dependencies. In RNNs, information from distant tokens becomes diluted, whereas Self-Attention directly connects all token pairs. The disadvantage is the O(n^2) computational complexity, which is proportional to the square of the sequence length. To address this, efficient variants such as Linformer, Performer, and FlashAttention have been developed.

Code Example

This is a Scaled Dot-Product Self-Attention implemented in PyTorch.

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

class SelfAttention(nn.Module):
    def __init__(self, embed_dim, num_heads=8):
        super().__init__()
        self.embed_dim = embed_dim
        self.num_heads = num_heads
        self.head_dim = embed_dim // num_heads

        assert embed_dim % num_heads == 0, "embed_dim must be divisible by num_heads"

        # Q, K, V 프로젝션
        self.q_proj = nn.Linear(embed_dim, embed_dim)
        self.k_proj = nn.Linear(embed_dim, embed_dim)
        self.v_proj = nn.Linear(embed_dim, embed_dim)
        self.out_proj = nn.Linear(embed_dim, embed_dim)

    def forward(self, x, mask=None):
        batch_size, seq_len, _ = x.shape

        # Q, K, V 계산
        Q = self.q_proj(x)  # (B, S, D)
        K = self.k_proj(x)
        V = self.v_proj(x)

        # Multi-head 분리: (B, S, D) -> (B, H, S, D/H)
        Q = Q.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        K = K.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        V = V.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)

        # Scaled Dot-Product Attention
        scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.head_dim)

        if mask is not None:
            scores = scores.masked_fill(mask == 0, float('-inf'))

        attn_weights = F.softmax(scores, dim=-1)
        attn_output = torch.matmul(attn_weights, V)  # (B, H, S, D/H)

        # 헤드 결합
        attn_output = attn_output.transpose(1, 2).contiguous()
        attn_output = attn_output.view(batch_size, seq_len, self.embed_dim)

        return self.out_proj(attn_output), attn_weights

# 사용 예시
model = SelfAttention(embed_dim=512, num_heads=8)
x = torch.randn(2, 100, 512)  # (batch, seq_len, embed_dim)
output, weights = model(x)
print(f"Output shape: {output.shape}")  # (2, 100, 512)
print(f"Attention weights shape: {weights.shape}")  # (2, 8, 100, 100)

Performance & Cost

Attention Variants Computational Complexity Memory Complexity Features
Standard Self-Attention O(n^2 * d) O(n^2) Basic, accurate
FlashAttention O(n^2 * d) O(n) Memory-efficient, fast
Linformer O(n * k * d) O(n * k) K,V projection
Performer O(n * d^2) O(n * d) Random Features
Sparse Attention O(n * sqrt(n)) O(n * sqrt(n)) Pattern-based sparsification

* n: sequence length, d: embedding dimension, k: projection dimension

🗣️ Say It Like This in Practice

"We had memory issues from processing long sequences, so we switched to FlashAttention. It reduces the O(n^2) memory of self-attention to O(n)."

In English, you would say, "We switched to FlashAttention to reduce the O(n^2) memory footprint of self-attention." Terms such as "scaled dot-product attention", "multi-head attention", and "attention score/weight" are also frequently used. When visualizing, draw an "attention heatmap" to show where the model is focusing.

⚠️ Common Mistakes & Cautions

  • 1. Missing scaling: If you do not divide by sqrt(d_k), softmax outputs extreme values, causing gradient vanishing.
  • 2. Masking mistakes: If you confuse the padding mask with the causal mask (which blocks future tokens), training does not work properly.
  • 3. Memory explosion: The size of the attention matrix grows rapidly for long sequences. With 8K tokens, 64M attention computations are required.
  • 4. Too many heads: If head_dim becomes too small, the expressiveness of each head decreases. Keep at least 32 to 64 dimensions.
  • 5. Missing positional information: Self-Attention itself is permutation invariant. Be sure to add Positional Encoding.

🔗 Related Terms

📚 Learn More