From Self-Attention to GQA
PremiumStarting from Self-Attention, unpack the design trade-offs of Multi-Head, Causal Masking, and GQA / MQA in turn
Starting from Self-Attention, unpack the design trade-offs of Multi-Head, Causal Masking, and GQA / MQA in turn
Attention is one of the most important innovations in modern deep learning. It allows a model to dynamically focus on information at different positions when processing sequence data.
In the Transformer architecture, the core idea of attention is: let each position's token perform a weighted sum over all other tokens according to its relevance to them.
Given an input sequence, Self-Attention computes its output through the following steps:
Linear projection: project the input into Query (), Key (), and Value ()
This is premium content. Please log in to access the full article.
Compute attention scores: compute similarity through the dot product of Query and Key
Apply Softmax: convert scores into a probability distribution
Weighted sum: weight the Value with the attention weights
Intuition:
import torch
import torch.nn.functional as F
def self_attention(X, W_q, W_k, W_v):
"""
X: (batch, seq_len, d_model)
W_q, W_k, W_v: (d_model, d_head)
"""
Q = X @ W_q
where is the head dimension, and dividing by is for numerical stability (scaled dot-product)