chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
# Differential Transformer V2 (DIFF V2)
|
||||
|
||||
[Read the blog post here](https://spiky-homegrown-4cb.notion.site/Differential-Transformer-V2-2e7baa052def80ecaa93d4d67d125417)
|
||||
|
||||
The implementation is provided in `multihead_flashdiffv2.py`.
|
||||
|
||||
## TL;DR
|
||||
|
||||
We introduce **Differential Transformer V2** (DIFF V2), an improved version of [Differential Transformer](https://arxiv.org/abs/2410.05258) (DIFF V1). This revision focuses on inference efficiency, training stability for production-level LLMs, and architectural elegance.
|
||||
|
||||
### Key Improvements
|
||||
|
||||
1. **Faster Inference & No Need of Custom Attention Kernels**
|
||||
Instead of forcing the attention parameter count to match the baseline Transformer (as in DIFF V1), we introduce additional parameters for $Q_2$. This design allows DIFF V2 to match the baseline Transformer’s decoding speed and directly use [FlashAttention](https://github.com/Dao-AILab/flash-attention) without custom kernels.
|
||||
|
||||
2. **Improved Training Stability**
|
||||
We remove the per-head RMSNorm after differential attention. We find the per-head RMSNorm can lead to instability in later stages of large-scale pretraining of LLM.
|
||||
|
||||
3. **Simpler Parameterization & Initialization**
|
||||
We replace the globally shared $\lambda$ with a token-specific, head-wise projected $\lambda$. This eliminates the exponential re-parameterization and initialization complexity of $\lambda$ in V1.
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Pseudocode
|
||||
|
||||
In the script, `h` represents number of query heads, `h_kv` represents number of key-value heads, and `d` means head dimension. The $\lambda$ in DIFF V2 is projected from $X$ for each token each head.
|
||||
|
||||
(For simplicity, we omit the batch dimension and assume that both the input and output of the following `flash_attn_func` are three-dimensional tensors `(tokens, heads, head dimension)`. Heads belonging to the same GQA group are arranged contiguously in the output)
|
||||
|
||||
```python
|
||||
def DiffAttnV2(
|
||||
q, k, v, lam
|
||||
):
|
||||
"""
|
||||
q: (N, 2h, d)
|
||||
k: (N, h_kv, d)
|
||||
v: (N, h_kv, d)
|
||||
lam: (N, h, 1)
|
||||
"""
|
||||
|
||||
attn = flash_attn_func(q, k, v)
|
||||
attn1, attn2 = (attn[:, 0::2],
|
||||
attn[:, 1::2])
|
||||
|
||||
lam_val = sigmoid(lam)
|
||||
attn = attn1 - lam_val * attn2
|
||||
return attn
|
||||
```
|
||||
|
||||
### Note
|
||||
|
||||
DIFF V2 subtracts two heads that are **in the same GQA group, which means they share the same key and value**.
|
||||
|
||||
```python
|
||||
# Subtraction of two heads that are **not** in the same GQA group
|
||||
# ❌ Wrong Implementation of DIFF V2!
|
||||
...
|
||||
attn = flash_attn_func(q, k, v)
|
||||
nh = attn.size(1)
|
||||
attn1, attn2 = (attn[:, :nh//2],
|
||||
attn[:, nh//2:])
|
||||
# similarly, also wrong implementation:
|
||||
# attn1, attn2 = attn.chunk(2, dim=1)
|
||||
...
|
||||
```
|
||||
|
||||
```python
|
||||
# DIFF V2: Subtraction of two heads that are **in** the same GQA group
|
||||
# ✅ Correct Implementation of DIFF V2
|
||||
...
|
||||
attn = flash_attn_func(q, k, v)
|
||||
|
||||
attn1, attn2 = (attn[:, 0::2],
|
||||
attn[:, 1::2])
|
||||
...
|
||||
```
|
||||
@@ -0,0 +1,76 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
from typing import Optional, Tuple
|
||||
from ..kernel.rotary import apply_rotary_emb
|
||||
from flash_attn import flash_attn_func
|
||||
|
||||
|
||||
@torch.compile
|
||||
def diff_func(attn1: torch.Tensor, attn2: torch.Tensor, lambda_val: torch.Tensor) -> torch.Tensor:
|
||||
return attn1 - torch.sigmoid(lambda_val).unsqueeze(-1) * attn2
|
||||
|
||||
|
||||
class MultiheadFlashDiffV2(nn.Module):
|
||||
"""
|
||||
Differential Attention Version 2 (DiffAttnV2) implementation using Flash Attention.
|
||||
"""
|
||||
def __init__(
|
||||
self,
|
||||
use_diff_v2: bool, # If False, acts as a baseline Transformer attention
|
||||
d_model: int, # Model dimension
|
||||
num_heads: int, # Number of output heads
|
||||
num_kv_heads: Optional[int], # Number of KV heads for GQA
|
||||
head_dim: int, # Dimension per head
|
||||
):
|
||||
super().__init__()
|
||||
self.use_diff_v2 = use_diff_v2
|
||||
self.d_model = d_model
|
||||
self.num_heads = num_heads
|
||||
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
||||
self.head_dim = head_dim
|
||||
|
||||
self.num_q_heads = 2 * self.num_heads if self.use_diff_v2 else self.num_heads
|
||||
self.q_proj = nn.Linear(self.d_model, self.num_q_heads * self.head_dim, bias=False)
|
||||
self.k_proj = nn.Linear(self.d_model, self.num_kv_heads * self.head_dim, bias=False)
|
||||
self.v_proj = nn.Linear(self.d_model, self.num_kv_heads * self.head_dim, bias=False)
|
||||
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.d_model, bias=False)
|
||||
self.lambda_proj = nn.Linear(self.d_model, self.num_heads, bias=False) if self.use_diff_v2 else None
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor, # Input tensor [bsz, seq_len, d_model]
|
||||
rel_pos: Tuple[torch.Tensor, torch.Tensor], # Rotary embedding (cos, sin)
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Forward pass for MultiheadFlashDiffV2.
|
||||
|
||||
Args:
|
||||
x: Input hidden states of shape [batch, length, d_model]
|
||||
rel_pos: Tuple of (cos, sin) tensors for rotary positional embeddings
|
||||
|
||||
Returns:
|
||||
Output tensor of shape [batch, length, d_model]
|
||||
"""
|
||||
bsz, tgt_len, _ = x.size()
|
||||
src_len = tgt_len
|
||||
|
||||
q = self.q_proj(x)
|
||||
k = self.k_proj(x)
|
||||
v = self.v_proj(x)
|
||||
|
||||
q = q.view(bsz, tgt_len, self.num_q_heads, self.head_dim)
|
||||
k = k.view(bsz, src_len, self.num_kv_heads, self.head_dim)
|
||||
v = v.view(bsz, src_len, self.num_kv_heads, self.head_dim)
|
||||
|
||||
q = apply_rotary_emb(q, *rel_pos, interleaved=True)
|
||||
k = apply_rotary_emb(k, *rel_pos, interleaved=True)
|
||||
|
||||
attn = flash_attn_func(q, k, v, causal=True)
|
||||
if self.use_diff_v2:
|
||||
lambda_val = self.lambda_proj(x)
|
||||
attn1, attn2 = attn[:, :, 0::2], attn[:, :, 1::2]
|
||||
attn = diff_func(attn1, attn2, lambda_val)
|
||||
|
||||
attn = attn.reshape(bsz, tgt_len, self.num_heads * self.head_dim)
|
||||
output = self.o_proj(attn)
|
||||
return output
|
||||
Reference in New Issue
Block a user