Download code/flash_attn_interface/__init__.py from amarck/parameter-golf-scylla: direct link, hf CLI and curl.
- Browser
- Download file 1.75 kB
-
https://huggingface.co/datasets/amarck/parameter-golf-scylla/resolve/main/code/flash_attn_interface/__init__.py
- Command line
-
hf download hf://datasets/amarck/parameter-golf-scylla/code/flash_attn_interface/__init__.py
-
curl -L -o __init__.py https://huggingface.co/datasets/amarck/parameter-golf-scylla/resolve/main/code/flash_attn_interface/__init__.py
1.75 kB
| 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] | |