File size: 19,264 Bytes
2d13eb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325

# === Appended from canonical.py ===
import math
import torch
import torch.nn.functional as F
from torch import nn

# Import for Rotary Positional Embeddings, a common technique in modern Transformers.
# Its use is mentioned in the paper's experimental setup (Section 3.3).
from kernel.rotary import apply_rotary_emb
try:
    # Attempt to import FusedRMSNorm from Apex for optimized performance.
    # This is an efficiency optimization and doesn't change the mathematical function.
    from apex.normalization import FusedRMSNorm as RMSNorm
except ModuleNotFoundError:
    # Fallback to a standard RMSNorm implementation if Apex is not available.
    print("No fused RMSNorm")
    from rms_norm import RMSNorm # Assuming rms_norm.py contains a PyTorch RMSNorm implementation


# --- Helper Function for Grouped-Query Attention (GQA) ---
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
    """
    Repeats Key (K) and Value (V) tensors for Grouped-Query Attention (GQA).
    In GQA, multiple query heads can share the same key/value head, reducing
    computation and memory for K and V projections compared to Multi-Head Attention (MHA).
    This function is equivalent to torch.repeat_interleave(x, dim=1, repeats=n_rep)
    if the input `x` was shaped (bs, n_kv_heads, slen * head_dim) and then reshaped,
    but here it operates on x with shape (bs, n_kv_heads, slen, head_dim) by expanding
    and reshaping. The dim 1 here refers to the head dimension after transpose.

    Args:
        x (torch.Tensor): Input Key or Value tensor after transposing to
                          (batch_size, num_kv_heads_or_values, sequence_length, head_dimension_component).
                          For K, num_kv_heads_or_values is 2 * num_kv_heads (for K1, K2).
                          For V, num_kv_heads_or_values is num_kv_heads.
        n_rep (int): Number of times to repeat each K/V head group.
                     This is typically num_query_heads / num_kv_heads.

    Returns:
        torch.Tensor: Repeated K/V tensor.
                      Shape for K: (batch_size, 2 * num_heads, sequence_length, head_dimension).
                      Shape for V: (batch_size, num_heads, sequence_length, 2 * head_dimension).

    Paper Correspondence:
    - The paper mentions the use of Grouped-Query Attention (GQA) in the __init__
      comments of the MultiheadDiffAttn class description (though not in the main text of Section 2.1).
    - This is a standard GQA implementation detail.
    """
    bs, n_kv_heads_component, slen, head_dim_component = x.shape # Note: n_kv_heads_component is the number of K/V groups to be repeated.
    if n_rep == 1:
        # If n_rep is 1, it means num_query_heads == num_kv_heads (no GQA, or MHA setup).
        # No repetition needed.
        return x
    # Expand and reshape to achieve repetition:
    # 1. Add a new dimension for repetition: x[:, :, None, :, :]
    #    Shape becomes (bs, n_kv_heads_component, 1, slen, head_dim_component)
    # 2. Expand along this new dimension: .expand(bs, n_kv_heads_component, n_rep, slen, head_dim_component)
    #    This copies the K/V head data `n_rep` times.
    #    Shape becomes (bs, n_kv_heads_component, n_rep, slen, head_dim_component)
    # 3. Reshape to combine n_kv_heads_component and n_rep: .reshape(bs, n_kv_heads_component * n_rep, slen, head_dim_component)
    #    This results in the desired shape where the original K/V groups are now repeated to match query head groups.
    return (
        x[:, :, None, :, :]
        .expand(bs, n_kv_heads_component, n_rep, slen, head_dim_component)
        .reshape(bs, n_kv_heads_component * n_rep, slen, head_dim_component)
    )

