seconds-0 commited on
Commit
9a7a74a
·
verified ·
1 Parent(s): 0d32e96

Upload NSAForCausalLM

Browse files
Files changed (6) hide show
  1. README.md +199 -0
  2. config.json +36 -0
  3. configuration_nsa.py +40 -0
  4. generation_config.json +8 -0
  5. model.safetensors +3 -0
  6. modeling_nsa.py +329 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "NSAForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_nsa.NSAConfig",
7
+ "AutoModelForCausalLM": "modeling_nsa.NSAForCausalLM"
8
+ },
9
+ "d_k": 64,
10
+ "d_v": 64,
11
+ "dtype": "float32",
12
+ "eos_token_id": 0,
13
+ "hidden_size": 768,
14
+ "max_position_embeddings": 2048,
15
+ "model_type": "nsa",
16
+ "n_kv_groups": 2,
17
+ "nsa": {
18
+ "block": 32,
19
+ "branches": [
20
+ "cmp",
21
+ "sel",
22
+ "win"
23
+ ],
24
+ "gqa_groups": 2,
25
+ "sel_block": 64,
26
+ "sel_top_n": 16,
27
+ "stride": 16,
28
+ "window": 512
29
+ },
30
+ "num_attention_heads": 12,
31
+ "num_hidden_layers": 12,
32
+ "pad_token_id": 0,
33
+ "rope_theta": 10000,
34
+ "transformers_version": "4.56.0",
35
+ "vocab_size": 256
36
+ }
configuration_nsa.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Remote code: configuration and modeling for NSA
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class NSAConfig(PretrainedConfig):
6
+ model_type = "nsa"
7
+
8
+ def __init__(
9
+ self,
10
+ vocab_size=50257,
11
+ hidden_size=768,
12
+ num_hidden_layers=12,
13
+ num_attention_heads=12,
14
+ n_kv_groups=1,
15
+ d_k=64,
16
+ d_v=64,
17
+ max_position_embeddings=2048,
18
+ rope_theta=10000,
19
+ nsa=None,
20
+ **kwargs,
21
+ ):
22
+ super().__init__(**kwargs)
23
+ self.vocab_size = vocab_size
24
+ self.hidden_size = hidden_size
25
+ self.num_hidden_layers = num_hidden_layers
26
+ self.num_attention_heads = num_attention_heads
27
+ self.n_kv_groups = n_kv_groups
28
+ self.d_k = d_k
29
+ self.d_v = d_v
30
+ self.max_position_embeddings = max_position_embeddings
31
+ self.rope_theta = rope_theta
32
+ self.nsa = nsa or {
33
+ "branches": ["cmp", "sel", "win"],
34
+ "window": 512,
35
+ "gqa_groups": n_kv_groups,
36
+ "block": 32,
37
+ "stride": 16,
38
+ "sel_block": 64,
39
+ "sel_top_n": 16,
40
+ }
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": [
4
+ 0
5
+ ],
6
+ "pad_token_id": 0,
7
+ "transformers_version": "4.56.0"
8
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a286e8c0a9e11a7bd3355d520a92a32b849212de186aa5c83c19ca23bcda7d8
3
+ size 313204760
modeling_nsa.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Remote code: configuration and modeling for NSA
2
+ import math
3
+ from typing import Optional
4
+
5
+ import torch
6
+ from torch import nn
7
+ from transformers import PreTrainedModel
8
+ from transformers.generation.utils import GenerationMixin
9
+ from transformers.modeling_outputs import CausalLMOutput
10
+
11
+ from .configuration_nsa import NSAConfig
12
+ _HAS_NSA = False # Do not attempt nested vendor import in HF dynamic loader
13
+
14
+
15
+ class RMSNorm(nn.Module):
16
+ def __init__(self, dim: int, eps: float = 1e-6) -> None:
17
+ super().__init__()
18
+ self.weight = nn.Parameter(torch.ones(dim))
19
+ self.eps = eps
20
+
21
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
22
+ rms = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).rsqrt()
23
+ return (x * rms) * self.weight
24
+
25
+
26
+ class MLP(nn.Module):
27
+ def __init__(self, dim: int, hidden_mult: int = 4) -> None:
28
+ super().__init__()
29
+ h = hidden_mult * dim
30
+ self.fc1 = nn.Linear(dim, h, bias=False)
31
+ self.fc2 = nn.Linear(h, dim, bias=False)
32
+
33
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
34
+ return self.fc2(torch.nn.functional.silu(self.fc1(x)))
35
+
36
+
37
+ def _rope(q: torch.Tensor) -> torch.Tensor:
38
+ B, S, D = q.shape[0], q.shape[2], q.shape[-1]
39
+ if D % 2 != 0:
40
+ return q
41
+ device = q.device
42
+ half = D // 2
43
+ pos = torch.arange(S, device=device).float().unsqueeze(-1)
44
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, half, device=device).float() / half))
45
+ angles = pos * inv_freq
46
+ cos = angles.cos().view(1, 1, S, half)
47
+ sin = angles.sin().view(1, 1, S, half)
48
+ q1, q2 = q[..., :half], q[..., half:]
49
+ return torch.cat([q1 * cos - q2 * sin, q1 * sin + q2 * cos], dim=-1)
50
+
51
+
52
+ def _avg_pool_time(x: torch.Tensor, kernel: int, stride: int) -> torch.Tensor:
53
+ if x.shape[2] < kernel:
54
+ return x[..., :0, :]
55
+ xt = x.permute(0, 3, 1, 2).contiguous()
56
+ y = torch.nn.functional.avg_pool2d(xt, kernel_size=(1, kernel), stride=(1, stride))
57
+ return y.permute(0, 2, 3, 1).contiguous()
58
+
59
+
60
+ def _window_mask(q: torch.Tensor, S: int, w: int) -> torch.Tensor:
61
+ B, h = q.shape[0], q.shape[1]
62
+ device = q.device
63
+ row = torch.arange(S, device=device).view(S, 1)
64
+ col = torch.arange(S, device=device).view(1, S)
65
+ allowed = (col <= row) & (col >= (row - (w - 1)))
66
+ M = torch.full((S, S), float('-inf'), device=device, dtype=q.dtype)
67
+ M.masked_fill_(allowed, 0.0)
68
+ return M.view(1, 1, S, S).expand(B, h, S, S)
69
+
70
+
71
+ def _selection_blocks(scores: torch.Tensor, l_sel: int, n_sel: int) -> torch.Tensor:
72
+ B, h, S = scores.shape
73
+ n_blocks = max(1, (S + l_sel - 1) // l_sel)
74
+ # Pad to multiple of l_sel
75
+ pad = n_blocks * l_sel - S
76
+ if pad > 0:
77
+ scores = torch.nn.functional.pad(scores, (0, pad), value=-1e9)
78
+ blk_scores = scores.view(B, h, n_blocks, l_sel).max(dim=-1).values
79
+ k = min(n_sel, n_blocks)
80
+ return torch.topk(blk_scores, k=k, dim=-1).indices
81
+
82
+
83
+ class EmbeddedNSAAttention(nn.Module):
84
+ def __init__(self, dim: int, n_heads: int, n_kv_groups: int, d_k: int, d_v: int,
85
+ l: int, d: int, l_sel: int, n_sel: int, w: int) -> None:
86
+ super().__init__()
87
+ self.n_heads = n_heads
88
+ self.n_kv_groups = n_kv_groups
89
+ self.d_k = d_k
90
+ self.d_v = d_v
91
+ self.l = l
92
+ self.stride = d
93
+ self.l_sel = l_sel
94
+ self.n_sel = n_sel
95
+ self.w = w
96
+ self.W_Q = nn.Linear(dim, n_heads * d_k, bias=False)
97
+ self.W_K_cmp = nn.Linear(dim, n_kv_groups * d_k, bias=False)
98
+ self.W_V_cmp = nn.Linear(dim, n_kv_groups * d_v, bias=False)
99
+ self.W_K_sel = nn.Linear(dim, n_kv_groups * d_k, bias=False)
100
+ self.W_V_sel = nn.Linear(dim, n_kv_groups * d_v, bias=False)
101
+ self.W_K_win = nn.Linear(dim, n_kv_groups * d_k, bias=False)
102
+ self.W_V_win = nn.Linear(dim, n_kv_groups * d_v, bias=False)
103
+ # Gate MLP operates on per-group pooled Q with width d_k (matches training)
104
+ gate_hidden = max(1, d_k // 2)
105
+ self.gate_fc1 = nn.Linear(d_k, gate_hidden, bias=True)
106
+ self.gate_fc2 = nn.Linear(gate_hidden, 3, bias=True)
107
+ nn.init.xavier_uniform_(self.gate_fc2.weight, gain=0.1)
108
+ nn.init.zeros_(self.gate_fc2.bias)
109
+ self.out = nn.Linear(n_heads * d_v, dim, bias=False)
110
+
111
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
112
+ B, S, D = x.shape
113
+ h, dk, dv = self.n_heads, self.d_k, self.d_v
114
+ Q = self.W_Q(x).view(B, S, h, dk).transpose(1, 2) # [B,h,S,dk]
115
+ g = max(1, self.n_kv_groups)
116
+ r = max(1, h // g)
117
+ # Project per-group K/V then broadcast to heads
118
+ Kc_g = self.W_K_cmp(x).view(B, S, g, dk).permute(0, 2, 1, 3) # [B,g,S,dk]
119
+ Vc_g = self.W_V_cmp(x).view(B, S, g, dv).permute(0, 2, 1, 3)
120
+ Ks_g = self.W_K_sel(x).view(B, S, g, dk).permute(0, 2, 1, 3)
121
+ Vs_g = self.W_V_sel(x).view(B, S, g, dv).permute(0, 2, 1, 3)
122
+ Kw_g = self.W_K_win(x).view(B, S, g, dk).permute(0, 2, 1, 3)
123
+ Vw_g = self.W_V_win(x).view(B, S, g, dv).permute(0, 2, 1, 3)
124
+ # Broadcast groups to heads
125
+ def _bcast_to_heads(T):
126
+ return T.unsqueeze(1).expand(B, r, g, S, T.shape[-1]).reshape(B, h, S, T.shape[-1])
127
+ Kc = _bcast_to_heads(Kc_g)
128
+ Vc = _bcast_to_heads(Vc_g)
129
+ Ks = _bcast_to_heads(Ks_g)
130
+ Vs = _bcast_to_heads(Vs_g)
131
+ Kw = _bcast_to_heads(Kw_g)
132
+ Vw = _bcast_to_heads(Vw_g)
133
+
134
+ # RoPE
135
+ Qr = _rope(Q.transpose(1, 2)).transpose(1, 2)
136
+ Kc_r = _rope(Kc.transpose(1, 2)).transpose(1, 2)
137
+ Ks_r = _rope(Ks.transpose(1, 2)).transpose(1, 2)
138
+ Kw_r = _rope(Kw.transpose(1, 2)).transpose(1, 2)
139
+
140
+ # Compressed: average-pool along time
141
+ Kc_p = _avg_pool_time(Kc_r, kernel=max(1, self.stride), stride=max(1, self.stride))
142
+ Vc_p = _avg_pool_time(Vc, kernel=max(1, self.stride), stride=max(1, self.stride))
143
+ O_cmp = torch.nn.functional.scaled_dot_product_attention(Qr, Kc_p, Vc_p, is_causal=True)
144
+
145
+ # Selection: naive top-n blocks (global), enforce causal via triangular mask
146
+ scores = (Qr * Ks_r).mean(dim=-1) # [B,h,S]
147
+ blk_idx = _selection_blocks(scores, self.l_sel, self.n_sel) # [B,h,n]
148
+ n_blocks = max(1, (S + self.l_sel - 1) // self.l_sel)
149
+ keep = torch.zeros((B, h, n_blocks), device=x.device, dtype=torch.bool)
150
+ keep.scatter_(2, blk_idx, True)
151
+ keep = keep.unsqueeze(-1).expand(B, h, n_blocks, self.l_sel).reshape(B, h, -1)[:, :, :S]
152
+ logits = torch.matmul(Qr / math.sqrt(dk), Ks_r.transpose(-2, -1)) # [B,h,S,S]
153
+ tri = torch.triu(torch.ones((S, S), device=x.device, dtype=torch.bool), diagonal=1)
154
+ logits = logits.masked_fill(tri, float('-inf'))
155
+ sel_mask = torch.where(keep.unsqueeze(2).expand(B, h, S, S), torch.zeros((), device=x.device, dtype=Qr.dtype), torch.full((), float('-inf'), device=x.device, dtype=Qr.dtype))
156
+ P = torch.nn.functional.softmax(logits + sel_mask, dim=-1)
157
+ O_sel = torch.matmul(P, Vs)
158
+
159
+ # Sliding window
160
+ M = _window_mask(Qr, S, max(1, self.w))
161
+ logits_w = torch.matmul(Qr / math.sqrt(dk), Kw_r.transpose(-2, -1)) + M
162
+ P_w = torch.nn.functional.softmax(logits_w, dim=-1)
163
+ O_win = torch.matmul(P_w, Vw)
164
+
165
+ # Gate & mix: compute per-token, per-group gate from pooled Q
166
+ # Pool Q across heads within each kv-group
167
+ # Qr: [B,h,S,dk] -> reshape to [B,G,h_per_group,S,dk] then mean over h_per_group
168
+ G = max(1, self.n_kv_groups)
169
+ h_per_group = max(1, h // G)
170
+ Qg = Qr.view(B, G, h_per_group, S, dk).mean(dim=2) # [B,G,S,dk]
171
+ Qg = Qg.permute(0, 2, 1, 3) # [B,S,G,dk]
172
+ g1 = torch.nn.functional.silu(self.gate_fc1(Qg))
173
+ gate = torch.nn.functional.softmax(self.gate_fc2(g1), dim=-1) # [B,S,G,3]
174
+ gc = gate[..., 0:1].unsqueeze(-1) # [B,S,G,1,1]
175
+ gs = gate[..., 1:2].unsqueeze(-1)
176
+ gw = gate[..., 2:3].unsqueeze(-1)
177
+ # Broadcast group gates to heads within the group
178
+ # Reshape branch outputs to [B,S,G,h_per_group,dv]
179
+ Oc = O_cmp.permute(0,2,1,3).view(B, S, G, h_per_group, dv)
180
+ Os = O_sel.permute(0,2,1,3).view(B, S, G, h_per_group, dv)
181
+ Ow = O_win.permute(0,2,1,3).view(B, S, G, h_per_group, dv)
182
+ O = gc * Oc + gs * Os + gw * Ow
183
+ O = O.reshape(B, S, h, dv).permute(0, 2, 1, 3)
184
+ O = O.transpose(1, 2).reshape(B, S, h * dv)
185
+ return self.out(O)
186
+
187
+ class SimpleAttention(nn.Module):
188
+ def __init__(self, dim: int, n_heads: int, d_k: int, d_v: int) -> None:
189
+ super().__init__()
190
+ self.n_heads = n_heads
191
+ self.d_k = d_k
192
+ self.d_v = d_v
193
+ self.q_proj = nn.Linear(dim, n_heads * d_k, bias=False)
194
+ self.k_proj = nn.Linear(dim, n_heads * d_k, bias=False)
195
+ self.v_proj = nn.Linear(dim, n_heads * d_v, bias=False)
196
+ self.out = nn.Linear(n_heads * d_v, dim, bias=False)
197
+
198
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
199
+ B, S, D = x.shape
200
+ h, dk, dv = self.n_heads, self.d_k, self.d_v
201
+ q = self.q_proj(x).view(B, S, h, dk).transpose(1, 2) # [B,h,S,dk]
202
+ k = self.k_proj(x).view(B, S, h, dk).transpose(1, 2) # [B,h,S,dk]
203
+ v = self.v_proj(x).view(B, S, h, dv).transpose(1, 2) # [B,h,S,dv]
204
+ attn = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
205
+ attn = attn.transpose(1, 2).contiguous().view(B, S, h * dv)
206
+ return self.out(attn)
207
+
208
+
209
+ class SimpleBlock(nn.Module):
210
+ def __init__(self, dim: int, n_heads: int, d_k: int, d_v: int) -> None:
211
+ super().__init__()
212
+ self.norm1 = RMSNorm(dim)
213
+ self.attn = SimpleAttention(dim, n_heads, d_k, d_v)
214
+ self.norm2 = RMSNorm(dim)
215
+ self.mlp = MLP(dim)
216
+
217
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
218
+ x = x + self.attn(self.norm1(x))
219
+ x = x + self.mlp(self.norm2(x))
220
+ return x
221
+
222
+
223
+ class NSABlockRemote(nn.Module):
224
+ """Transformer block with embedded NSA attention, pre/post RMSNorm, and MLP."""
225
+ def __init__(self, dim: int, n_heads: int, n_kv_groups: int, d_k: int, d_v: int,
226
+ l: int, d: int, l_sel: int, n_sel: int, w: int) -> None:
227
+ super().__init__()
228
+ self.norm1 = RMSNorm(dim)
229
+ self.attn = EmbeddedNSAAttention(dim, n_heads, n_kv_groups, d_k, d_v, l, d, l_sel, n_sel, w)
230
+ self.norm2 = RMSNorm(dim)
231
+ self.mlp = MLP(dim)
232
+
233
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
234
+ x = x + self.attn(self.norm1(x))
235
+ x = x + self.mlp(self.norm2(x))
236
+ return x
237
+
238
+ class NSATinyLM(nn.Module):
239
+ def __init__(self, config: NSAConfig):
240
+ super().__init__()
241
+ self.config = config
242
+ self.vocab_size = int(config.vocab_size)
243
+ self.hidden_size = int(config.hidden_size)
244
+ self.num_hidden_layers = int(config.num_hidden_layers)
245
+ self.num_attention_heads = int(config.num_attention_heads)
246
+ self.n_kv_groups = int(getattr(config, "n_kv_groups", 1))
247
+ self.d_k = int(getattr(config, "d_k", self.hidden_size // self.num_attention_heads))
248
+ self.d_v = int(getattr(config, "d_v", self.hidden_size // self.num_attention_heads))
249
+ nsa = config.nsa or {}
250
+ self.l = int(nsa.get("block", 32))
251
+ self.d = int(nsa.get("stride", 16))
252
+ self.l_sel = int(nsa.get("sel_block", 64))
253
+ self.n_sel = int(nsa.get("sel_top_n", 16))
254
+ self.w = int(nsa.get("window", 512))
255
+
256
+ self.embed = nn.Embedding(self.vocab_size, self.hidden_size)
257
+ import os as _os
258
+ # Allow forcing simple fallback via env for integration tests
259
+ _force_simple = _os.getenv('NSA_REMOTE_FORCE_SIMPLE', '0').lower() in ('1','true','yes')
260
+ if not _force_simple:
261
+ # Fallback to embedded minimal NSA if vendor import failed
262
+ self.blocks = nn.ModuleList([
263
+ NSABlockRemote(
264
+ self.hidden_size,
265
+ self.num_attention_heads,
266
+ self.n_kv_groups,
267
+ self.d_k,
268
+ self.d_v,
269
+ self.l,
270
+ self.d,
271
+ self.l_sel,
272
+ self.n_sel,
273
+ self.w,
274
+ ) for _ in range(self.num_hidden_layers)
275
+ ])
276
+ else:
277
+ self.blocks = nn.ModuleList([
278
+ SimpleBlock(self.hidden_size, self.num_attention_heads, self.d_k, self.d_v)
279
+ for _ in range(self.num_hidden_layers)
280
+ ])
281
+ self.norm = nn.LayerNorm(self.hidden_size)
282
+ self.lm_head = nn.Linear(self.hidden_size, self.vocab_size, bias=False)
283
+
284
+ def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
285
+ x = self.embed(input_ids)
286
+ for blk in self.blocks:
287
+ x = blk(x)
288
+ x = self.norm(x)
289
+ logits = self.lm_head(x)
290
+ return logits
291
+
292
+
293
+ class NSAForCausalLM(PreTrainedModel, GenerationMixin):
294
+ config_class = NSAConfig
295
+ _no_split_modules = ["EmbeddedNSAAttention", "SimpleBlock"]
296
+
297
+ def __init__(self, config: NSAConfig):
298
+ super().__init__(config)
299
+ self.model = NSATinyLM(config)
300
+ self.post_init()
301
+
302
+ def get_input_embeddings(self):
303
+ return self.model.embed
304
+
305
+ def set_input_embeddings(self, new_emb):
306
+ self.model.embed = new_emb
307
+
308
+ def forward(
309
+ self,
310
+ input_ids: Optional[torch.LongTensor] = None,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ labels: Optional[torch.LongTensor] = None,
313
+ **kwargs,
314
+ ):
315
+ if input_ids is None:
316
+ raise ValueError("input_ids is required")
317
+ logits = self.model(input_ids)
318
+ loss = None
319
+ if labels is not None:
320
+ # Shift for causal LM loss
321
+ shift_logits = logits[:, :-1, :].contiguous()
322
+ shift_labels = labels[:, 1:].contiguous()
323
+ loss_fct = torch.nn.CrossEntropyLoss()
324
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
325
+ return CausalLMOutput(loss=loss, logits=logits)
326
+
327
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
328
+ # No past_key_values cache: rerun full sequence. Works everywhere, slower at decode.
329
+ return {"input_ids": input_ids, "attention_mask": kwargs.get("attention_mask", None)}