| name | attention-mecanismes |
| description | Guide complet des mécanismes d'attention — softmax, scalaire, croisée, flash, sparse, linéaire, FFT, multi-tâches, state-space. En français. |
Mécanismes d'Attention — Guide Complet
Tous les mécanismes d'attention : des fondamentaux aux avancées 2024-2025.
1. Fondements Mathématiques
Scaled Dot-Product Attention
Attention(Q, K, V) = softmax(QKᵀ / √d_k) V
Q ∈ ℝ^(n×d_k) : Queries
K ∈ ℝ^(m×d_k) : Keys
V ∈ ℝ^(m×d_v) : Values
d_k : dimension des clés
def scaled_dot_product_attention(Q, K, V, mask=None):
"""Attention scalaire avec produit matriciel.
Args:
Q: (batch, heads, seq_q, d_k)
K: (batch, heads, seq_k, d_k)
V: (batch, heads, seq_k, d_v)
mask: (batch, 1, seq_q, seq_k) — booléen ou float(-inf)
"""
d_k = Q.size(-1)
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
attn_weights = F.softmax(scores, dim=-1)
output = torch.matmul(attn_weights, V)
return output, attn_weights
Pourquoi /√d_k ?
2. Taxonomie Complète
Attention
/ | \
Self-attention | Cross-attention
/ \ \
Causal Bidirectional Enc-Dec
|
+----+----+-------+--------+
| | | | |
Softmax Linear Sparse Flash Fourier
| (Linformer, (Longformer, (Dao 2022)
| Performer) BigBird)
|
Multi-Head (MHA)
Grouped-Query (GQA)
Multi-Query (MQA)
3. Self-Attention (Intra-séquence)
Bidirectionnelle (BERT)
Causale (GPT, LLaMA)
def causal_mask(seq_len, device='cpu'):
return torch.triu(
torch.full((seq_len, seq_len), float('-inf'), device=device),
diagonal=1,
)
Prefix Mask (T5, ULM)
4. Cross-Attention (Inter-séquences)
Encoder-Decoder (T5, BART, Transformer original)
class CrossAttention(nn.Module):
"""Q vient du decoder, K,V viennent de l'encoder."""
def __init__(self, d_model, n_heads):
super().__init__()
self.q_proj = nn.Linear(d_model, d_model)
self.k_proj = nn.Linear(d_model, d_model)
self.v_proj = nn.Linear(d_model, d_model)
self.out_proj = nn.Linear(d_model, d_model)
def forward(self, decoder_hidden, encoder_output, mask=None):
Q = self.q_proj(decoder_hidden)
K = self.k_proj(encoder_output)
V = self.v_proj(encoder_output)
Cross-attention multimodale (LLaVA, Flamingo)
5. FlashAttention (Dao et al., 2022-2023-2024)
FlashAttention v1 (NeurIPS 2022)
FlashAttention v2 (2023)
FlashAttention v3 (2024, Hopper/H100)
import torch
from flash_attn import flash_attn_func
out, lse, _ = flash_attn_func(
q, k, v,
dropout_p=0.0,
softmax_scale=None,
causal=False,
window_size=(-1, -1),
alibi=False,
deterministic=False,
)
from flash_attn import flash_attn_varlen_func
FlashAttention Triton
import triton
import triton.language as tl
@triton.jit
def flash_attention_kernel(Q, K, V, O, ...):
6. Attention Linéaire / Subquadratique
Linformer (2020)
Performer (FAVOR+, 2020)
def favor_plus(Q, K, V, num_features=256):
"""Attention approximée par features aléatoires."""
Q_prime = feature_map(Q, num_features)
K_prime = feature_map(K, num_features)
return (Q_prime @ (K_prime.transpose(-2, -1) @ V)) / n
RWKV (2023) — Attention linéaire récurrente
7. Attention Sparse et Structurée
Longformer (2020)
BigBird (2020)
ETC / LongT5 (2021)
Sparse Attention (OpenAI, 2019)
8. Attention Croisée Avancée
Cross-attention dans les systèmes multimodaux
class GatedCrossAttention(nn.Module):
"""Cross-attention avec gate apprise (Flamingo)."""
def __init__(self, d_model, n_heads):
self.attn = MultiHeadAttention(d_model, n_heads)
self.gate = nn.Parameter(torch.zeros(1, 1, d_model))
def forward(self, lang_hidden, vision_hidden):
x = self.attn(lang_hidden, vision_hidden, vision_hidden)
return lang_hidden + torch.tanh(self.gate) * x
Cross-attention pour RAG
9. Attention Multi-Résolution
Axial Attention (Google, 2019)
Perceiver (DeepMind, 2021)
class PerceiverBlock(nn.Module):
def __init__(self, d_latent, n_latents=256):
self.cross_attn = CrossAttention(d_latent, n_heads=8)
self.self_attn = MultiHeadAttention(d_latent, n_heads=8)
def forward(self, latent, data):
latent = self.cross_attn(latent, data, data)
latent = self.self_attn(latent, latent, latent)
return latent
10. Mécanismes d'Attention Récente (2024-2025)
Differential Attention (DIFF Transformer, 2024)
MLA — Multi-head Latent Attention (DeepSeek-V2/V3)
class MultiHeadLatentAttention(nn.Module):
"""Attention avec KV latent compressé."""
def __init__(self, d_model, n_heads, d_latent=512):
self.W_kv_down = nn.Linear(d_model, d_latent)
self.W_q_down = nn.Linear(d_model, d_latent)
self.W_k_up = nn.Linear(d_latent, d_model)
self.W_v_up = nn.Linear(d_latent, d_model)
Lizard Attention
Contrastive Attention
11. Attention Caching et Optimisation
class StreamingKVCache:
"""Cache KV avec gestion mémoire optimisée."""
def __init__(self, max_batch_size, max_seq_len, n_layers,
n_kv_heads, head_dim, dtype=torch.float16):
shape = (max_batch_size, max_seq_len, n_kv_heads, head_dim)
self.k_cache = [torch.zeros(shape, dtype=dtype) for _ in range(n_layers)]
self.v_cache = [torch.zeros(shape, dtype=dtype) for _ in range(n_layers)]
self.valid_positions = 0
def update(self, layer_id, k, v):
B, T, H, D = k.shape
assert T == 1
self.k_cache[layer_id][:, self.valid_positions] = k.squeeze(1)
self.v_cache[layer_id][:, self.valid_positions] = v.squeeze(1)
self.valid_positions += 1
return (self.k_cache[layer_id][:, :self.valid_positions],
self.v_cache[layer_id][:, :self.valid_positions])
12. Tableau Comparatif
| Mécanisme | Complexité | Mémoire | Qualité | Année |
|---|
| MHA (full) | O(n²) | O(n²) | ★★★★★ | 2017 |
| FlashAttn v1 | O(n²) | O(n) | ★★★★★ | 2022 |
| FlashAttn v2 | O(n²) | O(n) | ★★★★★ | 2023 |
| Linformer | O(nk) | O(nk) | ★★★☆☆ | 2020 |
| Performer | O(n) | O(n) | ★★★☆☆ | 2020 |
| Longformer | O(nw) | O(nw) | ★★★★☆ | 2020 |
| RWKV | O(n) | O(n) | ★★★★☆ | 2023 |
| MLA (DeepSeek) | O(n²) | O(n) | ★★★★★ | 2024 |
| Differential | O(n²) | O(n²) | ★★★★★ | 2024 |
Références