# --- Helper Function for Lambda Initialization ---
def lambda_init_fn(depth: int) -> float:
    """
    Calculates the initial value for the static component of lambda ($\lambda_{init}$)
    based on the layer depth. This function is used to initialize `self.lambda_init`
    in the `MultiheadDiffAttn` class.

    Args:
        depth (int): Current layer index (assumed to be 0-indexed by the caller).

    Returns:
        float: The initial value for $\lambda_{init}$.

    Paper Correspondence:
    - This function directly implements the formula provided in Section 2.1 of the paper,
      just below Equation (2):
      $\lambda_{init} = 0.8 - 0.6 \times \exp(-0.3 \cdot (l-1))$
    - In this code, `depth` corresponds to `(l-1)` from the paper's formula,
      where `l` is the 1-indexed layer number.
    """
    return 0.8 - 0.6 * math.exp(-0.3 * depth)


# --- Multi-Head Differential Attention Module ---
class MultiheadDiffAttn(nn.Module):
    def __init__(
        self,
        embed_dim: int, # Dimension of input embeddings (d_model in the paper).
        depth: int,      # Current layer index (0-indexed), used for lambda_init_fn.
        num_heads: int,  # Number of differential attention heads (h in the paper).
        num_kv_heads: int =None, # Number of Key/Value heads for GQA. If None, defaults to num_heads (MHA).
    ):
        super().__init__()
        self.embed_dim = embed_dim # d_model

        # `num_heads` (h in the paper) for DIFF Transformer is typically set to half
        # of a baseline Transformer's number of attention heads to maintain similar
        # parameter counts and computational complexity, as mentioned in Section 2.1 and 3.1.
        # This `num_heads` refers to the number of differential attention units.
        self.num_heads = num_heads

        # `num_kv_heads` is for Grouped-Query Attention (GQA).
        # If not specified (None), it defaults to `num_heads`, implying Multi-Head Attention (MHA)
        # where each differential head has its own K, V projections (before splitting into K1/K2).
        self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
        # Repetition factor for GQA, calculated as num_query_heads / num_kv_heads.
        # Here, num_query_heads is effectively self.num_heads (number of differential units).
        self.n_rep = self.num_heads // self.num_kv_heads

        # `head_dim` (d in the paper) is the dimension for EACH of Q1, Q2, K1, K2 vectors.
        # Paper (Section 2.1) states:
        # $Q_1, Q_2, K_1, K_2 \in \mathbb{R}^{N \times d}$
        # $V \in \mathbb{R}^{N \times 2d}$
        # And for Multi-Head: $h = d_{model} / (2d)$. Rearranging for d: $d = d_{model} / (2h)$.
        # In code: self.head_dim = embed_dim / (num_heads * 2).
        self.head_dim = embed_dim // num_heads // 2
        # Scaling factor for attention scores, $1/\sqrt{d}$, as per Equation (1).
        self.scaling = self.head_dim ** -0.5

        # --- Linear Projections for Q, K, V ---
        # These correspond to $W^Q, W^K, W^V$ in Equation (1) of the paper.
        # Bias is set to False, a common practice in modern Transformers (e.g., LLaMA),
        # and mentioned in Appendix B of the paper for their baseline Transformer.

        # Query projection: $XW^Q$. Projects `embed_dim` to `embed_dim`.
        # The output of this projection will be reshaped to form Q1 and Q2 components
        # for each of the `num_heads` differential attention heads.
        # Total projected query dim = num_heads * 2 * head_dim = embed_dim.
        self.q_proj = nn.Linear(embed_dim, embed_dim, bias=False)

        # Key projection: $XW^K$. Projects `embed_dim` to `embed_dim // n_rep`.
        # `embed_dim // n_rep` is equivalent to `num_kv_heads * 2 * head_dim`.
        # This provides the dimensions for K1 and K2 for each of the `num_kv_heads`.
        self.k_proj = nn.Linear(embed_dim, embed_dim // self.n_rep, bias=False)

        # Value projection: $XW^V$. Projects `embed_dim` to `embed_dim // n_rep`.
        # `embed_dim // n_rep` is equivalent to `num_kv_heads * 2 * head_dim`.
        # The paper states $V \in \mathbb{R}^{N \times 2d}$ per head. So for each of the `num_kv_heads`,
        # the value vector dimension is `2 * head_dim`.
        self.v_proj = nn.Linear(embed_dim, embed_dim // self.n_rep, bias=False)

        # Output projection: $W^O$ in Equation (3) of the paper.
        # Projects the concatenated head outputs back to `embed_dim`.
        self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False)

        # --- Lambda Parameters for Differential Attention ---
        # These parameters are used to compute the learnable scalar $\lambda$
        # as defined in Equation (2) of the paper:
        # $\lambda = \exp(\lambda_{q_1} \cdot \lambda_{k_1}) - \exp(\lambda_{q_2} \cdot \lambda_{k_2}) + \lambda_{init}$

        # Static component $\lambda_{init}$, calculated based on layer depth. `depth` is current layer index.
        self.lambda_init = lambda_init_fn(depth)

        # Learnable vectors $\lambda_{q1}, \lambda_{k1}, \lambda_{q2}, \lambda_{k2} \in \mathbb{R}^{d}$
        # where d is `self.head_dim`.
        # The initialization method (normal distribution with mean=0, std=0.1) is a
        # practical choice and not specified in the paper's core algorithm description.
        self.lambda_q1 = nn.Parameter(torch.zeros(self.head_dim, dtype=torch.float32).normal_(mean=0,std=0.1))
        self.lambda_k1 = nn.Parameter(torch.zeros(self.head_dim, dtype=torch.float32).normal_(mean=0,std=0.1))
        self.lambda_q2 = nn.Parameter(torch.zeros(self.head_dim, dtype=torch.float32).normal_(mean=0,std=0.1))
        self.lambda_k2 = nn.Parameter(torch.zeros(self.head_dim, dtype=torch.float32).normal_(mean=0,std=0.1))

        # --- Normalization Layer ---
        # This corresponds to $LN(head_i)$ in Equation (3) and is visualized as "GroupNorm"
        # in Figure 2 of the paper, applied independently to each head's output.
        # It's applied to the result of $(A_1 - \lambda A_2)V$ for each head.
        # The dimension of this per-head output is $2 \times \text{head\_dim}$ (the dimension of V for that head).
        # `eps=1e-5` is a standard epsilon value for RMSNorm.
        # `elementwise_affine=True` means RMSNorm has learnable gain and bias parameters.
        self.subln = RMSNorm(2 * self.head_dim, eps=1e-5, elementwise_affine=True)

    def forward(
        self,
        x: torch.Tensor, # Input tensor: (batch_size, sequence_length, embed_dim)
        rel_pos: tuple,  # Positional embeddings (e.g., from RoPE). Passed as a tuple of (cos, sin)
        attn_mask: torch.Tensor =None, # Attention mask (e.g., for causal decoding)
    ):
        bsz, tgt_len, _ = x.size() # bsz: batch_size, tgt_len: target sequence length
        # embed_dim is also x.size(-1) but not explicitly captured from size() here.
        src_len = tgt_len # Assuming self-attention, or cross-attention where src_len == tgt_len

        # 1. Project Queries, Keys, Values
        # Paper Correspondence: $Q = XW^Q, K = XW^K, V = XW^V$ from Eq (1) (conceptually).
        # q, k, v here are the full projections before reshaping into heads and Q1/Q2 etc.
        q = self.q_proj(x) # Shape: (bsz, tgt_len, embed_dim)
        k = self.k_proj(x) # Shape: (bsz, src_len, embed_dim // n_rep)
        v = self.v_proj(x) # Shape: (bsz, src_len, embed_dim // n_rep)

        # 2. Reshape Q, K, V for Multi-Head Processing
        # Q: (bsz, tgt_len, 2 * num_heads, head_dim)
        #   The `2 * num_heads` dimension effectively contains Q1 and Q2 components for all `num_heads`.
        q = q.view(bsz, tgt_len, 2 * self.num_heads, self.head_dim)
        # K: (bsz, src_len, 2 * num_kv_heads, head_dim)
        #   The `2 * num_kv_heads` dimension contains K1 and K2 components for all `num_kv_heads`.
        k = k.view(bsz, src_len, 2 * self.num_kv_heads, self.head_dim)
        # V: (bsz, src_len, num_kv_heads, 2 * head_dim)
        #   Each of the `num_kv_heads` has a value vector of dimension `2 * head_dim` (as V is $2d$ per head).
        v = v.view(bsz, src_len, self.num_kv_heads, 2 * self.head_dim)

        # 3. Apply Rotary Positional Embeddings (RoPE)
        # Paper Correspondence: RoPE is mentioned in experimental setups (e.g., Section 3.3)
        # but not in the core algorithm description in Section 2.1. Its use here is a
        # standard architectural choice for modern Transformers to inject positional information.
        # `interleaved=True` is a specific RoPE implementation detail.
        q = apply_rotary_emb(q, *rel_pos, interleaved=True)
        k = apply_rotary_emb(k, *rel_pos, interleaved=True)
        # Note: RoPE is typically applied after reshaping to (bsz, num_heads_total, seq_len, head_dim_component).
        # The current application is on q(bsz, tgt_len, 2*num_h, h_dim) and k(bsz, src_len, 2*num_kv_h, h_dim).
        # The apply_rotary_emb function must be compatible with this shape, likely operating on the last two dims.

        # `offset` is used for creating a causal mask if `attn_mask` is None.
        # For self-attention, src_len == tgt_len, so offset is 0.
        offset = src_len - tgt_len

        # 4. Transpose and Repeat K, V for GQA
        # Transpose Q to (bsz, 2 * num_heads, tgt_len, head_dim)
        q = q.transpose(1, 2)
        # Transpose K to (bsz, 2 * num_kv_heads, src_len, head_dim) then repeat for GQA.
        # Resulting K shape: (bsz, 2 * num_heads, src_len, head_dim)
        k = repeat_kv(k.transpose(1, 2), self.n_rep)
        # Transpose V to (bsz, num_kv_heads, src_len, 2 * head_dim) then repeat for GQA.
        # Resulting V shape: (bsz, num_heads, src_len, 2 * head_dim)
        v = repeat_kv(v.transpose(1, 2), self.n_rep)
        # At this point:
        # q: (bsz, 2 * num_heads, tgt_len, head_dim) -> Q1s and Q2s for all diff_heads
        # k: (bsz, 2 * num_heads, src_len, head_dim) -> K1s and K2s for all diff_heads (after GQA repeat)
        # v: (bsz, num_heads, src_len, 2*head_dim) -> Vs for all diff_heads (after GQA repeat)

        # 5. Compute Raw Attention Scores (before softmax)
        # This computes $Q K^T / \sqrt{d}$.
        q = q * self.scaling # Apply $1/\sqrt{d}$ scaling to queries
        # attn_weights shape: (bsz, 2 * num_heads, tgt_len, src_len)
        # This tensor contains the raw scores for both $Q_1K_1^T/\sqrt{d}$ and $Q_2K_2^T/\sqrt{d}$
        # interleaved along the `2 * num_heads` dimension.
        attn_weights = torch.matmul(q, k.transpose(-1, -2))

        # 6. Apply Attention Mask
        if attn_mask is None:
            # Create a causal mask if no mask is provided.
            # This prevents attention to future positions in a sequence.
            # `torch.triu` creates an upper triangle matrix. `diagonal=1+offset` ensures causality.
            # For self-attention (offset=0), diagonal is 1 (strict upper triangle).
            attn_mask = torch.triu(
                torch.zeros([tgt_len, src_len], device=attn_weights.device, dtype=torch.float) # Ensure same device
                .fill_(float("-inf")) # Fill with -infinity for masked positions
                .type_as(attn_weights), # Ensure same dtype as attn_weights
                1 + offset,
            )
            # This mask will be (tgt_len, src_len) and broadcastable.

        # Handle potential NaNs that might arise from masking or other operations.
        # This is a robustness measure.
        attn_weights = torch.nan_to_num(attn_weights)
        # Additive mask application.
        attn_weights = attn_weights + attn_mask # Additive mask
        
        # 7. Apply Softmax to get attention probabilities
        # Softmax is applied over the `src_len` dimension (dim=-1).
        # Using float32 for softmax computation can improve numerical stability, then cast back.
        attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).type_as(
            attn_weights # Cast back to original type (e.g. float16 if using mixed precision)
        )
        # attn_weights now contains softmax probabilities for both A1 and A2 components, interleaved.
        # Shape: (bsz, 2 * num_heads, tgt_len, src_len)

        # 8. Calculate the full lambda value (scalar)
        # Implements Equation (2) from the paper:
        # $\lambda = \exp(\lambda_{q_1} \cdot \lambda_{k_1}) - \exp(\lambda_{q_2} \cdot \lambda_{k_2}) + \lambda_{init}$
        # The dot product `torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1)` is over `head_dim`.
        # The result `lambda_full` is a scalar that will be shared by all heads in this layer.
        lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1).float()).type_as(q)
        lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1).float()).type_as(q)
        lambda_full = lambda_1 - lambda_2 + self.lambda_init

        # 9. Separate A1_probs and A2_probs and compute differential attention scores
        # Reshape attn_weights to explicitly separate the two components (A1 and A2) for each head.
        # (bsz, 2 * num_heads, tgt_len, src_len) -> (bsz, num_heads, 2, tgt_len, src_len)
        attn_weights = attn_weights.view(bsz, self.num_heads, 2, tgt_len, src_len)
        # Extract A1 probabilities (index 0 of the new dimension)
        # Extract A2 probabilities (index 1 of the new dimension)
        # Compute the differential attention scores: $A_1 - \lambda A_2$
        # This is the core of the differential attention mechanism from Equation (1) of the paper.
        attn_weights = attn_weights[:, :, 0] - lambda_full * attn_weights[:, :, 1]
        # attn_weights shape now: (bsz, num_heads, tgt_len, src_len)

        # 10. Compute Weighted Sum with Values (V)
        # This calculates $(A_1 - \lambda A_2)V$ for each head.
        # attn_weights shape: (bsz, num_heads, tgt_len, src_len)
        # v (after GQA repeat): (bsz, num_heads, src_len, 2 * head_dim)
        # attn shape: (bsz, num_heads, tgt_len, 2 * head_dim)
        attn = torch.matmul(attn_weights, v)

        # 11. Apply Head-wise Normalization (RMSNorm)
        # Paper Correspondence: This is $LN(head_i)$ in Equation (3) and referred to as
        # GroupNorm in Figure 2 (implying normalization per head).
        # RMSNorm normalizes over the last dimension (which is $2 \times \text{head\_dim}$).
        attn = self.subln(attn)
        # attn shape: (bsz, num_heads, tgt_len, 2 * head_dim)

        # 12. Apply fixed scaling factor $(1 - \lambda_{init})$
        # Paper Correspondence: This matches Equation (3): $\overline{head_i} = (1 - \lambda_{init}) \cdot LN(head_i)$.
        # This scaling is applied to align gradient flow with standard Transformers (Appendix G).
        attn = attn * (1 - self.lambda_init)

        # 13. Concatenate Heads and Reshape for Output Projection
        # Transpose to bring sequence length before heads: (bsz, tgt_len, num_heads, 2 * head_dim)
        # Reshape to combine head outputs into a single dimension: (bsz, tgt_len, num_heads * 2 * head_dim)
        # Since num_heads * 2 * head_dim = embed_dim, final shape is (bsz, tgt_len, embed_dim).
        # Paper Correspondence: This implements $Concat(\overline{head_1}, ..., \overline{head_h})$ from Eq (3).
        attn = attn.transpose(1, 2).reshape(bsz, tgt_len, self.num_heads * 2 * self.head_dim)

        # 14. Final Output Projection
        # Paper Correspondence: Multiplies by $W^O$ as in Equation (3).
        attn = self.out_proj(attn) # Shape: (bsz, tgt_len, embed_dim)
        return attn