|
|
import math
|
|
|
from typing import Optional
|
|
|
|
|
|
import torch
|
|
|
import torch.nn.functional as F
|
|
|
from torch import nn
|
|
|
|
|
|
|
|
|
from .rotary import apply_rotary_emb
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
|
|
|
"""Efficiently repeat keys / values for GQA without allocating new memory."""
|
|
|
bs, n_kv_heads, slen, head_dim = x.shape
|
|
|
if n_rep == 1:
|
|
|
return x
|
|
|
return (
|
|
|
x[:, :, None, :, :]
|
|
|
.expand(bs, n_kv_heads, n_rep, slen, head_dim)
|
|
|
.reshape(bs, n_kv_heads * n_rep, slen, head_dim)
|
|
|
)
|
|
|
|
|
|
|
|
|
def lambda_init_fn(depth: int) -> float:
|
|
|
"""Init schedule described in the DiffAttention paper."""
|
|
|
return 0.8 - 0.6 * math.exp(-0.3 * depth)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class MultiheadDiffAttn(nn.Module):
|
|
|
"""Optimised DiffAttention block.
|
|
|
|
|
|
Differences from the original implementation:
|
|
|
1. Removes the dependency on Apex / FusedRMSNorm; uses native LayerNorm.
|
|
|
2. Keeps all tensors on-device and works well with autocast fp16/bf16.
|
|
|
3. Minimises Python-side tensor reshapes and kernel launches.
|
|
|
"""
|
|
|
|
|
|
def __init__(
|
|
|
self,
|
|
|
embed_dim: int,
|
|
|
depth: int,
|
|
|
num_heads: int,
|
|
|
num_kv_heads: Optional[int] = None,
|
|
|
dropout: float = 0.1,
|
|
|
) -> None:
|
|
|
super().__init__()
|
|
|
|
|
|
self.embed_dim = embed_dim
|
|
|
self.num_heads = num_heads
|
|
|
self.num_kv_heads = num_kv_heads or num_heads
|
|
|
self.n_rep = (
|
|
|
self.num_heads // self.num_kv_heads
|
|
|
)
|
|
|
self.attn_dropout = dropout
|
|
|
|
|
|
|
|
|
self.head_dim = embed_dim // self.num_heads // 2
|
|
|
assert (
|
|
|
self.head_dim * self.num_heads * 2 == embed_dim
|
|
|
), "embed_dim must be divisible by num_heads * 2"
|
|
|
self.scaling = self.head_dim**-0.5
|
|
|
|
|
|
|
|
|
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
|
|
self.k_proj = nn.Linear(embed_dim, embed_dim // self.n_rep, bias=False)
|
|
|
self.v_proj = nn.Linear(embed_dim, embed_dim // self.n_rep, bias=False)
|
|
|
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False)
|
|
|
|
|
|
|
|
|
self.dropout = nn.Dropout(dropout)
|
|
|
|
|
|
|
|
|
self.lambda_init = lambda_init_fn(depth)
|
|
|
self.lambda_q1 = nn.Parameter(torch.randn(self.head_dim) * 0.1)
|
|
|
self.lambda_k1 = nn.Parameter(torch.randn(self.head_dim) * 0.1)
|
|
|
self.lambda_q2 = nn.Parameter(torch.randn(self.head_dim) * 0.1)
|
|
|
self.lambda_k2 = nn.Parameter(torch.randn(self.head_dim) * 0.1)
|
|
|
|
|
|
|
|
|
self.subln = nn.LayerNorm(2 * self.head_dim, eps=1e-5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def forward(
|
|
|
self,
|
|
|
x: torch.Tensor,
|
|
|
rel_pos: tuple[torch.Tensor, torch.Tensor],
|
|
|
attn_mask: Optional[torch.Tensor] = None,
|
|
|
) -> torch.Tensor:
|
|
|
bsz, seq_len, _ = x.size()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
q = self.q_proj(x)
|
|
|
k = self.k_proj(x)
|
|
|
v = self.v_proj(x)
|
|
|
|
|
|
|
|
|
q = q.view(bsz, seq_len, 2 * self.num_heads, self.head_dim)
|
|
|
k = k.view(bsz, seq_len, 2 * self.num_kv_heads, self.head_dim)
|
|
|
v = v.view(bsz, seq_len, self.num_kv_heads, 2 * self.head_dim)
|
|
|
|
|
|
|
|
|
cos, sin = rel_pos
|
|
|
cos = cos.to(dtype=q.dtype)
|
|
|
sin = sin.to(dtype=q.dtype)
|
|
|
q = apply_rotary_emb(q, cos, sin, interleaved=True)
|
|
|
k = apply_rotary_emb(k, cos, sin, interleaved=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
q = q.transpose(1, 2)
|
|
|
k = k.transpose(1, 2)
|
|
|
v = v.transpose(1, 2)
|
|
|
|
|
|
|
|
|
k = repeat_kv(k, self.n_rep)
|
|
|
v = repeat_kv(v, self.n_rep)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
q_pairs = q.view(bsz, 2, self.num_heads, seq_len, self.head_dim).permute(
|
|
|
0, 2, 1, 3, 4
|
|
|
)
|
|
|
k_pairs = k.view(bsz, 2, self.num_heads, seq_len, self.head_dim).permute(
|
|
|
0, 2, 1, 3, 4
|
|
|
)
|
|
|
|
|
|
q_pos, q_neg = q_pairs[:, :, 0], q_pairs[:, :, 1]
|
|
|
k_pos, k_neg = k_pairs[:, :, 0], k_pairs[:, :, 1]
|
|
|
|
|
|
|
|
|
lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1)).type_as(q_pos)
|
|
|
lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2)).type_as(q_pos)
|
|
|
lambda_full = lambda_1 - lambda_2 + self.lambda_init
|
|
|
|
|
|
|
|
|
ctx_pos = F.scaled_dot_product_attention(
|
|
|
q_pos, k_pos, v, dropout_p=self.attn_dropout, is_causal=True
|
|
|
)
|
|
|
ctx_neg = F.scaled_dot_product_attention(
|
|
|
q_neg, k_neg, v, dropout_p=self.attn_dropout, is_causal=True
|
|
|
)
|
|
|
|
|
|
|
|
|
attn_out = ctx_pos - lambda_full * ctx_neg
|
|
|
|
|
|
|
|
|
attn_out = self.subln(attn_out) * (1.0 - self.lambda_init)
|
|
|
|
|
|
|
|
|
attn_out = attn_out.transpose(1, 2).reshape(
|
|
|
bsz, seq_len, self.embed_dim
|
|
|
)
|
|
|
|
|
|
out = self.out_proj(attn_out)
|
|
|
return self.dropout(out)
|
|
|
|