File size: 1,751 Bytes
59d0297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import torch
import torch.nn.functional as F

def _build_sink_window_mask(T, window_size, num_sink_tokens, device):
    """Build causal + sliding window + sink tokens attention mask."""
    # Start with causal mask
    row = torch.arange(T, device=device).unsqueeze(1)
    col = torch.arange(T, device=device).unsqueeze(0)
    causal = col <= row
    # Add window constraint: attend to [max(0, i - window_size + 1) : i + 1]
    window = (row - col) < window_size
    # Sink tokens: always attend to first num_sink_tokens positions
    sink = col < num_sink_tokens
    # Combine: causal AND (within window OR sink token)
    mask = causal & (window | sink)
    return mask

def flash_attn_func(q, k, v, causal=False, window_size=None, num_sink_tokens=0):
    # q: [B, T, H, D], k: [B, T, Hkv, D], v: [B, T, Hkv, D]
    B, T, H, D = q.shape
    Hkv = k.shape[2]
    group = H // Hkv

    # Expand KV heads for GQA
    if group > 1:
        k = k.unsqueeze(3).expand(B, T, Hkv, group, D).reshape(B, T, H, D)
        v = v.unsqueeze(3).expand(B, T, Hkv, group, D).reshape(B, T, H, D)

    # [B, T, H, D] -> [B, H, T, D] for SDPA
    q = q.transpose(1, 2)
    k = k.transpose(1, 2)
    v = v.transpose(1, 2)

    use_window = window_size is not None and window_size != (-1, -1)
    if use_window or num_sink_tokens > 0:
        ws = window_size[0] if isinstance(window_size, tuple) else (window_size or T)
        mask = _build_sink_window_mask(T, ws, num_sink_tokens, q.device)
        out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
    elif causal:
        out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
    else:
        out = F.scaled_dot_product_attention(q, k, v)
    return out.transpose(1, 2)  # back to [B, T, H, D]