🤖 AI/ML

Multi-Head Attention

Multi-Head Attention

Learns diverse relationships by using multiple attention heads in parallel. A component of the Transformer.

📖 Detailed Explanation

Multi-Head Attention is a mechanism that performs multiple attention operations in parallel to simultaneously learn different representation subspaces of the input sequence. Unlike single attention, which captures relationships from only one perspective, Multi-Head Attention simultaneously captures diverse patterns such as syntax, semantics, and positional relationships.

It was proposed together with the Transformer architecture in the 2017 paper "Attention Is All You Need". It overcame the sequential processing limitations of the earlier RNN/LSTM and presented an attention-based structure that can be fully parallelized. The original paper used 8 heads, and it has since become a core component of all major language models, including GPT and BERT.

The working principle of Multi-Head Attention is as follows. After the input is transformed into Query (Q), Key (K), and Value (V), each head projects it with a different weight matrix. Each head performs Scaled Dot-Product Attention, and the outputs of all heads are concatenated, after which a final linear transformation is applied. The formula is MultiHead(Q,K,V) = Concat(head_1,...,head_h)W^O.

In 2024-2025, efficient attention variants are being actively researched. Flash Attention 2 maximizes GPU memory efficiency, and GQA (Grouped Query Attention) reduces the KV cache. Llama 2/3, Mistral, and others have adopted GQA to save memory in long contexts. MHA is still central to model quality, but optimizing inference cost is a major challenge.

💻 Code Example

# 멀티헤드 어텐션 구현 (PyTorch)
import torch
import torch.nn as nn
import torch.nn.functional as F
import math

class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, num_heads, dropout=0.1):
        super().__init__()
        assert d_model % num_heads == 0

        self.d_model = d_model
        self.num_heads = num_heads
        self.d_k = d_model // num_heads  # 헤드당 차원

        # Q, K, V 투영 가중치
        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 scaled_dot_product_attention(self, Q, K, V, mask=None):
        """Scaled Dot-Product Attention"""
        # Q @ K^T / sqrt(d_k)
        scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)

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

        attention_weights = F.softmax(scores, dim=-1)
        attention_weights = self.dropout(attention_weights)

        return torch.matmul(attention_weights, V), attention_weights

    def forward(self, query, key, value, mask=None):
        batch_size = query.size(0)

        # 1. 선형 투영 후 헤드 분할
        Q = self.W_q(query).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        K = self.W_k(key).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        V = self.W_v(value).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)

        # 2. 어텐션 계산
        attn_output, attn_weights = self.scaled_dot_product_attention(Q, K, V, mask)

        # 3. 헤드 연결 및 출력 투영
        attn_output = attn_output.transpose(1, 2).contiguous().view(
            batch_size, -1, self.d_model
        )
        output = self.W_o(attn_output)

        return output, attn_weights

# 사용 예시
mha = MultiHeadAttention(d_model=512, num_heads=8)
x = torch.randn(2, 10, 512)  # (batch, seq_len, d_model)
output, weights = mha(x, x, x)
print(f"출력 shape: {output.shape}")      # [2, 10, 512]
print(f"어텐션 shape: {weights.shape}")   # [2, 8, 10, 10]

🗣️ Say It Like This in Practice

💬 In a Meeting
"The slow model inference is because of KV cache memory. If you switch from MHA to GQA, you can keep the number of heads while reducing the KV cache to 1/8. Llama 3 uses this approach too."
💬 In an Interview
"The core of Multi-Head Attention is learning diverse representation subspaces. With 8 heads, the 512 dimensions are split into eight 64-dimension parts, and each learns a different relationship. Dividing by 'sqrt(d_k)' is to prevent softmax vanishing gradients."
💬 In a Technical Discussion
"If you apply Flash Attention 2, even the same MHA goes from O(N^2) to O(N) in memory. It's essential when training on long contexts. Since PyTorch 2.0, scaled_dot_product_attention automatically uses Flash Attention."

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

⚠️ Common Mistakes & Cautions

❌
d_model is not divisible by num_heads

With d_model=512 and num_heads=12, an error occurs. d_k = d_model // num_heads must be an integer. For 512, use values such as 8, 16, or 32.

❌
Attention mask direction error

If you confuse the causal mask (masking future tokens) with the padding mask, training will not work properly. The decoder uses an upper-triangular mask, and padding uses a True/False mask.

✅
The right way

We recommend using PyTorch's nn.MultiheadAttention or F.scaled_dot_product_attention. They automatically apply Flash Attention, and mask handling is also verified.

🔗 Related Terms

📚 Learn More