SeaWolf-AI commited on
Commit
48b5231
ยท
verified ยท
1 Parent(s): 79fb190

fix: make model loadable via AutoModelForCausalLM (add auto_map, flatten module files to repo root, inherit GenerationMixin)

Browse files
Files changed (1) hide show
  1. nsa.py +149 -0
nsa.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ """
3
+ Native Sparse Attention (NSA) โ€” 3-branch design.
4
+
5
+ โš ๏ธ ๋™์ƒ ์ž‘์„ฑ placeholder (์‚ฌ์šฉ์ž๋‹˜ ๋ณธ PC ์ •์‹ ๋ฒ„์ „ ๋„์ฐฉ ์‹œ ๊ต์ฒด)
6
+
7
+ Branches:
8
+ 1. Compress: average over blocks โ†’ KV cache reduction
9
+ 2. Select: top-k token selection per query
10
+ 3. Sliding: local window attention
11
+ 4. Gate: learnable combination of 3 branches
12
+ """
13
+ import math
14
+ from typing import Optional, Tuple
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+
20
+
21
+ class NSAAttention(nn.Module):
22
+ """3-branch Native Sparse Attention.
23
+
24
+ For testing purposes. Production version ์‚ฌ์šฉ์ž๋‹˜ ๋ณธ PC.
25
+ """
26
+
27
+ def __init__(self, config, layer_idx: int = 0):
28
+ super().__init__()
29
+ self.config = config
30
+ self.layer_idx = layer_idx
31
+ self.hidden_size = config.hidden_size
32
+ self.num_heads = config.num_attention_heads
33
+ self.num_kv_heads = getattr(config, "num_key_value_heads", config.num_attention_heads)
34
+ self.head_dim = config.head_dim
35
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
36
+ self.compress_block = getattr(config, "compress_block_size", 16)
37
+ self.sliding_window = getattr(config, "sliding_window_size", 256)
38
+ self.select_topk = getattr(config, "nsa_select_topk", 16)
39
+
40
+ # Shared Q/K/V projections (3 branches share base projections)
41
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
42
+ self.k_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
43
+ self.v_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
44
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
45
+
46
+ # Compress branch: pooling MLP
47
+ self.compress_mlp = nn.Linear(self.head_dim, self.head_dim, bias=False)
48
+
49
+ # Select branch: scoring head (project to scalar score per token)
50
+ self.select_score = nn.Linear(self.head_dim, 1, bias=False)
51
+
52
+ # 3-branch gate (initialized at 0.5 each, will be normalized)
53
+ self.gate_logit = nn.Parameter(torch.zeros(3)) # sigmoid โ†’ ~0.5
54
+
55
+ def _repeat_kv(self, x: torch.Tensor) -> torch.Tensor:
56
+ """GQA: repeat KV heads to match Q heads."""
57
+ if self.num_kv_groups == 1:
58
+ return x
59
+ bsz, n_kv, seq, dim = x.shape
60
+ return (x[:, :, None, :, :]
61
+ .expand(bsz, n_kv, self.num_kv_groups, seq, dim)
62
+ .reshape(bsz, n_kv * self.num_kv_groups, seq, dim))
63
+
64
+ def _compress_branch(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
65
+ """Compress branch: average KV in blocks, then full attention on compressed."""
66
+ bsz, n_h, seq, dim = q.shape
67
+ if seq < self.compress_block * 2:
68
+ return self._full_attention(q, k, v)
69
+
70
+ n_blocks = seq // self.compress_block
71
+ # Compress K, V by averaging blocks (only complete blocks)
72
+ usable = n_blocks * self.compress_block
73
+ k_comp = k[:, :, :usable, :].view(bsz, n_h, n_blocks, self.compress_block, dim).mean(dim=3)
74
+ v_comp = v[:, :, :usable, :].view(bsz, n_h, n_blocks, self.compress_block, dim).mean(dim=3)
75
+ # Apply MLP to compressed K
76
+ k_comp = self.compress_mlp(k_comp)
77
+ # Full attention against compressed
78
+ return F.scaled_dot_product_attention(q, k_comp, v_comp, dropout_p=0.0, is_causal=False)
79
+
80
+ def _select_branch(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
81
+ """Select branch: top-k token selection per query position."""
82
+ bsz, n_h, seq, dim = q.shape
83
+ if seq <= self.select_topk:
84
+ return self._full_attention(q, k, v)
85
+
86
+ # Score each KV position via select_score on K
87
+ scores = self.select_score(k).squeeze(-1) # (bsz, n_h, seq)
88
+ topk = min(self.select_topk, seq)
89
+ _, top_idx = scores.topk(topk, dim=-1) # (bsz, n_h, topk)
90
+
91
+ # Gather top-k K, V (causal mask: only attend to past)
92
+ idx_expand = top_idx.unsqueeze(-1).expand(-1, -1, -1, dim)
93
+ k_sel = k.gather(2, idx_expand)
94
+ v_sel = v.gather(2, idx_expand)
95
+
96
+ return F.scaled_dot_product_attention(q, k_sel, v_sel, dropout_p=0.0, is_causal=False)
97
+
98
+ def _sliding_branch(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
99
+ """Sliding window: only attend to local window."""
100
+ bsz, n_h, seq, dim = q.shape
101
+ if seq <= self.sliding_window:
102
+ return self._full_attention(q, k, v)
103
+
104
+ # Build sliding window mask
105
+ idx = torch.arange(seq, device=q.device)
106
+ rel = idx.unsqueeze(0) - idx.unsqueeze(1) # (seq, seq)
107
+ mask = (rel >= 0) & (rel <= self.sliding_window) # local + causal
108
+ attn_mask = torch.where(mask, 0.0, float("-inf")).unsqueeze(0).unsqueeze(0).to(q.dtype)
109
+ return F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=0.0)
110
+
111
+ def _full_attention(self, q, k, v):
112
+ return F.scaled_dot_product_attention(q, k, v, dropout_p=0.0, is_causal=True)
113
+
114
+ def forward(
115
+ self,
116
+ hidden_states: torch.Tensor,
117
+ attention_mask: Optional[torch.Tensor] = None,
118
+ position_ids: Optional[torch.LongTensor] = None,
119
+ past_key_value=None,
120
+ use_cache: bool = False,
121
+ **kwargs,
122
+ ) -> Tuple[torch.Tensor, Optional[object]]:
123
+ bsz, q_len, _ = hidden_states.size()
124
+
125
+ q = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
126
+ k = self.k_proj(hidden_states).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
127
+ v = self.v_proj(hidden_states).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
128
+
129
+ # GQA: repeat KV to match Q heads
130
+ k = self._repeat_kv(k)
131
+ v = self._repeat_kv(v)
132
+
133
+ # 3 branches
134
+ out_compress = self._compress_branch(q, k, v)
135
+ out_select = self._select_branch(q, k, v)
136
+ out_sliding = self._sliding_branch(q, k, v)
137
+
138
+ # Gate (softmax over 3 branches)
139
+ gate = F.softmax(self.gate_logit, dim=0)
140
+ out = (gate[0] * out_compress
141
+ + gate[1] * out_select
142
+ + gate[2] * out_sliding)
143
+
144
+ # Reshape and project
145
+ out = out.transpose(1, 2).contiguous().view(bsz, q_len, -1)
146
+ return self.o_proj(out), past_key_value
147
+
148
+
149
+ __all__ = ["NSAAttention"]