Self-Attention
Self-Attention
A mechanism that computes relationships among all elements in a sequence. The core of Transformers. Captures context with Query, Key, and Value.
Self-Attention
A mechanism that computes relationships among all elements in a sequence. The core of Transformers. Captures context with Query, Key, and Value.
Self-Attention is a mechanism in which each element of a sequence computes its relationship to every other element in the same sequence. To work out that "it" refers to "cat" in "The cat sat on the mat because it was tired", you have to look at the relationships among all the words in the sentence. Self-Attention does exactly that.
It was proposed together with the Transformer in the 2017 paper "Attention Is All You Need". Earlier RNNs had to process sequences step by step, which made parallelization difficult and long-range dependencies hard to learn. Self-Attention computes all positions at once, so it can be parallelized and captures relationships regardless of distance.
The key is the Query (Q), Key (K), and Value (V) transformations. Multiplying the input X by weight matrices produces Q, K, and V, and attention is computed as Attention(Q,K,V) = softmax(QK^T / sqrt(d_k)) * V. When the dot product of Q and K is high, the relevance is high, so the corresponding V receives more weight.
It underlies all LLMs such as GPT, BERT, and T5, and it is also applied to images through the Vision Transformer (ViT). Multi-Head Attention runs several Self-Attention operations in parallel to learn diverse relationship patterns. Its O(N^2) complexity in sequence length N is a drawback, so optimization techniques such as Sparse Attention and Flash Attention are being researched.
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class SelfAttention(nn.Module):
"""Scaled Dot-Product Self-Attention"""
def __init__(self, embed_dim, num_heads=1):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
# Query, Key, Value ๋ณํ ํ๋ ฌ
self.W_q = nn.Linear(embed_dim, embed_dim)
self.W_k = nn.Linear(embed_dim, embed_dim)
self.W_v = nn.Linear(embed_dim, embed_dim)
self.W_o = nn.Linear(embed_dim, embed_dim)
def forward(self, x, mask=None):
batch_size, seq_len, _ = x.shape
# Q, K, V ๊ณ์ฐ
Q = self.W_q(x) # (batch, seq, embed)
K = self.W_k(x)
V = self.W_v(x)
# Attention Score: QK^T / sqrt(d_k)
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.head_dim)
# scores: (batch, seq, seq)
# ๋ง์คํน (์ต์
: causal mask for decoder)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
# Softmax๋ก ํ๋ฅ ๋ณํ
attention_weights = F.softmax(scores, dim=-1)
# Value์ ๊ฐ์ค์น ์ ์ฉ
output = torch.matmul(attention_weights, V)
output = self.W_o(output)
return output, attention_weights
# ์ฌ์ฉ ์์
embed_dim = 512
seq_len = 10
batch_size = 2
x = torch.randn(batch_size, seq_len, embed_dim)
attention = SelfAttention(embed_dim)
output, weights = attention(x)
print(f"์
๋ ฅ: {x.shape}") # (2, 10, 512)
print(f"์ถ๋ ฅ: {output.shape}") # (2, 10, 512)
print(f"์ดํ
์
๊ฐ์ค์น: {weights.shape}") # (2, 10, 10)
# Causal Mask (Decoder์ฉ - ๋ฏธ๋ ํ ํฐ ์ฐจ๋จ)
causal_mask = torch.tril(torch.ones(seq_len, seq_len))
print(f"Causal Mask:\n{causal_mask}")
# 1 0 0 0 ...
# 1 1 0 0 ...
# 1 1 1 0 ...
output_masked, _ = attention(x, mask=causal_mask)
# === Multi-Head Attention ๊ตฌํ ===
class MultiHeadAttention(nn.Module):
"""Multi-Head Self-Attention (์ฌ๋ฌ ํค๋ ๋ณ๋ ฌ ์ฒ๋ฆฌ)"""
def __init__(self, embed_dim, num_heads):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == embed_dim
self.W_q = nn.Linear(embed_dim, embed_dim)
self.W_k = nn.Linear(embed_dim, embed_dim)
self.W_v = nn.Linear(embed_dim, embed_dim)
self.W_o = nn.Linear(embed_dim, embed_dim)
def forward(self, x, mask=None):
batch_size, seq_len, _ = x.shape
# Q, K, V ๊ณ์ฐ ํ ํค๋๋ณ๋ก ๋ถ๋ฆฌ
Q = self.W_q(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
K = self.W_k(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
V = self.W_v(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
# (batch, heads, seq, head_dim)
# ๊ฐ ํค๋์์ ๋
๋ฆฝ์ ์ผ๋ก 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'))
weights = F.softmax(scores, dim=-1)
output = torch.matmul(weights, V)
# ํค๋ ๊ฒฐํฉ
output = output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.embed_dim)
return self.W_o(output)
# === PyTorch ๋ด์ฅ ์ฌ์ฉ (๊ถ์ฅ) ===
mha = nn.MultiheadAttention(embed_dim=512, num_heads=8, batch_first=True)
output, attn_weights = mha(x, x, x) # Self-Attention: Q=K=V
# === Flash Attention (๋ฉ๋ชจ๋ฆฌ ํจ์จ) ===
# pip install flash-attn
from flash_attn import flash_attn_func
# Flash Attention์ O(N) ๋ฉ๋ชจ๋ฆฌ๋ก O(N^2) ์ฐ์ฐ์ ์ํ
# 128K ์ปจํ
์คํธ๋ ๊ฐ๋ฅํ๊ฒ ๋ง๋ ํต์ฌ ๊ธฐ์
# === Attention ๊ฐ์ค์น ์๊ฐํ ===
import matplotlib.pyplot as plt
import seaborn as sns
def visualize_attention(attention_weights, tokens):
"""์ดํ
์
ํํธ๋งต ์๊ฐํ"""
plt.figure(figsize=(10, 10))
sns.heatmap(
attention_weights.detach().numpy(),
xticklabels=tokens,
yticklabels=tokens,
cmap='viridis'
)
plt.title("Self-Attention Weights")
plt.show()
# === Cross-Attention vs Self-Attention ===
# Self-Attention: Q, K, V ๋ชจ๋ ๊ฐ์ ์
๋ ฅ์์ ์ ๋
# Cross-Attention: Q๋ ํ ์
๋ ฅ, K/V๋ ๋ค๋ฅธ ์
๋ ฅ์์
# ์: Encoder-Decoder์์ Decoder๊ฐ Encoder ์ถ๋ ฅ ์ฐธ์กฐ
class CrossAttention(nn.Module):
def __init__(self, embed_dim):
super().__init__()
self.W_q = nn.Linear(embed_dim, embed_dim)
self.W_k = nn.Linear(embed_dim, embed_dim)
self.W_v = nn.Linear(embed_dim, embed_dim)
def forward(self, query_input, key_value_input):
Q = self.W_q(query_input) # Decoder ์ํ
K = self.W_k(key_value_input) # Encoder ์ถ๋ ฅ
V = self.W_v(key_value_input) # Encoder ์ถ๋ ฅ
# ์ดํ ๋์ผํ attention ๊ณ์ฐ
"Each Transformer layer contains Multi-Head Self-Attention, and with 8 heads it learns 8 different relationship patterns in parallel. Some heads learn syntactic relations, and others learn coreference."
"Self-Attention consists of three transformations: Q, K, and V. It computes relevance scores from the dot product of Q and K, normalizes them with softmax, and then applies a weighted sum over V. Dividing by sqrt(d_k) prevents the dot-product values from growing large and making the softmax extreme."
"Self-Attention is O(N^2), so memory blows up with long contexts. With Flash Attention you cut memory by 90% and also get a 2-3x speedup. It's essential for 128K-context models."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
If you do not divide by sqrt(d_k), the dot-product values become very large when d_k is large, and the softmax becomes nearly one-hot. Gradients vanish and training fails.
When training a language model, if it can see future tokens it learns the answer in advance. Always block the future with a lower-triangular matrix mask.
If you use PyTorch's nn.MultiheadAttention, scaling and masking are handled automatically. When writing a custom implementation, always check / sqrt(d_k) and the attn_mask parameter.