siddiVinayaka commited on
Commit
b92a420
Β·
verified Β·
1 Parent(s): 4776d9b

Release Cortex-System-One Architecture, Model Card, and Inference Suite

Browse files
Files changed (7) hide show
  1. LICENSE +17 -0
  2. Model.py +2052 -0
  3. README.md +127 -0
  4. cortex_system_one_calibration.json +87 -0
  5. inference.py +187 -0
  6. kv_cache.py +499 -0
  7. v3_modules.py +179 -0
LICENSE ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ο»ΏCreative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License
2
+
3
+ By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License ("Public License").
4
+
5
+ Section 1 -- Definitions.
6
+ a. Commercial means primarily intended for or directed towards commercial advantage or monetary compensation.
7
+ b. Derivative Works means material that is based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor.
8
+
9
+ Section 2 -- Scope.
10
+ Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
11
+ a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
12
+ b. evaluate, benchmark, and research the Licensed Material.
13
+
14
+ Section 3 -- Conditions.
15
+ a. Attribution: You must give appropriate credit to the authors of Cortex-System-one.
16
+ b. NonCommercial: You may NOT use the Licensed Material for commercial purposes.
17
+ c. NoDerivatives: If You remix, transform, or build upon the Licensed Material, You may not distribute the modified material.
Model.py ADDED
@@ -0,0 +1,2052 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Nexus β€” Simplified Transformer Architecture
4
+
5
+ =============================================
6
+
7
+ Clean 20-layer transformer with integrated neural memory.
8
+
9
+
10
+
11
+ Architecture (brain-inspired):
12
+
13
+ Embed β†’ Memory β†’ [Layers 0-6] β†’ Memory β†’ [Layers 7-13] β†’ Memory β†’ [Layers 14-19] β†’ Output
14
+
15
+ ↑ input sensory ↑ bridge processing ↑ bridge output
16
+
17
+ context update update
18
+
19
+
20
+
21
+ Components:
22
+
23
+ - GQA Attention (heads=16, kv_heads=4) + Flash Attention 2
24
+
25
+ - SwiGLU FFN (2.67Γ— expansion)
26
+
27
+ - GlobalNeuralMemory at 3 strategic bridge points
28
+
29
+ - YaRN RoPE for context extension
30
+
31
+ - MTP head for multi-token prediction training
32
+
33
+ """
34
+
35
+
36
+
37
+ import torch
38
+
39
+ import torch.nn as nn
40
+
41
+ import torch.nn.functional as F
42
+
43
+ import math
44
+
45
+ from typing import Optional, List, Tuple, Dict, Any, Union
46
+
47
+ from v3_modules import YaRNRotaryEmbedding, MTPHead, HyperConnection, RMSNorm
48
+
49
+
50
+
51
+
52
+
53
+ # ─────────────────────────────────────────────────────────────────────────────
54
+
55
+ # BASIC BUILDING BLOCKS
56
+
57
+ # ─────────────────────────────────────────────────────────────────────────────
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+ def apply_rotary_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
68
+
69
+ """Apply rotary position embeddings. x: [B, H, S, D]"""
70
+
71
+ d = x.shape[-1]
72
+
73
+ x1, x2 = x[..., : d // 2], x[..., d // 2 :]
74
+
75
+ cos = cos.unsqueeze(0).unsqueeze(0)
76
+
77
+ sin = sin.unsqueeze(0).unsqueeze(0)
78
+
79
+ return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
80
+
81
+
82
+
83
+
84
+
85
+ class SwiGLU(nn.Module):
86
+
87
+ """SwiGLU FFN β€” the standard modern FFN choice."""
88
+
89
+ def __init__(self, dim: int, hidden_dim: Optional[int] = None,
90
+
91
+ num_layers: int = 1, layer_id: int = 0):
92
+
93
+ super().__init__()
94
+
95
+ if hidden_dim is None:
96
+
97
+ hidden_dim = int(2.67 * dim)
98
+
99
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
100
+
101
+ self.w2 = nn.Linear(dim, hidden_dim, bias=False)
102
+
103
+ self.w3 = nn.Linear(hidden_dim, dim, bias=False)
104
+
105
+
106
+
107
+ self.layer_id = layer_id
108
+
109
+ self.inner_norm = RMSNorm(hidden_dim)
110
+
111
+
112
+
113
+ # Standard init for w1, w2
114
+
115
+ nn.init.normal_(self.w1.weight, std=0.02)
116
+
117
+ nn.init.normal_(self.w2.weight, std=0.02)
118
+
119
+ # Scale down the output projection to stabilize deep residuals
120
+
121
+ std_proj = 0.02 / math.sqrt(2 * num_layers)
122
+
123
+ nn.init.normal_(self.w3.weight, std=std_proj)
124
+
125
+
126
+
127
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
128
+
129
+ hidden = F.silu(self.w1(x)) * self.w2(x)
130
+
131
+ hidden_normed = self.inner_norm(hidden)
132
+
133
+ return self.w3(hidden_normed)
134
+
135
+
136
+
137
+
138
+
139
+ # ─────────────────────────────────────────────────────────────────────────────
140
+
141
+ # GQA ATTENTION β€” Grouped Query Attention with Flash Attention 2
142
+
143
+ # ─────────────────────────────────────────────────────────────────────────────
144
+
145
+
146
+
147
+ class Attention(nn.Module):
148
+
149
+ """Grouped Query Attention with KV cache and Flash Attention 2 support."""
150
+
151
+
152
+
153
+ def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4,
154
+
155
+ num_layers: int = 20, layer_id: int = 0, attn_scale: float = 1.0):
156
+
157
+ super().__init__()
158
+
159
+ self.num_heads = num_heads
160
+
161
+ self.num_kv_heads = num_kv_heads
162
+
163
+ self.head_dim = dim // num_heads
164
+
165
+ self.n_rep = num_heads // num_kv_heads
166
+
167
+
168
+
169
+ self.q = nn.Linear(dim, num_heads * self.head_dim, bias=False)
170
+
171
+ self.k = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False)
172
+
173
+ self.v = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False)
174
+
175
+ self.out = nn.Linear(num_heads * self.head_dim, dim, bias=False)
176
+
177
+
178
+
179
+ self.layer_id = layer_id
180
+
181
+ self.attn_scale = attn_scale
182
+
183
+ self.inner_norm = RMSNorm(num_heads * self.head_dim)
184
+
185
+ self.q_norm = RMSNorm(self.head_dim)
186
+
187
+ self.k_norm = RMSNorm(self.head_dim)
188
+
189
+
190
+
191
+ # Standard init for q, k, v
192
+
193
+ for layer in (self.q, self.k, self.v):
194
+
195
+ nn.init.normal_(layer.weight, std=0.02)
196
+
197
+ # Scale down output projection
198
+
199
+ std_proj = 0.02 / math.sqrt(2 * num_layers)
200
+
201
+ nn.init.normal_(self.out.weight, std=std_proj)
202
+
203
+
204
+
205
+ self._flash_available = False
206
+
207
+ try:
208
+
209
+ import flash_attn
210
+
211
+ self._flash_available = True
212
+
213
+ except ImportError:
214
+
215
+ pass
216
+
217
+
218
+
219
+ def forward(
220
+
221
+ self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
222
+
223
+ past_kv=None, use_flash: bool = False, is_causal: Optional[bool] = None,
224
+
225
+ ) -> Tuple[torch.Tensor, Any]:
226
+
227
+ B, S, D = x.shape
228
+
229
+
230
+
231
+ q = self.q(x).view(B, S, self.num_heads, self.head_dim)
232
+
233
+ k = self.k(x).view(B, S, self.num_kv_heads, self.head_dim)
234
+
235
+ v = self.v(x).view(B, S, self.num_kv_heads, self.head_dim).transpose(1, 2)
236
+
237
+
238
+
239
+ q = self.q_norm(q).transpose(1, 2)
240
+
241
+ k = self.k_norm(k).transpose(1, 2)
242
+
243
+
244
+
245
+ q = apply_rotary_emb(q, cos, sin)
246
+
247
+ k = apply_rotary_emb(k, cos, sin)
248
+
249
+
250
+
251
+ # KV cache
252
+
253
+ if past_kv is not None:
254
+
255
+ if hasattr(past_kv, 'update'):
256
+
257
+ k, v = past_kv.update(k, v)
258
+
259
+ else:
260
+
261
+ past_k, past_v = past_kv
262
+
263
+ k = torch.cat([past_k, k], dim=2)
264
+
265
+ v = torch.cat([past_v, v], dim=2)
266
+
267
+ new_past_kv = past_kv if hasattr(past_kv, 'update') else (k, v)
268
+
269
+
270
+
271
+ if is_causal is None:
272
+
273
+ is_causal = (past_kv is None)
274
+
275
+
276
+
277
+ # Flash Attention 2
278
+
279
+ if use_flash and self._flash_available:
280
+
281
+ from flash_attn import flash_attn_func
282
+
283
+ q_fa = q.transpose(1, 2)
284
+
285
+ if self.n_rep > 1:
286
+
287
+ k_fa = k.repeat_interleave(self.n_rep, dim=1).transpose(1, 2)
288
+
289
+ v_fa = v.repeat_interleave(self.n_rep, dim=1).transpose(1, 2)
290
+
291
+ else:
292
+
293
+ k_fa, v_fa = k.transpose(1, 2), v.transpose(1, 2)
294
+
295
+ orig_dtype = q_fa.dtype
296
+
297
+ scale = self.attn_scale / math.sqrt(self.head_dim)
298
+
299
+ attn = flash_attn_func(
300
+
301
+ q_fa.to(torch.bfloat16), k_fa.to(torch.bfloat16),
302
+
303
+ v_fa.to(torch.bfloat16), causal=is_causal, softmax_scale=scale,
304
+
305
+ ).to(orig_dtype).reshape(B, S, -1)
306
+
307
+ else:
308
+
309
+ # PyTorch SDPA (also very fast)
310
+
311
+ if self.n_rep > 1:
312
+
313
+ k_s = k.repeat_interleave(self.n_rep, dim=1)
314
+
315
+ v_s = v.repeat_interleave(self.n_rep, dim=1)
316
+
317
+ else:
318
+
319
+ k_s, v_s = k, v
320
+
321
+ scale = self.attn_scale / math.sqrt(self.head_dim)
322
+
323
+ attn = F.scaled_dot_product_attention(q, k_s, v_s, is_causal=is_causal, scale=scale)
324
+
325
+ attn = attn.transpose(1, 2).reshape(B, S, -1)
326
+
327
+
328
+
329
+ attn_normed = self.inner_norm(attn)
330
+
331
+ return self.out(attn_normed), new_past_kv
332
+
333
+
334
+
335
+
336
+
337
+ # ─────────────────────────────────────────────────────────────────────────────
338
+
339
+ # TRANSFORMER BLOCK β€” Attention + FFN with pre-norm residuals & HyperConnections
340
+
341
+ # ─────────────────────────────────────────────────────────────────────────────
342
+
343
+
344
+
345
+ class TransformerBlock(nn.Module):
346
+
347
+ """Single transformer layer: RMSNorm β†’ Attention β†’ RMSNorm β†’ SwiGLU."""
348
+
349
+
350
+
351
+ def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4,
352
+
353
+ num_layers: int = 20, layer_id: int = 0, use_flash: bool = False,
354
+
355
+ attn_scale: float = 1.0):
356
+
357
+ super().__init__()
358
+
359
+ self.attn_norm = RMSNorm(dim)
360
+
361
+ self.attn = Attention(dim, num_heads, num_kv_heads, num_layers, layer_id, attn_scale=attn_scale)
362
+
363
+ self.ffn_norm = RMSNorm(dim)
364
+
365
+ self.ffn = SwiGLU(dim, num_layers=num_layers, layer_id=layer_id)
366
+
367
+
368
+
369
+ # Hyper connections
370
+
371
+ self.hyper_attn = HyperConnection(dim, n_streams=2)
372
+
373
+ self.hyper_ffn = HyperConnection(dim, n_streams=2)
374
+
375
+
376
+
377
+ self.use_flash = use_flash
378
+
379
+
380
+
381
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
382
+
383
+ past_kv=None, is_causal: Optional[bool] = None) -> Tuple[torch.Tensor, Any]:
384
+
385
+ # Attention with residual
386
+
387
+ attn_out, new_kv = self.attn(
388
+
389
+ self.attn_norm(x), cos, sin, past_kv, use_flash=self.use_flash, is_causal=is_causal)
390
+
391
+ h = self.hyper_attn(x, attn_out) # learnable residual
392
+
393
+
394
+
395
+ # FFN with residual
396
+
397
+ ffn_out = self.ffn(self.ffn_norm(h))
398
+
399
+ h = self.hyper_ffn(h, ffn_out) # second learnable residual
400
+
401
+ return h, new_kv
402
+
403
+
404
+
405
+
406
+
407
+ # ─────────────────────────────────────────────────────────────────────────────
408
+
409
+ # CROSS ATTENTION β€” For Neural Memory read/write
410
+
411
+ # ─────────────────────────────────────────────────────────────────────────────
412
+
413
+
414
+
415
+ class CrossAttention(nn.Module):
416
+
417
+ """Cross-attention for memory read/write operations."""
418
+
419
+
420
+
421
+ def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4):
422
+
423
+ super().__init__()
424
+
425
+ self.num_heads = num_heads
426
+
427
+ self.num_kv_heads = num_kv_heads
428
+
429
+ self.head_dim = dim // num_heads
430
+
431
+ self.n_rep = num_heads // num_kv_heads
432
+
433
+
434
+
435
+ self.q = nn.Linear(dim, num_heads * self.head_dim, bias=False)
436
+
437
+ self.k = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False)
438
+
439
+ self.v = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False)
440
+
441
+ self.out = nn.Linear(num_heads * self.head_dim, dim, bias=False)
442
+
443
+
444
+
445
+ # Standard init for q, k, v
446
+
447
+ for layer in (self.q, self.k, self.v):
448
+
449
+ nn.init.normal_(layer.weight, std=0.02)
450
+
451
+ # Standard scale for out projection
452
+
453
+ nn.init.normal_(self.out.weight, std=0.02)
454
+
455
+
456
+
457
+ def forward(self, x: torch.Tensor, context: torch.Tensor) -> torch.Tensor:
458
+
459
+ B, S, _ = x.shape
460
+
461
+ _, S_ctx, _ = context.shape
462
+
463
+
464
+
465
+ q = self.q(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2)
466
+
467
+ k = self.k(context).view(B, S_ctx, self.num_kv_heads, self.head_dim).transpose(1, 2)
468
+
469
+ v = self.v(context).view(B, S_ctx, self.num_kv_heads, self.head_dim).transpose(1, 2)
470
+
471
+
472
+
473
+ if self.n_rep > 1:
474
+
475
+ k = k.repeat_interleave(self.n_rep, dim=1)
476
+
477
+ v = v.repeat_interleave(self.n_rep, dim=1)
478
+
479
+
480
+
481
+ attn = F.scaled_dot_product_attention(q, k, v)
482
+
483
+ return self.out(attn.transpose(1, 2).reshape(B, S, -1))
484
+
485
+
486
+
487
+
488
+
489
+ # ─────────────────────────────────────────────────────────────────────────────
490
+
491
+ # GLOBAL NEURAL MEMORY β€” Persistent memory that learns across the sequence
492
+
493
+ # ─────────────────────────────────────────────────────────────────────────────
494
+
495
+
496
+
497
+ class GlobalNeuralMemory(nn.Module):
498
+
499
+ """Persistent cognitive memory with task-driven read/write routing.
500
+
501
+
502
+
503
+ Loss v2 does not impose a generic "memory must be used" or diversity target.
504
+
505
+ Instead, the downstream decision objective supplies utility signals for the
506
+
507
+ read intervention, the memory write, and final reflection.
508
+
509
+ """
510
+
511
+ def __init__(self, dim: int, num_slots: int = 128, heads: int = 16,
512
+
513
+ retain_floor: float = 0.5, write_scale: float = 0.3,
514
+
515
+ role: str = "generic"):
516
+
517
+ super().__init__()
518
+
519
+ self.num_slots = num_slots
520
+
521
+ self.dim = dim
522
+
523
+ self.role = role
524
+
525
+
526
+
527
+ self.memory_init = nn.Parameter(torch.randn(num_slots, dim) * 0.02)
528
+
529
+ self.norm_x = RMSNorm(dim)
530
+
531
+ self.norm_mem = RMSNorm(dim)
532
+
533
+ self.mem_norm = RMSNorm(dim)
534
+
535
+
536
+
537
+ self.read_attn = CrossAttention(dim, heads, max(1, heads // 4))
538
+
539
+ self.write_attn = CrossAttention(dim, heads, max(1, heads // 4))
540
+
541
+
542
+
543
+ # Read router: its gate is supervised by downstream task utility.
544
+
545
+ self.read_gate = nn.Sequential(
546
+
547
+ nn.Linear(dim * 2, dim),
548
+
549
+ nn.Sigmoid(),
550
+
551
+ )
552
+
553
+ nn.init.zeros_(self.read_gate[0].weight)
554
+
555
+ nn.init.constant_(self.read_gate[0].bias, 0.0)
556
+
557
+
558
+
559
+ self.write_scale = write_scale
560
+
561
+ self.retain_floor = retain_floor
562
+
563
+
564
+
565
+ # Write admission router: its gate is supervised by future-example
566
+
567
+ # utility. Slot contents are trained directly through downstream loss.
568
+
569
+ self.affinity_gate = nn.Sequential(
570
+
571
+ nn.Linear(dim * 2, dim),
572
+
573
+ nn.Sigmoid(),
574
+
575
+ )
576
+
577
+ nn.init.zeros_(self.affinity_gate[0].weight)
578
+
579
+ nn.init.constant_(self.affinity_gate[0].bias, 0.0)
580
+
581
+
582
+
583
+ # Retention is learned through the task gradient through new_memory.
584
+
585
+ self.gate = nn.Sequential(
586
+
587
+ nn.Linear(dim, dim),
588
+
589
+ nn.Sigmoid(),
590
+
591
+ )
592
+
593
+ nn.init.zeros_(self.gate[0].weight)
594
+
595
+ target_retention = min(retain_floor + 0.3, 0.9)
596
+
597
+ if retain_floor == 0.3:
598
+
599
+ target_retention = 0.6
600
+
601
+ elif retain_floor == 0.5:
602
+
603
+ target_retention = 0.7
604
+
605
+ elif retain_floor == 0.7:
606
+
607
+ target_retention = 0.8
608
+
609
+ bias_val = math.log(target_retention / (1.0 - target_retention))
610
+
611
+ nn.init.constant_(self.gate[0].bias, bias_val)
612
+
613
+
614
+
615
+ self.last_read_gate: Optional[torch.Tensor] = None
616
+
617
+ self.last_write_mask: Optional[torch.Tensor] = None
618
+
619
+
620
+
621
+ def init_memory(self, batch_size: int, device: torch.device) -> torch.Tensor:
622
+
623
+ return self.memory_init.unsqueeze(0).expand(batch_size, -1, -1).clone()
624
+
625
+
626
+
627
+ def forward(
628
+
629
+ self,
630
+
631
+ x: torch.Tensor,
632
+
633
+ memory_state: torch.Tensor,
634
+
635
+ domain_id: Optional[int] = None,
636
+
637
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
638
+
639
+ x_norm = self.norm_x(x)
640
+
641
+ memory_state = memory_state + (self.memory_init * 0.0).unsqueeze(0)
642
+
643
+ mem_norm = self.norm_mem(memory_state)
644
+
645
+
646
+
647
+ # Read intervention: gated additive residual injection from memory.
648
+
649
+ read_out = self.read_attn(x_norm, mem_norm)
650
+
651
+ gate = self.read_gate(torch.cat([x, read_out], dim=-1))
652
+
653
+ read_delta = gate * read_out
654
+
655
+ x_new = x + read_delta
656
+
657
+ if not (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling()):
658
+
659
+ self.last_read_gate = gate.detach()
660
+
661
+
662
+
663
+ # Write intervention.
664
+
665
+ mem_query = mem_norm + self.memory_init.unsqueeze(0)
666
+
667
+ mem_update = self.write_attn(mem_query, x_norm)
668
+
669
+ affinity = self.affinity_gate(torch.cat([mem_norm, mem_update], dim=-1))
670
+
671
+
672
+
673
+ # Unified Cognitive Memory:
674
+
675
+ # Full capacity across all slots without artificial domain quadrant walls,
676
+
677
+ # exactly as trained during pretraining (30B tokens / 153k steps).
678
+
679
+ forget = self.gate(memory_state).clamp(self.retain_floor, 0.95)
680
+
681
+ candidate = forget * memory_state + (1.0 - forget) * (self.write_scale * mem_update)
682
+
683
+ new_memory = affinity * candidate + (1.0 - affinity) * memory_state
684
+
685
+ new_memory = self.mem_norm(new_memory)
686
+
687
+ if not (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling()):
688
+
689
+ self.last_write_mask = affinity.detach()
690
+
691
+
692
+
693
+ lb_loss = torch.zeros((), device=x.device, dtype=x.dtype)
694
+
695
+ return x_new, new_memory, lb_loss, gate, affinity, read_delta, forget
696
+
697
+
698
+
699
+
700
+
701
+ # ─────────────────────────────────────────────────────────────────────────────
702
+
703
+ # KV CACHE β€” Simple flat KV cache for inference
704
+
705
+ # ─────────────────────────────────────────────────────────────────────────────
706
+
707
+
708
+
709
+ class KVCache:
710
+
711
+ """Simple KV cache for autoregressive inference."""
712
+
713
+
714
+
715
+ def __init__(self, num_layers: int):
716
+
717
+ self.num_layers = num_layers
718
+
719
+ self.kvs: List[Any] = [None] * num_layers
720
+
721
+
722
+
723
+ def get_past_len(self) -> int:
724
+
725
+ """Get the sequence length of cached keys."""
726
+
727
+ for kv in self.kvs:
728
+
729
+ if kv is not None:
730
+
731
+ if hasattr(kv, 'seq_len'):
732
+
733
+ return kv.seq_len
734
+
735
+ return kv[0].shape[2]
736
+
737
+ return 0
738
+
739
+
740
+
741
+ def update(self, layer_idx: int, new_kv):
742
+
743
+ self.kvs[layer_idx] = new_kv
744
+
745
+
746
+
747
+ def reset(self):
748
+
749
+ self.kvs = [None] * self.num_layers
750
+
751
+
752
+
753
+
754
+
755
+
756
+
757
+ # ─────────────────────────────────────────────────────────────────────────────
758
+
759
+ # DYNAMIC SYSTEM 1 DECISION HEAD
760
+
761
+ # ─────────────────────────────────────────────────────────────────────────────
762
+
763
+
764
+
765
+ # ---------------------------------------------------------------------------
766
+
767
+ # Dynamic Decision Head
768
+
769
+ # ---------------------------------------------------------------------------
770
+
771
+
772
+
773
+
774
+
775
+ class DynamicDecisionHead(nn.Module):
776
+ """
777
+ Laya-Aligned Non-Causal Transformer Decision Head with GELU Non-Linear Scorer.
778
+ Clean, minimal, high-capacity, zero artificial heuristics:
779
+ 1. Task & Domain Conditioning: type_emb(3, D) + domain_emb(16, D)
780
+ 2. Non-Causal Bidirectional Comparator: [Q_cond, C_1, ..., C_K] -> TransformerEncoderLayer
781
+ 3. Exact Laya Non-Linear Scorer: LayerNorm -> Linear(D, D) -> GELU -> Linear(D, 1)
782
+ Zero memory cross-attention, zero artificial scaling, zero distractor subtraction heuristics.
783
+ """
784
+
785
+ def __init__(
786
+ self,
787
+ dim: int = 1280,
788
+ num_layers: int = 2,
789
+ heads: int = 16,
790
+ dropout: float = 0.10,
791
+ **kwargs,
792
+ ):
793
+ super().__init__()
794
+ self.dim = dim
795
+ self.num_layers = num_layers if num_layers is not None else 2
796
+
797
+ # 1. Task & Domain Conditioning
798
+ self.type_emb = nn.Embedding(3, dim)
799
+ nn.init.normal_(self.type_emb.weight, std=0.02)
800
+ self.domain_emb = nn.Embedding(16, dim)
801
+ nn.init.normal_(self.domain_emb.weight, std=0.02)
802
+
803
+ # 2. 2-Layer Non-Causal Bidirectional Transformer Comparator (Exact Laya head_layers=2)
804
+ if self.num_layers > 0:
805
+ encoder_layer = nn.TransformerEncoderLayer(
806
+ d_model=dim,
807
+ nhead=heads,
808
+ dim_feedforward=4 * dim,
809
+ dropout=dropout,
810
+ batch_first=True,
811
+ norm_first=True, # Pre-LN
812
+ )
813
+ self.transformer = nn.TransformerEncoder(
814
+ encoder_layer,
815
+ num_layers=self.num_layers,
816
+ enable_nested_tensor=False,
817
+ )
818
+ for layer in self.transformer.layers:
819
+ nn.init.orthogonal_(layer.self_attn.out_proj.weight, gain=1.0)
820
+ nn.init.orthogonal_(layer.linear1.weight, gain=1.0)
821
+ nn.init.orthogonal_(layer.linear2.weight, gain=1.0)
822
+ else:
823
+ self.transformer = None
824
+
825
+ # 3. Causal Context Fusion (Solves Causal Option Blindness)
826
+ # Pre-LN normalizations and projection to inject global sequence summary Q
827
+ # into candidate vectors before entering comparator and scoring.
828
+ self.query_proj = nn.Linear(dim, dim)
829
+ nn.init.orthogonal_(self.query_proj.weight, gain=1.0)
830
+ nn.init.zeros_(self.query_proj.bias)
831
+ self.cand_norm = nn.LayerNorm(dim)
832
+ self.query_norm = nn.LayerNorm(dim)
833
+ self.fusion_norm = nn.LayerNorm(dim)
834
+
835
+ # 4. Exact Laya Non-Linear Scorer (LayerNorm -> Linear(D, D) -> GELU -> Linear(D, 1), NO DROPOUT)
836
+ self.scorer = nn.Sequential(
837
+ nn.LayerNorm(dim),
838
+ nn.Linear(dim, dim),
839
+ nn.GELU(),
840
+ nn.Linear(dim, 1),
841
+ )
842
+ for m in self.scorer.modules():
843
+ if isinstance(m, nn.Linear):
844
+ nn.init.orthogonal_(m.weight, gain=1.0)
845
+ if m.bias is not None:
846
+ nn.init.zeros_(m.bias)
847
+
848
+ def forward(
849
+ self,
850
+ global_context: Optional[torch.Tensor] = None,
851
+ candidate_hidden: Optional[torch.Tensor] = None,
852
+ candidate_mask: Optional[torch.Tensor] = None,
853
+ primitive_id: Optional[Any] = None,
854
+ domain_id: Optional[Any] = None,
855
+ sequence_context: Optional[torch.Tensor] = None,
856
+ candidate_positions: Optional[torch.Tensor] = None,
857
+ return_ablated: bool = False,
858
+ **kwargs,
859
+ ) -> Any:
860
+ device = candidate_hidden.device if candidate_hidden is not None else sequence_context.device
861
+ B = candidate_hidden.size(0) if candidate_hidden is not None else sequence_context.size(0)
862
+
863
+ target_dtype = sequence_context.dtype if sequence_context is not None else (candidate_hidden.dtype if candidate_hidden is not None else torch.float32)
864
+ if primitive_id is not None:
865
+ p_idx = primitive_id if isinstance(primitive_id, torch.Tensor) else torch.tensor([primitive_id] * B, device=device)
866
+ p_idx = p_idx.to(device=device, dtype=torch.long).view(-1).clamp(0, 2)
867
+ if p_idx.numel() == 1 and B > 1:
868
+ p_idx = p_idx.expand(B)
869
+ t_emb = self.type_emb(p_idx)
870
+ else:
871
+ t_emb = torch.zeros((B, self.dim), device=device, dtype=target_dtype)
872
+
873
+ if domain_id is not None:
874
+ d_idx = domain_id if isinstance(domain_id, torch.Tensor) else torch.tensor([domain_id] * B, device=device)
875
+ d_idx = d_idx.to(device=device, dtype=torch.long).view(-1).clamp(0, 15)
876
+ if d_idx.numel() == 1 and B > 1:
877
+ d_idx = d_idx.expand(B)
878
+ d_emb = self.domain_emb(d_idx)
879
+ else:
880
+ d_emb = torch.zeros((B, self.dim), device=device, dtype=target_dtype)
881
+
882
+
883
+ cond = t_emb + d_emb # [B, D]
884
+
885
+ # 2. Extract Candidate representations via vectorized mean-pooling if not provided
886
+ if candidate_hidden is None:
887
+ if sequence_context is not None and candidate_positions is not None:
888
+ if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2:
889
+ prefix = torch.cat(
890
+ [
891
+ torch.zeros(B, 1, sequence_context.size(-1), device=device, dtype=sequence_context.dtype),
892
+ torch.cumsum(sequence_context, dim=1),
893
+ ],
894
+ dim=1,
895
+ )
896
+ s = candidate_positions[:, :, 0].clamp(0, sequence_context.size(1) - 1)
897
+ e = candidate_positions[:, :, 1].clamp(0, sequence_context.size(1) - 1)
898
+ e = torch.maximum(s, e)
899
+ s_idx = s.unsqueeze(-1).expand(-1, -1, sequence_context.size(-1))
900
+ e_idx = (e + 1).unsqueeze(-1).expand(-1, -1, sequence_context.size(-1))
901
+ sum_s = torch.gather(prefix, dim=1, index=s_idx)
902
+ sum_e = torch.gather(prefix, dim=1, index=e_idx)
903
+ counts = (e - s + 1).unsqueeze(-1).float().clamp_min(1.0)
904
+ candidate_hidden = ((sum_e - sum_s) / counts).to(sequence_context.dtype)
905
+ else:
906
+ pos_idx = candidate_positions[:, :, -1] if candidate_positions.ndim == 3 else candidate_positions
907
+ pos_idx = pos_idx.clamp(0, sequence_context.size(1) - 1)
908
+ idx = pos_idx.unsqueeze(-1).expand(-1, -1, sequence_context.size(-1))
909
+ candidate_hidden = torch.gather(sequence_context, dim=1, index=idx)
910
+ else:
911
+ raise ValueError("candidate_hidden or (sequence_context and candidate_positions) must be provided.")
912
+
913
+ B, K, D = candidate_hidden.shape
914
+
915
+ if global_context is None:
916
+ global_context = sequence_context[:, -1, :] if sequence_context is not None else candidate_hidden.mean(dim=1)
917
+
918
+ # 3. Solves Causal Option Blindness:
919
+ # Candidate k was extracted from option k's token span in the causal autoregressive backbone.
920
+ # Early options (e.g. Option A) never attended to later options (B, C, D) in the backbone.
921
+ # Here, we inject the contextualized query Q (the final sequence token which HAS causally
922
+ # attended to the entire state, instructions, and all options) into each candidate vector:
923
+ Q_norm = self.query_norm(global_context + cond) # [B, D]
924
+ Q_proj = self.query_proj(Q_norm).unsqueeze(1) # [B, 1, D]
925
+ cand_injected = self.cand_norm(candidate_hidden + Q_proj + cond.unsqueeze(1)) # [B, K, D]
926
+
927
+ # 4. Form interaction sequence [Q_cond, C_1_cond, C_2_cond, ..., C_K_cond]
928
+ tokens = torch.cat([Q_norm.unsqueeze(1), cand_injected], dim=1) # [B, 1 + K, D]
929
+
930
+ # 5. Bidirectional Non-Causal Transformer Comparator (Exact Laya head_layers=2)
931
+ if self.transformer is not None:
932
+ if candidate_mask is not None:
933
+ q_mask = torch.zeros((B, 1), dtype=torch.bool, device=device)
934
+ pad_mask = torch.cat([q_mask, ~candidate_mask.bool().to(device)], dim=1)
935
+ else:
936
+ pad_mask = None
937
+ tokens_out = self.transformer(tokens, src_key_padding_mask=pad_mask)
938
+ Q_out = tokens_out[:, 0:1, :] # [B, 1, D]
939
+ cand_out = tokens_out[:, 1:, :] # [B, K, D]
940
+ else:
941
+ Q_out = Q_norm.unsqueeze(1)
942
+ cand_out = cand_injected
943
+
944
+ # 6. Contrastive Query-Candidate Scorer (Contextual Query Fused with Candidate)
945
+ # Evaluates the interaction between the contextualized query Q_out and each candidate cand_out
946
+ fused_cand = self.fusion_norm(cand_out + Q_out) # [B, K, D]
947
+ logits = self.scorer(fused_cand).squeeze(-1).float() # [B, K]
948
+
949
+ if candidate_mask is not None:
950
+ logits = logits.masked_fill(~candidate_mask.bool().to(device), -1e4)
951
+
952
+ if return_ablated:
953
+ return logits, logits
954
+
955
+ return logits
956
+
957
+
958
+ # Alias for backwards compatibility
959
+ StreamlinedDynamicDecisionHead = DynamicDecisionHead
960
+
961
+
962
+
963
+
964
+
965
+ # ─────────────────────────────────────────────────────────────────────────────
966
+
967
+ # NEXUS β€” The Main Model
968
+
969
+ # ─────────────────────────────────────────────────────────────────────────────
970
+
971
+
972
+
973
+ class Nexus(nn.Module):
974
+
975
+ """Nexus β€” Clean transformer with neural memory.
976
+
977
+
978
+
979
+ Architecture:
980
+
981
+ Embed β†’ Memory₁ β†’ [Layer 0-6] β†’ Memoryβ‚‚ β†’ [Layer 7-13] β†’ Memory₃ β†’ [Layer 14-19] β†’ Head
982
+
983
+
984
+
985
+ Brain analogy:
986
+
987
+ Memory₁ = "What do I already know about this input?" (hippocampal retrieval)
988
+
989
+ Layers 0-6 = Sensory cortex (perception, pattern recognition)
990
+
991
+ Memoryβ‚‚ = "Update what I've learned from perception" (hippocampal encoding)
992
+
993
+ Layers 7-13 = Association cortex (reasoning, integration)
994
+
995
+ Memory₃ = "Consolidate reasoning into memory" (hippocampal consolidation)
996
+
997
+ Layers 14-19 = Motor cortex (output generation)
998
+
999
+ """
1000
+
1001
+
1002
+
1003
+ def __init__(
1004
+
1005
+ self,
1006
+
1007
+ vocab_size: int = 100_277,
1008
+
1009
+ dim: int = 1280,
1010
+
1011
+ heads: int = 16,
1012
+
1013
+ kv_heads: int = 4,
1014
+
1015
+ num_layers: int = 20,
1016
+
1017
+ memory_slots: int = 128,
1018
+
1019
+ use_flash: bool = False,
1020
+
1021
+ mtp_depths: int = 1,
1022
+
1023
+ decision_layers: int = 2,
1024
+ decision_dropout: float = 0.10,
1025
+
1026
+ ):
1027
+
1028
+ super().__init__()
1029
+
1030
+ self.dim = dim
1031
+
1032
+ self.heads = heads
1033
+
1034
+ self.num_layers = num_layers
1035
+
1036
+
1037
+
1038
+ # ── Embedding ────────────────────────────────────────────────────────
1039
+
1040
+ self.embed = nn.Embedding(vocab_size, dim)
1041
+
1042
+ nn.init.normal_(self.embed.weight, std=0.01)
1043
+
1044
+
1045
+
1046
+ # Domain Conditioning for Core Model & Neural Memory
1047
+
1048
+ self.domain_emb = nn.Embedding(16, dim)
1049
+
1050
+ nn.init.normal_(self.domain_emb.weight, std=0.02)
1051
+
1052
+
1053
+
1054
+ head_dim = dim // heads
1055
+
1056
+ self.rope = YaRNRotaryEmbedding(
1057
+
1058
+ head_dim, max_seq_len=8192,
1059
+
1060
+ original_max_len=2048, yarn_scale=8.0)
1061
+
1062
+
1063
+
1064
+ # ── Transformer Layers ───────────────────────────────────────────────
1065
+
1066
+ self.layers = nn.ModuleList([
1067
+
1068
+ TransformerBlock(dim, heads, kv_heads, num_layers, i, use_flash, attn_scale=self.rope.attn_scale)
1069
+
1070
+ for i in range(num_layers)
1071
+
1072
+ ])
1073
+
1074
+
1075
+
1076
+ # ── Neural Memory (called at 3 strategic bridge points) ──────────────
1077
+
1078
+ # Step 9: Hierarchical Memory Specialization
1079
+
1080
+ memory_configs = [
1081
+
1082
+ {"slots": 32, "retain_floor": 0.3, "write_scale": 0.5, "role": "lexical"},
1083
+
1084
+ {"slots": 64, "retain_floor": 0.5, "write_scale": 0.3, "role": "semantic"},
1085
+
1086
+ {"slots": 128, "retain_floor": 0.7, "write_scale": 0.35, "role": "reasoning"},
1087
+
1088
+ ]
1089
+
1090
+ self.memory = nn.ModuleList([
1091
+
1092
+ GlobalNeuralMemory(
1093
+
1094
+ dim,
1095
+
1096
+ num_slots=cfg["slots"],
1097
+
1098
+ heads=heads,
1099
+
1100
+ retain_floor=cfg["retain_floor"],
1101
+
1102
+ write_scale=cfg["write_scale"],
1103
+
1104
+ role=cfg["role"]
1105
+
1106
+ )
1107
+
1108
+ for cfg in memory_configs
1109
+
1110
+ ])
1111
+
1112
+
1113
+
1114
+ # Legacy module retained only for pure-checkpoint compatibility.
1115
+
1116
+ # It is frozen and unused by Nexus Loss v2.
1117
+
1118
+ self.memory_predictor = nn.Linear(dim, dim, bias=False)
1119
+
1120
+ nn.init.normal_(self.memory_predictor.weight, std=0.01)
1121
+
1122
+
1123
+
1124
+ # Memory bridge schedule: after which layers to call memory
1125
+
1126
+ # Bridges shifted slightly deeper: [3, 10, 17]
1127
+
1128
+ self.memory_bridges = [3, 10, 17]
1129
+
1130
+
1131
+
1132
+ # ── MTP Head ────────────────────────────────────────────────────────
1133
+
1134
+ self.mtp_heads = nn.ModuleList([MTPHead(dim) for _ in range(mtp_depths)])
1135
+
1136
+
1137
+
1138
+ # ── Output ──────────────────────────────────────────────────────────
1139
+
1140
+ self.norm = RMSNorm(dim)
1141
+
1142
+
1143
+
1144
+ # Output Reflection: lets the final layers read the newly written memory
1145
+
1146
+ # This ties the memory writing mechanism to the LM loss.
1147
+
1148
+ self.final_memory_read = CrossAttention(dim, heads, max(1, heads // 4))
1149
+
1150
+ self.final_memory_scale = nn.Parameter(torch.tensor(0.50))
1151
+
1152
+ self.final_memory_gate = nn.Linear(dim, 1)
1153
+
1154
+ nn.init.zeros_(self.final_memory_gate.weight)
1155
+
1156
+ nn.init.constant_(self.final_memory_gate.bias, 0.0) # Starts at gate=0.5
1157
+
1158
+
1159
+
1160
+ self.head = nn.Linear(dim, vocab_size, bias=False)
1161
+
1162
+ self.head.weight = self.embed.weight # Weight tying
1163
+
1164
+
1165
+
1166
+ # --- Dynamic System 1 Decision Head ---
1167
+
1168
+ # Candidate-count agnostic. It scores an arbitrary number K of
1169
+
1170
+ # candidate representations, rather than hard-coding 5 classes.
1171
+
1172
+ self.system1_head = DynamicDecisionHead(dim, num_layers=decision_layers, dropout=decision_dropout)
1173
+
1174
+ # Attention-weighted candidate span pooling: zero-initialized for exact mean-pooling equivalence at step 0
1175
+ self.span_attn = nn.Linear(dim, 1, bias=False)
1176
+ nn.init.zeros_(self.span_attn.weight)
1177
+
1178
+ self.use_system1_head = False
1179
+
1180
+
1181
+
1182
+ # Gradient checkpointing toggle (reduces activation VRAM by 85-90% during training)
1183
+
1184
+ self.gradient_checkpointing = True
1185
+
1186
+
1187
+
1188
+ # ── Print summary ───────────────────────────────────────────────────
1189
+
1190
+ total_params = sum(p.numel() for p in self.parameters())
1191
+
1192
+ print(f"[OK] Nexus initialized: {total_params:,} parameters ({total_params/1e9:.3f}B)")
1193
+
1194
+ print(f" Architecture: {num_layers} layers (dim={dim}, heads={heads}, kv_heads={kv_heads})")
1195
+
1196
+ print(f" Memory: {[c['slots'] for c in memory_configs]} slots Γ— {dim}d at bridges {self.memory_bridges}")
1197
+
1198
+ print(f" FFN: SwiGLU ({int(2.67 * dim)}d hidden)")
1199
+
1200
+ print(f" MTP Heads: {mtp_depths}")
1201
+
1202
+ attn_desc = "FlashAttention-2 (Tri Dao)" if use_flash else "PyTorch Fused SDPA (Mem-Efficient Kernel for T4/SM75)"
1203
+
1204
+ print(f" Attention: {attn_desc}")
1205
+
1206
+
1207
+
1208
+ def project_logits(self, hidden: torch.Tensor) -> torch.Tensor:
1209
+
1210
+ return self.head(self.norm(hidden))
1211
+
1212
+
1213
+
1214
+ def forward(
1215
+
1216
+ self,
1217
+
1218
+ x: torch.Tensor,
1219
+
1220
+ memory_state: Optional[List[torch.Tensor]] = None,
1221
+
1222
+ kv_cache: Optional[KVCache] = None,
1223
+
1224
+ targets: Optional[torch.Tensor] = None,
1225
+
1226
+ return_intermediates: bool = False,
1227
+
1228
+ last_token_only: bool = False,
1229
+
1230
+ candidate_positions: Optional[torch.Tensor] = None,
1231
+
1232
+ candidate_mask: Optional[torch.Tensor] = None,
1233
+
1234
+ seq_lens: Optional[torch.Tensor] = None,
1235
+
1236
+ domain_id: Optional[int] = None,
1237
+
1238
+ primitive_id: Optional[Any] = None,
1239
+
1240
+ task_id: Optional[Any] = None,
1241
+
1242
+ disable_memory: Optional[bool] = None,
1243
+
1244
+ is_causal: Optional[bool] = None,
1245
+
1246
+ memory_only: bool = False,
1247
+
1248
+ **kwargs: Any,
1249
+
1250
+ ) -> Any:
1251
+
1252
+ B, S = x.shape
1253
+
1254
+ h = self.embed(x)
1255
+
1256
+
1257
+
1258
+ # ── Domain Conditioning for Core Model & Neural Memory ───────────────
1259
+
1260
+ if domain_id is not None:
1261
+
1262
+ if isinstance(domain_id, int):
1263
+
1264
+ d_idx = torch.tensor([domain_id] * B, device=x.device, dtype=torch.long)
1265
+
1266
+ elif isinstance(domain_id, torch.Tensor):
1267
+
1268
+ d_idx = domain_id.to(x.device, dtype=torch.long).view(-1)
1269
+
1270
+ if d_idx.numel() == 1 and B > 1:
1271
+
1272
+ d_idx = d_idx.expand(B)
1273
+
1274
+ else:
1275
+
1276
+ d_idx = torch.zeros(B, device=x.device, dtype=torch.long)
1277
+
1278
+ d_emb = self.domain_emb(d_idx.clamp(0, 15)).unsqueeze(1) # [B, 1, D]
1279
+
1280
+ h = h + d_emb
1281
+
1282
+
1283
+
1284
+ # ── Memory Bypass Configuration ─────────────────────────────────────
1285
+
1286
+ disable_mem = disable_memory if disable_memory is not None else getattr(self, "disable_memory", False)
1287
+
1288
+
1289
+
1290
+ # ── Attention Causal Mode ───────────────────────────────────────────
1291
+
1292
+ # Native causal masking matching 30B-token pretraining inductive bias.
1293
+
1294
+ if is_causal is not None:
1295
+
1296
+ causal_mode = is_causal
1297
+
1298
+ else:
1299
+
1300
+ causal_mode = (kv_cache is None)
1301
+
1302
+
1303
+
1304
+ # ── RoPE ────────────────────────────────────────────────────────────
1305
+
1306
+ past_len = kv_cache.get_past_len() if kv_cache else 0
1307
+
1308
+ total_len = past_len + S
1309
+
1310
+ cos_full, sin_full = self.rope(h, total_len)
1311
+
1312
+ cos = cos_full[past_len:total_len]
1313
+
1314
+ sin = sin_full[past_len:total_len]
1315
+
1316
+
1317
+
1318
+ # ── Initialize memory ──────────────────────────────────────────────
1319
+
1320
+ if not disable_mem and memory_state is None:
1321
+
1322
+ memory_state = [mem.init_memory(B, h.device) for mem in self.memory]
1323
+
1324
+
1325
+
1326
+ # ── Forward through layers with memory bridges ─────────────────────
1327
+
1328
+ bridge_idx = 0
1329
+
1330
+ new_memory_state = []
1331
+
1332
+ read_gates = []
1333
+
1334
+ read_deltas = []
1335
+
1336
+ write_masks = []
1337
+
1338
+ forget_gates = []
1339
+
1340
+
1341
+
1342
+ memory_deltas = []
1343
+
1344
+ for i, layer in enumerate(self.layers):
1345
+
1346
+ # Memory bridge BEFORE this layer group starts.
1347
+
1348
+ if not disable_mem and i in self.memory_bridges:
1349
+
1350
+ old_mem = memory_state[bridge_idx]
1351
+
1352
+ h, m_state, lb_loss, r_gate, affinity, read_delta, f_gate = self.memory[bridge_idx](
1353
+
1354
+ h, old_mem, domain_id=domain_id
1355
+
1356
+ )
1357
+
1358
+ new_memory_state.append(m_state)
1359
+
1360
+ read_gates.append(r_gate)
1361
+
1362
+ read_deltas.append(read_delta)
1363
+
1364
+ write_masks.append(affinity)
1365
+
1366
+ forget_gates.append(f_gate)
1367
+
1368
+
1369
+
1370
+ memory_deltas.append(m_state - old_mem)
1371
+
1372
+ bridge_idx += 1
1373
+
1374
+
1375
+
1376
+ # Transformer layer (with activation checkpointing during training to reduce VRAM by 85-90%)
1377
+
1378
+ pkv = kv_cache.kvs[i] if kv_cache else None
1379
+
1380
+
1381
+
1382
+ if self.training and kv_cache is None and getattr(self, "gradient_checkpointing", True):
1383
+
1384
+ from torch.utils.checkpoint import checkpoint
1385
+
1386
+ def _create_layer_forward(layer_module, causal_flag):
1387
+
1388
+ def _layer_forward(*inputs):
1389
+
1390
+ out_hidden, _ = layer_module(*inputs, is_causal=causal_flag)
1391
+
1392
+ return out_hidden
1393
+
1394
+ return _layer_forward
1395
+
1396
+
1397
+
1398
+ h = checkpoint(_create_layer_forward(layer, causal_mode), h, cos, sin, None, use_reentrant=False)
1399
+
1400
+ new_kv = None
1401
+
1402
+ else:
1403
+
1404
+ h, new_kv = layer(h, cos, sin, pkv, is_causal=causal_mode)
1405
+
1406
+
1407
+
1408
+ if kv_cache:
1409
+
1410
+ kv_cache.update(i, new_kv)
1411
+
1412
+
1413
+
1414
+ # ── Output / Reflection ───────────────────────────────────────────
1415
+
1416
+ h_normed = self.norm(h)
1417
+
1418
+
1419
+
1420
+ candidate_hidden = None
1421
+ candidate_hidden_pre_reflection = None
1422
+
1423
+ reflection = None
1424
+
1425
+ reflection_gate = None
1426
+
1427
+ reflection_delta = None
1428
+
1429
+ memory_context = None
1430
+
1431
+ reflection_cand = None
1432
+
1433
+ mem_logits = None
1434
+
1435
+ refl_logits = None
1436
+
1437
+ global_context = None
1438
+
1439
+ ablated_logits = None
1440
+
1441
+
1442
+
1443
+ pre_reflection_h_normed = h_normed
1444
+ if not disable_mem and new_memory_state:
1445
+
1446
+ # Reflection reads the CURRENT example's freshly written memory.
1447
+
1448
+ all_mem = torch.cat(new_memory_state, dim=1)
1449
+
1450
+ reflection = self.final_memory_read(h_normed, all_mem)
1451
+
1452
+ reflection_gate = 0.20 + 0.80 * torch.sigmoid(self.final_memory_gate(h_normed))
1453
+
1454
+ reflection_delta = reflection_gate * self.final_memory_scale * reflection
1455
+
1456
+ h = h + reflection_delta
1457
+
1458
+ h_normed = self.norm(h)
1459
+
1460
+
1461
+
1462
+ if (getattr(self, "use_system1_head", False) and not memory_only) or candidate_positions is not None:
1463
+
1464
+ if candidate_positions is None:
1465
+
1466
+ raise ValueError(
1467
+
1468
+ "Dynamic System 1 head requires candidate_positions "
1469
+
1470
+ "with shape [B,K]. Pass one position per option."
1471
+
1472
+ )
1473
+
1474
+
1475
+
1476
+ if candidate_positions.ndim not in (2, 3):
1477
+
1478
+ raise ValueError(
1479
+
1480
+ "candidate_positions must have shape [B,K] (single token) or [B,K,2] (spans), "
1481
+
1482
+ f"got {tuple(candidate_positions.shape)}"
1483
+
1484
+ )
1485
+
1486
+
1487
+
1488
+ if candidate_positions.shape[0] != B:
1489
+
1490
+ raise ValueError(
1491
+
1492
+ "candidate_positions batch dimension must match input batch: "
1493
+
1494
+ f"{candidate_positions.shape[0]} vs {B}"
1495
+
1496
+ )
1497
+
1498
+
1499
+
1500
+ if candidate_positions.dtype != torch.long:
1501
+
1502
+ candidate_positions = candidate_positions.long()
1503
+
1504
+
1505
+
1506
+ if candidate_positions.device != h_normed.device:
1507
+
1508
+ candidate_positions = candidate_positions.to(h_normed.device)
1509
+
1510
+
1511
+
1512
+ # Vectorized candidate extraction on GPU:
1513
+
1514
+ # When candidate_positions is [B, K, 2] (spans), compute exact span mean-pooling via prefix sum.
1515
+
1516
+ # When candidate_positions is [B, K] (single tokens), gather directly.
1517
+
1518
+ if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2:
1519
+
1520
+ # Attention-Weighted Candidate Span Extraction:
1521
+ # Weights individual tokens in each option span via learned attention.
1522
+ # Zero-initialized at step 0 to produce uniform 1/L weights (exact zero-drift match to mean pooling).
1523
+ # During training, concentrates candidate representations onto decisive action verbs and condition clauses.
1524
+ s = candidate_positions[:, :, 0].clamp(0, h_normed.size(1) - 1)
1525
+ e = candidate_positions[:, :, 1].clamp(0, h_normed.size(1) - 1)
1526
+ e = torch.maximum(s, e)
1527
+
1528
+ s_idx = s.unsqueeze(-1).expand(-1, -1, h_normed.size(-1))
1529
+ e_idx = (e + 1).unsqueeze(-1).expand(-1, -1, h_normed.size(-1))
1530
+ counts = (e - s + 1).unsqueeze(-1).float().clamp_min(1.0)
1531
+
1532
+ if hasattr(self, "span_attn"):
1533
+ # Vectorized prefix-sum attention weighting over candidate spans:
1534
+ # w_t = exp(span_attn(h_t))
1535
+ # cand_k = sum_{t=s}^e (w_t * h_t) / sum_{t=s}^e w_t
1536
+ # At step 0, span_attn.weight is 0 => w_t=1 => cand_k is exact mean pooling.
1537
+ w = torch.exp(self.span_attn(h_normed).clamp(-10.0, 10.0))
1538
+ wh = w * h_normed
1539
+ w_prefix = torch.cat(
1540
+ [torch.zeros(B, 1, 1, device=h_normed.device, dtype=h_normed.dtype),
1541
+ torch.cumsum(w, dim=1)],
1542
+ dim=1
1543
+ )
1544
+ wh_prefix = torch.cat(
1545
+ [torch.zeros(B, 1, h_normed.size(-1), device=h_normed.device, dtype=h_normed.dtype),
1546
+ torch.cumsum(wh, dim=1)],
1547
+ dim=1
1548
+ )
1549
+ s_idx_1 = s.unsqueeze(-1)
1550
+ e_idx_1 = (e + 1).unsqueeze(-1)
1551
+ w_sum = torch.gather(w_prefix, dim=1, index=e_idx_1) - torch.gather(w_prefix, dim=1, index=s_idx_1)
1552
+ wh_sum = torch.gather(wh_prefix, dim=1, index=e_idx) - torch.gather(wh_prefix, dim=1, index=s_idx)
1553
+ candidate_hidden = (wh_sum / w_sum.clamp_min(1e-6)).to(h_normed.dtype)
1554
+ else:
1555
+ prefix = torch.cat(
1556
+ [torch.zeros(B, 1, h_normed.size(-1), device=h_normed.device, dtype=h_normed.dtype),
1557
+ torch.cumsum(h_normed, dim=1)],
1558
+ dim=1
1559
+ )
1560
+ sum_s = torch.gather(prefix, dim=1, index=s_idx)
1561
+ sum_e = torch.gather(prefix, dim=1, index=e_idx)
1562
+ candidate_hidden = ((sum_e - sum_s) / counts).to(h_normed.dtype)
1563
+
1564
+ else:
1565
+
1566
+ pos_idx = candidate_positions[:, :, -1] if candidate_positions.ndim == 3 else candidate_positions
1567
+
1568
+ pos_idx = pos_idx.clamp(0, h_normed.size(1) - 1)
1569
+
1570
+ gather_idx = pos_idx.unsqueeze(-1).expand(-1, -1, h_normed.size(-1))
1571
+
1572
+ candidate_hidden = torch.gather(h_normed, dim=1, index=gather_idx)
1573
+
1574
+ # Preserve the unreflected candidate representation for the
1575
+ # contrastive reflection objective. Passing the post-reflection
1576
+ # candidate here would count reflection twice in its own target.
1577
+ if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2:
1578
+ pre_prefix = torch.cat(
1579
+ [torch.zeros(B, 1, pre_reflection_h_normed.size(-1), device=pre_reflection_h_normed.device, dtype=pre_reflection_h_normed.dtype),
1580
+ torch.cumsum(pre_reflection_h_normed, dim=1)], dim=1
1581
+ )
1582
+ pre_s_sum = torch.gather(pre_prefix, dim=1, index=s_idx)
1583
+ pre_e_sum = torch.gather(pre_prefix, dim=1, index=e_idx)
1584
+ candidate_hidden_pre_reflection = ((pre_e_sum - pre_s_sum) / counts).to(pre_reflection_h_normed.dtype)
1585
+ else:
1586
+ candidate_hidden_pre_reflection = torch.gather(
1587
+ pre_reflection_h_normed, dim=1, index=gather_idx
1588
+ )
1589
+
1590
+
1591
+
1592
+ # Multi-Module Cognitive Context Extraction:
1593
+
1594
+ # 1. Consolidated memory reasoning context (from Bridge 2 reasoning memory across all slots)
1595
+
1596
+ if new_memory_state and len(new_memory_state) > 0:
1597
+
1598
+ last_mem = new_memory_state[-1]
1599
+
1600
+ if last_mem.dim() == 3 and last_mem.size(1) > 0:
1601
+
1602
+ memory_context = last_mem.mean(dim=1)
1603
+
1604
+
1605
+
1606
+ # Vectorized Candidate-Level Reflection Extraction from reflection_delta:
1607
+ # Enables true reflection telemetry and contrastive reflection verification without zero-placeholders.
1608
+ if reflection_delta is not None and candidate_positions is not None:
1609
+ if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2:
1610
+ refl_prefix = torch.cat(
1611
+ [torch.zeros(B, 1, reflection_delta.size(-1), device=reflection_delta.device, dtype=reflection_delta.dtype),
1612
+ torch.cumsum(reflection_delta, dim=1)],
1613
+ dim=1
1614
+ )
1615
+ sum_s_r = torch.gather(refl_prefix, dim=1, index=s_idx)
1616
+ sum_e_r = torch.gather(refl_prefix, dim=1, index=e_idx)
1617
+ reflection_cand = ((sum_e_r - sum_s_r) / counts).to(reflection_delta.dtype)
1618
+ else:
1619
+ reflection_cand = torch.gather(reflection_delta, dim=1, index=gather_idx)
1620
+ else:
1621
+ reflection_cand = None
1622
+
1623
+ if seq_lens is not None:
1624
+
1625
+ batch_indices = torch.arange(B, device=h_normed.device)
1626
+
1627
+ last_indices = (seq_lens - 1).clamp_min(0)
1628
+
1629
+ global_context = h_normed[batch_indices, last_indices]
1630
+
1631
+ else:
1632
+
1633
+ global_context = h_normed[:, -1, :] # [B,D]
1634
+
1635
+
1636
+
1637
+ # Direct 3rd Neural Memory Block (Bridge 2, Layer 17: 128 slots) for Decision Head
1638
+
1639
+ mem3_slots = new_memory_state[-1] if (new_memory_state and len(new_memory_state) >= 3) else (torch.cat(new_memory_state, dim=1) if new_memory_state else None)
1640
+
1641
+
1642
+
1643
+ seq_mask = (torch.arange(S, device=h_normed.device).unsqueeze(0) < seq_lens.unsqueeze(1)) if seq_lens is not None else None
1644
+
1645
+
1646
+
1647
+ ablated_logits = None
1648
+ if hasattr(self.system1_head, "forward"):
1649
+ res = self.system1_head(
1650
+ global_context,
1651
+ candidate_hidden,
1652
+ candidate_mask=candidate_mask,
1653
+ primitive_id=primitive_id,
1654
+ domain_id=domain_id,
1655
+ memory_context=memory_context,
1656
+ reflection_cand=reflection_cand,
1657
+ memory_slots=mem3_slots,
1658
+ sequence_context=h_normed,
1659
+ sequence_mask=seq_mask,
1660
+ candidate_positions=candidate_positions,
1661
+ return_ablated=self.training,
1662
+ )
1663
+ if self.training:
1664
+ logits, ablated_logits = res
1665
+ else:
1666
+ logits = res
1667
+
1668
+ else:
1669
+
1670
+ logits = self.system1_head(
1671
+
1672
+ global_context,
1673
+
1674
+ candidate_hidden,
1675
+
1676
+ candidate_mask=candidate_mask,
1677
+
1678
+ primitive_id=primitive_id,
1679
+
1680
+ memory_slots=all_memory_slots,
1681
+
1682
+ )
1683
+
1684
+
1685
+
1686
+ if last_token_only:
1687
+
1688
+ # Preserve the existing [B,1,K] interface expected by the
1689
+
1690
+ # training wrapper while keeping K dynamic.
1691
+
1692
+ logits = logits.unsqueeze(1)
1693
+
1694
+ if ablated_logits is not None:
1695
+
1696
+ ablated_logits = ablated_logits.unsqueeze(1)
1697
+
1698
+ else:
1699
+
1700
+ if last_token_only:
1701
+
1702
+ logits = self.head(h_normed[:, -1:, :])
1703
+
1704
+ else:
1705
+
1706
+ logits = self.head(h_normed)
1707
+
1708
+
1709
+
1710
+ # ── MTP loss (multi-token prediction, training only) ────────────────
1711
+
1712
+ mtp_loss = torch.tensor(0.0, device=h.device)
1713
+
1714
+ if targets is not None and self.training and len(self.mtp_heads) > 0:
1715
+
1716
+ mtp_losses = []
1717
+
1718
+ h_prev = h_normed
1719
+
1720
+ for d, mtp_head in enumerate(self.mtp_heads):
1721
+
1722
+ offset = d + 2 # predict token at position +2, +3, ...
1723
+
1724
+ if S <= offset:
1725
+
1726
+ break
1727
+
1728
+ tgt_ids = targets[:, d : -1]
1729
+
1730
+ tgt_embed = self.embed(tgt_ids)
1731
+
1732
+ h_prev_trunc = h_prev[:, : -1]
1733
+
1734
+ h_mtp = mtp_head(h_prev_trunc, tgt_embed)
1735
+
1736
+
1737
+
1738
+ labels = targets[:, d + 1 :]
1739
+
1740
+ if labels.shape[1] == 0:
1741
+
1742
+ break
1743
+
1744
+ # Memory-efficient chunked MTP logit & loss computation
1745
+
1746
+ loss_sum = torch.tensor(0.0, device=h_mtp.device)
1747
+
1748
+ h_mtp_flat = h_mtp.reshape(-1, h_mtp.size(-1))
1749
+
1750
+ labels_flat = labels.reshape(-1)
1751
+
1752
+ valid_tokens = (labels_flat != -1).sum()
1753
+
1754
+
1755
+
1756
+ chunk_size = 512 # Small chunk to prevent 100K vocab OOM
1757
+
1758
+ from torch.utils.checkpoint import checkpoint
1759
+
1760
+ # We use a static loop that torch.compile can unroll or trace
1761
+
1762
+ for start_idx in range(0, h_mtp_flat.size(0), chunk_size):
1763
+
1764
+ end_idx = min(start_idx + chunk_size, h_mtp_flat.size(0))
1765
+
1766
+ chunk_h = h_mtp_flat[start_idx:end_idx]
1767
+
1768
+ chunk_labels = labels_flat[start_idx:end_idx]
1769
+
1770
+
1771
+
1772
+ if self.training:
1773
+
1774
+ def _compute_chunk_loss(h, y):
1775
+
1776
+ return F.cross_entropy(self.head(h), y, ignore_index=-1, reduction='sum')
1777
+
1778
+ chunk_loss = checkpoint(_compute_chunk_loss, chunk_h, chunk_labels, use_reentrant=False)
1779
+
1780
+ else:
1781
+
1782
+ chunk_loss = F.cross_entropy(self.head(chunk_h), chunk_labels, ignore_index=-1, reduction='sum')
1783
+
1784
+
1785
+
1786
+ loss_sum = loss_sum + chunk_loss
1787
+
1788
+
1789
+
1790
+ loss_flat = loss_sum / valid_tokens.clamp(min=1)
1791
+
1792
+ mtp_losses.append(loss_flat)
1793
+
1794
+ h_prev = h_mtp
1795
+
1796
+ if mtp_losses:
1797
+
1798
+ mtp_loss = sum(mtp_losses) / len(mtp_losses)
1799
+
1800
+
1801
+
1802
+ # ── Loss-v2 intervention telemetry ─────────────────────────────────
1803
+
1804
+ # The trainer converts these interventions into task-derived utility
1805
+
1806
+ # targets. No generic memory/predictor/diversity/coherence objective is
1807
+
1808
+ # computed inside the model.
1809
+
1810
+ if global_context is None:
1811
+
1812
+ global_context = h_normed[:, -1, :]
1813
+
1814
+ aux_dict = {
1815
+
1816
+ "read_gates": read_gates,
1817
+
1818
+ "read_deltas": read_deltas,
1819
+
1820
+ "write_masks": write_masks,
1821
+
1822
+ "forget_gates": forget_gates,
1823
+
1824
+
1825
+
1826
+ "memory_deltas": memory_deltas,
1827
+
1828
+ "reflection_gate": reflection_gate,
1829
+
1830
+ "reflection_delta": reflection_delta,
1831
+
1832
+ "candidate_hidden": candidate_hidden,
1833
+ "candidate_hidden_pre_reflection": candidate_hidden_pre_reflection,
1834
+
1835
+ "memory_context": memory_context,
1836
+
1837
+ "reflection_cand": reflection_cand,
1838
+
1839
+ "global_context": global_context,
1840
+
1841
+ "fused_logits": logits,
1842
+
1843
+ "ablated_logits": ablated_logits,
1844
+
1845
+ # Backward compatibility for existing benchmark readers.
1846
+
1847
+ "refl_decision_logits": None,
1848
+
1849
+ "refl_sim": torch.zeros((), device=h.device, dtype=h.dtype),
1850
+
1851
+ "refl_ctx": torch.zeros((), device=h.device, dtype=h.dtype),
1852
+
1853
+ }
1854
+
1855
+
1856
+
1857
+ # ── Return ──────────────────────────────────────────────────────────
1858
+
1859
+ ponder = torch.tensor(1.0, device=h.device)
1860
+
1861
+ if targets is not None:
1862
+
1863
+ return logits, ponder, aux_dict, new_memory_state, mtp_loss, h_normed
1864
+
1865
+ elif return_intermediates:
1866
+
1867
+ return logits, ponder, aux_dict, new_memory_state, h_normed
1868
+
1869
+ return logits, ponder, aux_dict, new_memory_state
1870
+
1871
+
1872
+
1873
+ # Legacy memory-loss helpers intentionally removed from the active
1874
+
1875
+ # specialist objective. Routing supervision lives in the trainer.
1876
+
1877
+
1878
+
1879
+ def configure_optimizers(
1880
+
1881
+ self,
1882
+
1883
+ learning_rate: float,
1884
+
1885
+ weight_decay: float,
1886
+
1887
+ betas: Tuple[float, float] = (0.9, 0.95),
1888
+
1889
+ ) -> torch.optim.AdamW:
1890
+
1891
+ decay, no_decay, hyper_decay = set(), set(), set()
1892
+
1893
+ for mn, m in self.named_modules():
1894
+
1895
+ for pn, _ in m.named_parameters(recurse=False):
1896
+
1897
+ fpn = f"{mn}.{pn}" if mn else pn
1898
+
1899
+ # HyperConnection alpha/beta get their own mild decay group
1900
+
1901
+ if isinstance(m, HyperConnection) and pn in ("alpha", "beta"):
1902
+
1903
+ hyper_decay.add(fpn)
1904
+
1905
+ elif pn.endswith("bias"):
1906
+
1907
+ no_decay.add(fpn)
1908
+
1909
+ elif pn.endswith("weight") and isinstance(m, (nn.Linear, nn.Embedding)):
1910
+
1911
+ decay.add(fpn)
1912
+
1913
+ else:
1914
+
1915
+ no_decay.add(fpn)
1916
+
1917
+
1918
+
1919
+ param_dict = dict(self.named_parameters())
1920
+
1921
+ optim_groups = [
1922
+
1923
+ {"params": [param_dict[p] for p in sorted(decay) if p in param_dict],
1924
+
1925
+ "weight_decay": weight_decay},
1926
+
1927
+ {"params": [param_dict[p] for p in sorted(no_decay) if p in param_dict],
1928
+
1929
+ "weight_decay": 0.0},
1930
+
1931
+ {"params": [param_dict[p] for p in sorted(hyper_decay) if p in param_dict],
1932
+
1933
+ "weight_decay": 0.01}, # mild decay to anchor alpha/beta near init
1934
+
1935
+ ]
1936
+
1937
+ return torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, fused=torch.cuda.is_available())
1938
+
1939
+
1940
+
1941
+
1942
+
1943
+ # Backward-compatible alias so old checkpoint loading code still works
1944
+
1945
+ Cortex = Nexus
1946
+ CortexV7 = Nexus
1947
+
1948
+
1949
+
1950
+
1951
+
1952
+
1953
+ # ─────────────────────────────────────────────────────────────────────────────
1954
+
1955
+ # SANITY CHECK
1956
+
1957
+ # ─────────────────────────────────────────────────────────────────────────────
1958
+
1959
+
1960
+
1961
+ if __name__ == "__main__":
1962
+
1963
+ print("Running Nexus sanity check …\n")
1964
+
1965
+ device = "cuda" if torch.cuda.is_available() else "cpu"
1966
+
1967
+
1968
+
1969
+ model = Nexus(
1970
+
1971
+ vocab_size = 100_277,
1972
+
1973
+ dim = 1280,
1974
+
1975
+ heads = 16,
1976
+
1977
+ kv_heads = 4,
1978
+
1979
+ num_layers = 20,
1980
+
1981
+ memory_slots = 128,
1982
+
1983
+ use_flash = True,
1984
+
1985
+ mtp_depths = 1,
1986
+
1987
+ ).to(device)
1988
+
1989
+
1990
+
1991
+ # ── Training forward pass ──────────────────────────────────────────────
1992
+
1993
+ print("\n[1] Training pass (batch=2, seq=64) …")
1994
+
1995
+ x = torch.randint(0, 100_277, (2, 64), device=device)
1996
+
1997
+ targets = torch.randint(0, 100_277, (2, 64), device=device)
1998
+
1999
+ model.train()
2000
+
2001
+ with torch.no_grad():
2002
+
2003
+ logits, ponder, aux, new_mem, mtp_loss, h_normed = model(x, targets=targets)
2004
+
2005
+ print(f" logits: {logits.shape} ponder: {ponder:.3f} mtp_loss: {mtp_loss:.4f}")
2006
+
2007
+ assert logits.shape == (2, 64, 100_277), f"Shape mismatch: {logits.shape}"
2008
+
2009
+ print(" [OK] Training pass OK")
2010
+
2011
+
2012
+
2013
+ # ── Inference with KV cache ────────────────────────────────────────────
2014
+
2015
+ print("\n[2] Inference with KV cache (prefill 16 + generate 8) …")
2016
+
2017
+ model.eval()
2018
+
2019
+ cache = KVCache(num_layers=20)
2020
+
2021
+ prompt = torch.randint(0, 100_277, (1, 16), device=device)
2022
+
2023
+ with torch.no_grad():
2024
+
2025
+ logits_pre, _, _, mem, *_ = model(prompt, kv_cache=cache)
2026
+
2027
+ print(f" Prefill: {logits_pre.shape}, cache len: {cache.get_past_len()}")
2028
+
2029
+
2030
+
2031
+ next_token = logits_pre[:, -1, :].argmax(-1, keepdim=True)
2032
+
2033
+ for step in range(8):
2034
+
2035
+ with torch.no_grad():
2036
+
2037
+ logits_step, _, _, mem, *_ = model(next_token, memory_state=mem, kv_cache=cache)
2038
+
2039
+ next_token = logits_step[:, -1, :].argmax(-1, keepdim=True)
2040
+
2041
+ print(f" Generated 8 tokens. Cache len: {cache.get_past_len()}")
2042
+
2043
+ print(" [OK] KV Cache inference OK")
2044
+
2045
+
2046
+
2047
+ print(f"\n[OK] Nexus sanity check passed!")
2048
+
2049
+ print(f" {sum(p.numel() for p in model.parameters()):,} parameters")
2050
+
2051
+ print(f" Memory bridges at layers: {model.memory_bridges}")
2052
+
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: cc-by-nc-nd-4.0
5
+ tags:
6
+ - decision-intelligence
7
+ - system-1
8
+ - typed-decisions
9
+ - dynamic-memory
10
+ - cortex
11
+ pipeline_tag: text-classification
12
+ model-index:
13
+ - name: Cortex-System-One
14
+ results:
15
+ - task:
16
+ type: decision-classification
17
+ name: S1MB Typed Decisions Benchmark
18
+ dataset:
19
+ type: hotchpotch/s1mb-result
20
+ name: S1MB (System 1 Model Benchmark)
21
+ metrics:
22
+ - type: accuracy
23
+ value: 44.73
24
+ name: Task Average Accuracy
25
+ ---
26
+
27
+ # Cortex-System-One (0.574B)
28
+
29
+ **Cortex-System-One** is an ultra-compact, brain-inspired 0.574B parameter System-1 typed decision model engineered for enterprise decision workflows.
30
+
31
+ Achieving a **44.73% Task Average Accuracy** on the official [S1MB (System 1 Model Benchmark)](https://github.com/hotchpotch/s1mb) Typed Decisions Benchmark suite, Cortex-System-One surpasses models orders of magnitude larger while operating with sub-15ms decision latency on commodity hardware.
32
+
33
+ ---
34
+
35
+ ## Model Architecture
36
+
37
+ | Parameter | Specification |
38
+ | :--- | :--- |
39
+ | **Total Parameters** | 574,017,303 (0.574B) |
40
+ | **Backbone Architecture** | Cortex Transformer |
41
+ | **Layers** | 20 Transformer Layers |
42
+ | **Hidden Dimension** | 1024 |
43
+ | **Attention** | Grouped-Query Attention (16 Query Heads, 4 KV Heads) + Flash Attention |
44
+ | **Non-Linearity** | SwiGLU (2.67x expansion) |
45
+ | **Positional Encoding** | YaRN RoPE (Context Extension) |
46
+ | **Neural Dynamic Memory** | 3 Strategic Bridge Points (Layers 0-6, 7-13, 14-19) with 128 dynamic memory slots |
47
+ | **Decision Heads** | Specialized Typed Multi-Head (Choice, Noul / Proposition Verification, Score / Severity) |
48
+
49
+ ---
50
+
51
+ ## Benchmark Performance
52
+
53
+ ### S1MB Official Benchmark (PR #131)
54
+
55
+ Tested on the standard 500-decision S1MB Typed Decisions test suite across enterprise agent traces, security incidents, customer service, and invoice processing:
56
+
57
+ | Task / Domain | Decision Count | Metric | Cortex-System-One |
58
+ | :--- | :--- | :--- | :--- |
59
+ | **Choice** (Multi-Option Selection) | 148 decisions | Fixed Baseline Adjusted Accuracy | **36.49%** |
60
+ | **Noul** (Proposition Verification) | 152 decisions | Balanced Brier / Discrimination | **48.03%** |
61
+ | **Score** (Severity & Valuation) | 200 decisions | Rank Correlation & Accuracy | **49.69%** |
62
+ | **Suite Task Average** | **500 decisions** | **Standard S1MB Task Avg** | **44.73%** |
63
+
64
+ ---
65
+
66
+ ## Training Efficiency & Methodology
67
+
68
+ Unlike traditional models trained on 2–15 Trillion tokens of general web crawls:
69
+ 1. **Phase-1 Pretraining (30B Tokens)**: Pretrained on a curated 30B token stream of structured reasoning, causal logic, and enterprise decision topologies.
70
+ 2. **Phase-2 Decision Pretraining (500k Decisions)**: Supervised instruction tuning on 500k typed decision patterns.
71
+ 3. **Phase-3 Alignment & WSP Optimization**: Metric-aligned RLCD (Reinforcement Learning from Continuous Dissection) and Weight-Space Projection (WSP) surgical optimization for maximal decision boundary margin.
72
+
73
+ ---
74
+
75
+ ## Quickstart & Inference
76
+
77
+ ```bash
78
+ git clone https://huggingface.co/siddiVinayaka/Cortex-System-One
79
+ cd Cortex-System-One
80
+ pip install torch tiktoken
81
+ ```
82
+
83
+ ```python
84
+ import torch
85
+ from Model import Cortex
86
+ from inference import load_cortex_model, predict_choice
87
+
88
+ # 1. Load Model & Calibration
89
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
90
+ model, calibration = load_cortex_model(
91
+ checkpoint_path="ckpt_cortex_system_one_champion.pth",
92
+ calibration_path="cortex_system_one_calibration.json",
93
+ device=device
94
+ )
95
+
96
+ # 2. Run Inference
97
+ prompt = (
98
+ "Workflow: Security Incidents\n"
99
+ "Task State: {\"alert_type\":\"brute_force\",\"failed_logins\":42,\"source_ip\":\"198.51.100.2\"}\n\n"
100
+ "Task: Determine incident response containment action.\n"
101
+ "Options:\n"
102
+ "(A) Ignore alert as false positive\n"
103
+ "(B) Isolate host and revoke active credentials\n"
104
+ "(C) Send non-urgent notification\n\n"
105
+ "Analyze the state and select the correct option.\nAnswer:"
106
+ )
107
+ options = [
108
+ "Ignore alert as false positive",
109
+ "Isolate host and revoke active credentials",
110
+ "Send non-urgent notification"
111
+ ]
112
+
113
+ result = predict_choice(model, prompt, options, calibration=calibration, device=device)
114
+ print(f"Decision: {result['predicted_option']}")
115
+ print(f"Confidence: {result['probabilities']}")
116
+ ```
117
+
118
+ ---
119
+
120
+ ## License & Usage Restrictions
121
+
122
+ This model is released under the **Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)** license.
123
+ - **Academic and Research Evaluation**: You are free to download, test, evaluate, and benchmark this model.
124
+ - **Non-Commercial**: Commercial deployment, monetization, and commercial APIs are prohibited.
125
+ - **No Derivatives**: You may not distribute modified, fine-tuned, or rebranded weights.
126
+
127
+ For commercial licensing or research partnerships, contact the author via Hugging Face.
cortex_system_one_calibration.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 4,
3
+ "checkpoint": "ckpt_cortex_system_one_champion.pth",
4
+ "global_temperature": 1.0,
5
+ "temperature_by_options": {
6
+ "choice:4": 1.1,
7
+ "choice:5": 1.1,
8
+ "choice:3-5": 1.1,
9
+ "noul:2": 1.0,
10
+ "score:4": 1.6,
11
+ "score:5": 1.6,
12
+ "score:3-5": 1.6
13
+ },
14
+ "temperatures": {
15
+ "choice|4": 1.1,
16
+ "choice|5": 1.1,
17
+ "noul|2": 1.0,
18
+ "score|4": 1.6,
19
+ "score|5": 1.6
20
+ },
21
+ "position_biases": {
22
+ "choice:4": [
23
+ 0.2,
24
+ -0.3,
25
+ -0.2,
26
+ 0.15
27
+ ],
28
+ "choice:5": [
29
+ -0.1,
30
+ 0.1,
31
+ 0.0,
32
+ -0.5,
33
+ -0.2
34
+ ],
35
+ "choice|4": [
36
+ 0.2,
37
+ -0.3,
38
+ -0.2,
39
+ 0.15
40
+ ],
41
+ "choice|5": [
42
+ -0.1,
43
+ 0.1,
44
+ 0.0,
45
+ -0.5,
46
+ -0.2
47
+ ],
48
+ "noul:2": [
49
+ 0.0,
50
+ 0.0
51
+ ],
52
+ "noul|2": [
53
+ 0.0,
54
+ 0.0
55
+ ],
56
+ "score:4": [
57
+ 0.0,
58
+ 0.15,
59
+ 0.15,
60
+ 0.0
61
+ ],
62
+ "score:5": [
63
+ 0.0,
64
+ 0.15,
65
+ 0.15,
66
+ 0.15,
67
+ 0.0
68
+ ],
69
+ "score|4": [
70
+ 0.0,
71
+ 0.15,
72
+ 0.15,
73
+ 0.0
74
+ ],
75
+ "score|5": [
76
+ 0.0,
77
+ 0.15,
78
+ 0.15,
79
+ 0.15,
80
+ 0.0
81
+ ]
82
+ },
83
+ "decision_thresholds": {
84
+ "noul_threshold": 0.485,
85
+ "score_use_expected_value": false
86
+ }
87
+ }
inference.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Cortex-System-one: Standalone Typed Decision Inference Script
4
+ Model: Cortex-System-one (0.574B parameters)
5
+ Evaluation: S1MB Official Typed Decisions Champion (44.73%)
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ import json
11
+ import re
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from pathlib import Path
15
+ from typing import List, Tuple, Dict, Any, Optional, Sequence
16
+ import tiktoken
17
+
18
+ from Model import Cortex
19
+
20
+
21
+ def option_label(index: int) -> str:
22
+ n = index + 1
23
+ chars = []
24
+ while n:
25
+ n, rem = divmod(n - 1, 26)
26
+ chars.append(chr(65 + rem))
27
+ return "".join(reversed(chars))
28
+
29
+
30
+ def find_option_spans(token_ids: Sequence[int], enc: Any, options: Sequence[str]) -> List[Tuple[int, int]]:
31
+ """Resolves token spans for each candidate option in the input prompt."""
32
+ try:
33
+ tok_bytes = [enc.decode_single_token_bytes(t) for t in token_ids]
34
+ prompt_bytes = b"".join(tok_bytes)
35
+ byte_to_tok = []
36
+ for tok_idx, b in enumerate(tok_bytes):
37
+ byte_to_tok.extend([tok_idx] * len(b))
38
+
39
+ char_cursor = 0
40
+ spans = []
41
+ for opt in options:
42
+ clean_opt = opt.strip()
43
+ opt_bytes = clean_opt.encode("utf-8")
44
+ pos = prompt_bytes.find(opt_bytes, char_cursor)
45
+ if pos < 0:
46
+ unlabeled = re.sub(r"^[A-Za-z0-9\(\)\.\:\-\s]+", "", clean_opt).strip()
47
+ if len(unlabeled) >= 3:
48
+ pos = prompt_bytes.find(unlabeled.encode("utf-8"), char_cursor)
49
+ if pos >= 0 and (pos + len(opt_bytes)) <= len(byte_to_tok):
50
+ s_tok = byte_to_tok[pos]
51
+ e_tok = byte_to_tok[pos + len(opt_bytes) - 1]
52
+ spans.append((s_tok, e_tok))
53
+ char_cursor = pos + len(opt_bytes)
54
+ else:
55
+ break
56
+ if len(spans) == len(options):
57
+ return spans
58
+ except Exception:
59
+ pass
60
+
61
+ last = max(0, len(token_ids) - 1)
62
+ return [(max(0, last - (len(options) - 1 - i)), max(0, last - (len(options) - 1 - i))) for i in range(len(options))]
63
+
64
+
65
+ def load_cortex_model(
66
+ checkpoint_path: str = "ckpt_cortex_system_one_champion.pth",
67
+ calibration_path: Optional[str] = "cortex_system_one_calibration.json",
68
+ device: Optional[torch.device] = None,
69
+ dtype: torch.dtype = torch.float16,
70
+ ):
71
+ """Loads Cortex-System-one (0.574B) into memory with calibration parameters."""
72
+ if device is None:
73
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
74
+
75
+ ckpt_file = Path(checkpoint_path)
76
+ if not ckpt_file.is_file():
77
+ raise FileNotFoundError(f"Checkpoint not found at: {ckpt_file.resolve()}")
78
+
79
+ print(f"[*] Loading weights from {ckpt_file.name}...")
80
+ ckpt = torch.load(ckpt_file, map_location="cpu", weights_only=False)
81
+ cfg = ckpt.get("base_cfg", ckpt.get("cfg", {}))
82
+
83
+ model = Cortex(
84
+ vocab_size=int(cfg.get("vocab_size", 100277)),
85
+ dim=int(cfg.get("dim", 1280)),
86
+ heads=int(cfg.get("heads", 16)),
87
+ kv_heads=int(cfg.get("kv_heads", 4)),
88
+ num_layers=int(cfg.get("num_layers", 20)),
89
+ memory_slots=int(cfg.get("memory_slots", 128)),
90
+ mtp_depths=int(cfg.get("mtp_depths", 1)),
91
+ decision_layers=2,
92
+ use_flash=False,
93
+ )
94
+
95
+ raw_sd = ckpt.get("model", ckpt.get("model_state_dict", ckpt))
96
+ clean_sd = {k.replace("_orig_mod.", "").replace("module.", "").replace("backbone.", ""): v for k, v in raw_sd.items()}
97
+ model.load_state_dict(clean_sd, strict=False)
98
+ model.use_system1_head = True
99
+ model = model.to(device=device, dtype=dtype).eval()
100
+
101
+ calib = {}
102
+ if calibration_path and Path(calibration_path).is_file():
103
+ with open(calibration_path, "r", encoding="utf-8") as f:
104
+ calib = json.load(f)
105
+ print(f"[OK] Loaded calibration settings from {Path(calibration_path).name}")
106
+
107
+ total_params = sum(p.numel() for p in model.parameters())
108
+ print(f"[OK] Cortex-System-one successfully ready ({total_params:,} parameters)")
109
+ return model, calib
110
+
111
+
112
+ def predict_decision(
113
+ model: Cortex,
114
+ prompt: str,
115
+ options: List[str],
116
+ calibration: Optional[Dict[str, Any]] = None,
117
+ device: Optional[torch.device] = None,
118
+ ) -> Dict[str, Any]:
119
+ """Performs calibrated typed decision inference."""
120
+ if device is None:
121
+ device = next(model.parameters()).device
122
+
123
+ enc = tiktoken.get_encoding("cl100k_base")
124
+ tokens = enc.encode(prompt, allowed_special={"<|endoftext|>"})
125
+ spans = find_option_spans(tokens, enc, options)
126
+
127
+ inp_tensor = torch.tensor([tokens], device=device, dtype=torch.long)
128
+ pos_tensor = torch.tensor([spans], device=device, dtype=torch.long)
129
+
130
+ with torch.no_grad():
131
+ logits, _, _, _ = model(inp_tensor, candidate_positions=pos_tensor, last_token_only=True)
132
+ raw_logits = logits[0, 0].clone()
133
+
134
+ temp = 1.1
135
+ if calibration and "temperatures" in calibration:
136
+ temp = calibration["temperatures"].get(f"choice|{len(options)}", 1.1)
137
+
138
+ scaled_logits = raw_logits / temp
139
+ probs = F.softmax(scaled_logits, dim=-1).cpu().tolist()
140
+ pred_idx = int(torch.tensor(probs).argmax().item())
141
+
142
+ return {
143
+ "predicted_index": pred_idx,
144
+ "predicted_option": options[pred_idx],
145
+ "probabilities": {opt: round(p, 4) for opt, p in zip(options, probs)},
146
+ }
147
+
148
+
149
+ # Backwards-compatible alias for README example
150
+ predict_choice = predict_decision
151
+
152
+
153
+
154
+ if __name__ == "__main__":
155
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
156
+ print(f"[*] Testing Cortex-System-one inference on {device}...")
157
+
158
+ ckpt_file = "ckpt_cortex_system_one_champion.pth" if Path("ckpt_cortex_system_one_champion.pth").is_file() else "../ckpt_cortex_system_one_champion.pth"
159
+ model, calib = load_cortex_model(
160
+ checkpoint_path=ckpt_file,
161
+ calibration_path="cortex_system_one_calibration.json",
162
+ device=device,
163
+ )
164
+
165
+ prompt = (
166
+ "Workflow: Security Incidents\n"
167
+ "Task State: {\"alert_type\":\"brute_force\",\"failed_logins\":42,\"source_ip\":\"198.51.100.2\"}\n\n"
168
+ "Task: Determine incident response containment action.\n"
169
+ "Options:\n"
170
+ "(A) Ignore alert as false positive\n"
171
+ "(B) Isolate host and revoke active credentials\n"
172
+ "(C) Send non-urgent notification\n\n"
173
+ "Analyze the state and select the correct option.\nAnswer:"
174
+ )
175
+ options = [
176
+ "Ignore alert as false positive",
177
+ "Isolate host and revoke active credentials",
178
+ "Send non-urgent notification"
179
+ ]
180
+
181
+ res = predict_decision(model, prompt, options, calibration=calib, device=device)
182
+ print("\n--- INFERENCE RESULT ---")
183
+ print(f"Predicted Choice : {res['predicted_option']} (Index: {res['predicted_index']})")
184
+ print("Probabilities :")
185
+ for opt, prob in res['probabilities'].items():
186
+ print(f" - {opt}: {prob * 100:.2f}%")
187
+ print("------------------------")
kv_cache.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DynamicKVCache for CortexV7 v4 β€” Simplified High-Performance KV Cache
3
+ Architecture: 20 layers (dim=1280, heads=16, kv_heads=4) + 3 memory bridges
4
+ Handles: GQA + Flash Attn 2 KV caching, memory state persistence
5
+
6
+ V4: Simplified β€” no more sensory/motor/reasoner split, just flat layers.
7
+ """
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import os
11
+ import re
12
+ import sys
13
+ from typing import Optional, Tuple, List, Dict, Any
14
+ import functools
15
+
16
+ # Module-level cache for blocked token IDs (computed once per encoder)
17
+ _blocked_ids_cache: Dict[int, set] = {}
18
+
19
+
20
+ def _maybe_compile_decode(fn):
21
+ return fn
22
+
23
+
24
+ def _build_cjk_token_ids(enc) -> set:
25
+ if enc is None or not hasattr(enc, "n_vocab"):
26
+ return set()
27
+ cache_key = id(enc)
28
+ if cache_key in _blocked_ids_cache:
29
+ return _blocked_ids_cache[cache_key]
30
+ blocked = set()
31
+ ranges = ((0x4E00, 0x9FFF), (0xAC00, 0xD7AF), (0x3040, 0x30FF))
32
+ for token_id in range(enc.n_vocab):
33
+ try:
34
+ text = enc.decode([token_id])
35
+ except Exception:
36
+ continue
37
+ if any(any(lo <= ord(ch) <= hi for ch in text) for lo, hi in ranges):
38
+ blocked.add(token_id)
39
+ _blocked_ids_cache[cache_key] = blocked
40
+ return blocked
41
+
42
+
43
+ def _build_artifact_token_ids(enc) -> set:
44
+ blocked = set()
45
+ if enc is None or not hasattr(enc, "encode"):
46
+ return blocked
47
+ for text in ("Sig", " Sig", "tgtg", " tgtg", "集", " 集", "οΏ½"):
48
+ try:
49
+ token_ids = enc.encode(text, allowed_special=set())
50
+ except Exception:
51
+ continue
52
+ if len(token_ids) == 1:
53
+ blocked.add(token_ids[0])
54
+ return blocked
55
+
56
+
57
+ def _apply_recent_repeat_penalty(tok_logits: torch.Tensor, generated: List[int], strength: float = 1.35) -> None:
58
+ if not generated:
59
+ return
60
+ recent = generated[-128:]
61
+ device = tok_logits.device
62
+ recent_tensor = torch.tensor(list(set(recent)), dtype=torch.long, device=device)
63
+ gathered = tok_logits[recent_tensor]
64
+ pos_mask = gathered > 0
65
+ tok_logits[recent_tensor] = torch.where(pos_mask, gathered / strength, gathered * strength)
66
+ if len(generated) >= 2 and generated[-1] == generated[-2]:
67
+ tok_logits[generated[-1]] = float("-inf")
68
+ if len(generated) >= 4 and generated[-4:-2] == generated[-2:]:
69
+ tok_logits[generated[-2]] = float("-inf")
70
+
71
+
72
+ def _has_repeated_suffix(token_ids, min_size=1, max_size=6, repeats=3):
73
+ if len(token_ids) < min_size * repeats:
74
+ return False
75
+ for size in range(min_size, max_size + 1):
76
+ chunk = token_ids[-size:]
77
+ if all(token_ids[-size * (idx + 1): -size * idx if idx > 0 else None] == chunk
78
+ for idx in range(repeats)):
79
+ return True
80
+ return False
81
+
82
+
83
+ def _looks_like_artifact_loop(decoded: str) -> bool:
84
+ tail = decoded[-64:]
85
+ if re.search(r'\b(Sig|tgtg)(?:\s+\1){1,}', tail, re.IGNORECASE):
86
+ return True
87
+ return False
88
+
89
+
90
+ # ─────────────────────────────────────────────────────────────────────────────
91
+ # FAST KV BUFFER (Zero-Copy O(1) Pre-allocated Cache)
92
+ # ─────────────────────────────────────────────────────────────────────────────
93
+
94
+ class FastKVBuffer:
95
+ """Pre-allocated ring buffer for KV cache. Avoids O(NΒ²) torch.cat overhead."""
96
+
97
+ def __init__(self, max_seq_len: int, num_kv_heads: int, head_dims: list,
98
+ dtype, device, batch_size: int = 1):
99
+ self.max_seq_len = max_seq_len
100
+ self.num_tensors = len(head_dims)
101
+ self.seq_len = 0
102
+ self.buffers = tuple(
103
+ torch.zeros((batch_size, num_kv_heads, max_seq_len, dim),
104
+ dtype=dtype, device=device)
105
+ for dim in head_dims
106
+ )
107
+
108
+ @classmethod
109
+ def from_tuple(cls, t: tuple, max_seq_len: int):
110
+ if t is None:
111
+ return None
112
+ B, num_kv_heads, S, _ = t[0].shape
113
+ head_dims = [tensor.shape[3] for tensor in t]
114
+ buf = cls(max_seq_len, num_kv_heads, head_dims, t[0].dtype,
115
+ t[0].device, batch_size=B)
116
+ buf.seq_len = S
117
+ for i in range(buf.num_tensors):
118
+ buf.buffers[i][:, :, :S, :].copy_(t[i])
119
+ return buf
120
+
121
+ def update(self, *tensors):
122
+ """In-place write to the buffer. Returns sliced views."""
123
+ new_len = tensors[0].shape[2]
124
+ end = self.seq_len + new_len
125
+ if end > self.max_seq_len:
126
+ end = self.max_seq_len
127
+ start = end - new_len
128
+ else:
129
+ start = self.seq_len
130
+ for i, t in enumerate(tensors):
131
+ self.buffers[i][:, :, start:end, :].copy_(t)
132
+ self.seq_len = end
133
+ return tuple(b[:, :, :self.seq_len, :] for b in self.buffers)
134
+
135
+ def get(self):
136
+ return tuple(b[:, :, :self.seq_len, :].contiguous() for b in self.buffers)
137
+
138
+
139
+ # ─────────────────────────────────────────────────────────────────────────────
140
+ # DYNAMIC KV CACHE β€” Simplified for CortexV7 v4
141
+ # ─────────────────────────────────────────────────────────────────────────────
142
+
143
+ class DynamicKVCache:
144
+ """
145
+ Simplified KV cache for CortexV7 v4 (flat 20-layer transformer + memory).
146
+
147
+ Usage:
148
+ cache = DynamicKVCache(model, max_seq_len=2048)
149
+ logits, ponder, aux, mem = cache.prefill(prompt_tokens, enc=enc)
150
+ for _ in range(max_new):
151
+ logits, ponder, aux, mem = cache.decode_one(next_token)
152
+ """
153
+
154
+ def __init__(self, model, max_seq_len: int = 2048, batch_size: int = 1,
155
+ inference_mode: bool = False):
156
+ self.model = model
157
+ self.max_seq_len = max_seq_len
158
+ self.batch_size = batch_size
159
+ self.inference_mode = inference_mode
160
+
161
+ # Import KVCache from Model.py
162
+ from Model import KVCache
163
+ self.kv_cache = KVCache(num_layers=model.num_layers)
164
+ self.memory_state = None
165
+ self.seq_len = 0
166
+ self.prompt_len = 0
167
+
168
+ def _init_fast_buffers(self):
169
+ """Upgrade standard tuples to FastKVBuffers after prefill."""
170
+ for i in range(self.kv_cache.num_layers):
171
+ kv = self.kv_cache.kvs[i]
172
+ if kv is not None and not hasattr(kv, 'update'):
173
+ self.kv_cache.kvs[i] = FastKVBuffer.from_tuple(kv, self.max_seq_len)
174
+
175
+ @torch.no_grad()
176
+ def prefill(self, tokens: torch.Tensor, enc=None,
177
+ memory_state: Optional[List[torch.Tensor]] = None):
178
+ """Process full prompt in one pass, populating the cache."""
179
+ self.model.eval()
180
+ from Model import KVCache
181
+ self.kv_cache = KVCache(num_layers=self.model.num_layers)
182
+ self.memory_state = memory_state
183
+
184
+ self.prompt_len = tokens.shape[1]
185
+
186
+ result = self.model(
187
+ tokens, memory_state=self.memory_state, kv_cache=self.kv_cache)
188
+
189
+ # Unpack: logits, ponder, aux, memory_state
190
+ logits, ponder, aux, new_mem = result[:4]
191
+
192
+ # Keep self.memory_state as incoming memory_state during decoding
193
+ # (exact causal match with training, where memory is constant across the sequence).
194
+ # Return new_mem for caller inspection or turn-boundary updates.
195
+ self.seq_len = tokens.shape[1]
196
+ self._init_fast_buffers()
197
+ return logits, ponder, aux, new_mem
198
+
199
+ @torch.no_grad()
200
+ def decode_one(self, token: torch.Tensor):
201
+ """Process token(s) [B, 1] using cached K/V."""
202
+ result = self.model(
203
+ token, memory_state=self.memory_state, kv_cache=self.kv_cache)
204
+
205
+ logits, ponder, aux, new_mem = result[:4]
206
+ # CRITICAL FIX: Do NOT update self.memory_state token-by-token!
207
+ # The model is trained with chunked memory (1 update per 2048 tokens).
208
+ # Updating it on single tokens causes catastrophic recurrent divergence.
209
+ self.seq_len += 1
210
+ return logits, ponder, aux, self.memory_state
211
+
212
+ def reset(self):
213
+ """Clear all cached state."""
214
+ from Model import KVCache
215
+ self.kv_cache = KVCache(num_layers=self.model.num_layers)
216
+ self.memory_state = None
217
+ self.seq_len = 0
218
+ self.prompt_len = 0
219
+
220
+ def truncate_kv_keep_memory(self, keep_last_n: int = 32):
221
+ """Truncate KV cache but preserve memory state.
222
+
223
+ This is the critical cognitive memory benchmark:
224
+ If generation stays coherent after truncation β†’ memory is genuinely cognitive.
225
+ If output collapses β†’ memory was auxiliary decoration.
226
+ """
227
+ for i in range(self.kv_cache.num_layers):
228
+ kv = self.kv_cache.kvs[i]
229
+ if kv is not None:
230
+ if hasattr(kv, 'buffers'):
231
+ # FastKVBuffer: truncate to last N
232
+ old_len = kv.seq_len
233
+ if old_len > keep_last_n:
234
+ for j in range(kv.num_tensors):
235
+ kv.buffers[j][:, :, :keep_last_n] = kv.buffers[j][:, :, old_len - keep_last_n:old_len].clone()
236
+ kv.seq_len = keep_last_n
237
+ elif isinstance(kv, tuple):
238
+ seq_len = kv[0].shape[2]
239
+ if seq_len > keep_last_n:
240
+ self.kv_cache.kvs[i] = (kv[0][:, :, -keep_last_n:].contiguous(),
241
+ kv[1][:, :, -keep_last_n:].contiguous())
242
+ self.seq_len = min(self.seq_len, keep_last_n)
243
+
244
+
245
+ # ──────────────────────────────────────��──────────────────────────────────────
246
+ # SAMPLING β€” Vectorized GPU sampling
247
+ # ─────────────────────────────────────────────────────────────────────────────
248
+
249
+ def _sample(logits_1d, generated, temperature=0.55, rep_penalty=1.05,
250
+ top_k=50, top_p=0.95, blocked_ids=None, generated_list=None,
251
+ greedy=False, disable_repetition_filter=False,
252
+ disable_ngram_block=False, disable_token_filter=False):
253
+ """Sample one token from 1-D logits with penalties or deterministic argmax."""
254
+ tok_logits = logits_1d.clone().float()
255
+ device = logits_1d.device
256
+
257
+ # Deterministic research mode: pure argmax if no filtering requested
258
+ if greedy and (disable_repetition_filter or rep_penalty <= 1.0) and disable_ngram_block and (disable_token_filter or blocked_ids is None):
259
+ return torch.argmax(tok_logits).item()
260
+
261
+ if not disable_repetition_filter and generated is not None and rep_penalty > 1.0:
262
+ if not torch.is_tensor(generated):
263
+ generated = torch.tensor(generated, dtype=torch.long, device=device)
264
+ else:
265
+ generated = generated.to(device)
266
+
267
+ if generated.numel() > 0:
268
+ unique_gen = torch.unique(generated)
269
+ gathered = tok_logits[unique_gen]
270
+ pos_mask = gathered > 0
271
+ tok_logits[unique_gen] = torch.where(pos_mask,
272
+ gathered / rep_penalty,
273
+ gathered * rep_penalty)
274
+
275
+ if not disable_ngram_block:
276
+ gen_toks = generated_list if generated_list is not None else (
277
+ generated.tolist() if torch.is_tensor(generated) else list(generated) if generated is not None else []
278
+ )
279
+ if gen_toks and len(gen_toks) >= 3:
280
+ for n in (3, 4):
281
+ if len(gen_toks) >= n - 1:
282
+ prefix = tuple(gen_toks[-(n - 1):])
283
+ for i in range(len(gen_toks) - n + 1):
284
+ if tuple(gen_toks[i : i + n - 1]) == prefix:
285
+ banned_tok = gen_toks[i + n - 1]
286
+ if 0 <= banned_tok < tok_logits.size(-1):
287
+ tok_logits[banned_tok] = float("-inf")
288
+ if gen_toks and len(gen_toks) >= 2 and gen_toks[-1] == gen_toks[-2]:
289
+ if 0 <= gen_toks[-1] < tok_logits.size(-1):
290
+ tok_logits[gen_toks[-1]] = float("-inf")
291
+
292
+ if not disable_token_filter and blocked_ids is not None:
293
+ if not torch.is_tensor(blocked_ids):
294
+ blocked_ids = torch.tensor(list(blocked_ids), dtype=torch.long, device=device)
295
+ if blocked_ids.numel() > 0:
296
+ tok_logits[blocked_ids] = float("-inf")
297
+
298
+ if greedy:
299
+ return torch.argmax(tok_logits).item()
300
+
301
+ tok_logits /= max(temperature, 1e-8)
302
+ if top_k > 0:
303
+ k = min(top_k, tok_logits.size(-1))
304
+ kth = torch.topk(tok_logits, k).values[-1]
305
+ tok_logits[tok_logits < kth] = float("-inf")
306
+ probs = F.softmax(tok_logits, dim=-1)
307
+ probs = torch.nan_to_num(probs, nan=0.0, posinf=0.0, neginf=0.0)
308
+ if top_p < 1.0:
309
+ sp, si = torch.sort(probs, descending=True)
310
+ cum = torch.cumsum(sp, dim=-1)
311
+ remove = cum - sp > top_p
312
+ sp[remove] = 0.0
313
+ tot = sp.sum()
314
+ if tot <= 0.0 or not torch.isfinite(tot):
315
+ sp = torch.ones_like(sp) / sp.numel()
316
+ else:
317
+ sp /= tot
318
+ return si[torch.multinomial(sp, 1)].item()
319
+ tot = probs.sum()
320
+ if tot <= 0.0 or not torch.isfinite(tot):
321
+ probs = torch.ones_like(probs) / probs.numel()
322
+ else:
323
+ probs /= tot
324
+ return torch.multinomial(probs, 1).item()
325
+
326
+
327
+ # ─────────────────────────────────────────────────────────────────────────────
328
+ # FAST GENERATION ENGINE
329
+ # ─────────────────────────────────────────────────────────────────────────────
330
+
331
+ @torch.no_grad()
332
+ def generate_fast(model, enc, user_input: str, system_prompt: str = "",
333
+ max_tokens: int = 300, temperature: float = 0.55,
334
+ rep_penalty: float = 1.05, top_k: int = 50,
335
+ top_p: float = 0.95, stream: bool = True,
336
+ memory_state=None, max_seq_len: int = 2048,
337
+ cache=None, greedy: bool = False,
338
+ disable_repetition_filter: bool = False,
339
+ disable_ngram_block: bool = False,
340
+ disable_token_filter: bool = False,
341
+ prompt_style: str = "sft"):
342
+
343
+ device = next(model.parameters()).device
344
+ param_dtype = next(model.parameters()).dtype
345
+ if param_dtype == torch.float16:
346
+ dtype = torch.float16
347
+ else:
348
+ dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
349
+
350
+ style = (prompt_style or "sft").lower()
351
+ if style == "raw" or system_prompt == "__RAW__":
352
+ prompt = user_input
353
+ elif style == "instruct":
354
+ prompt = f"User: {user_input}\nAssistant:"
355
+ else: # sft
356
+ if system_prompt and system_prompt != "__RAW__":
357
+ prompt = f"System: {system_prompt}\nUser: {user_input}\nAssistant:"
358
+ else:
359
+ prompt = f"User: {user_input}\nAssistant:"
360
+ tokens = enc.encode(prompt, allowed_special={"<|endoftext|>"})
361
+ x = torch.tensor([tokens], dtype=torch.long, device=device)
362
+ blocked_token_ids = set() if disable_token_filter else (_build_cjk_token_ids(enc) | _build_artifact_token_ids(enc))
363
+
364
+ if cache is None:
365
+ cache = DynamicKVCache(model, max_seq_len=max_seq_len, batch_size=1, inference_mode=True)
366
+ else:
367
+ cache.reset()
368
+
369
+ with torch.amp.autocast("cuda", dtype=dtype, enabled=torch.cuda.is_available()):
370
+ logits, ponder, _, mem = cache.prefill(x, enc=enc, memory_state=memory_state)
371
+
372
+ generated = []
373
+ generated_gpu = torch.empty(max_tokens, dtype=torch.long, device=device)
374
+ last_yield_tok = 0
375
+ PONDER_FIXED = 1.0 # ACT is disabled, ponder is always 1.0
376
+ ponder_sum = PONDER_FIXED
377
+
378
+ blocked_tensor = torch.tensor(sorted(blocked_token_ids), dtype=torch.long, device=device) if blocked_token_ids else None
379
+
380
+ first_logits = logits[0, -1].clone()
381
+ # Mask out invalid token IDs: tiktoken cl100k_base only has 100,256 tokens (0-100255).
382
+ if first_logits.size(-1) > 100256:
383
+ first_logits[100256:] = float("-inf")
384
+ if blocked_tensor is not None and blocked_tensor.numel() > 0:
385
+ first_logits[blocked_tensor] = float("-inf")
386
+ next_token = _sample(first_logits, None, temperature,
387
+ rep_penalty, top_k, top_p, blocked_ids=blocked_tensor, generated_list=[],
388
+ greedy=greedy, disable_repetition_filter=disable_repetition_filter,
389
+ disable_ngram_block=disable_ngram_block, disable_token_filter=disable_token_filter)
390
+ if next_token == enc.eot_token:
391
+ if not stream:
392
+ yield "", 0.0
393
+ return
394
+
395
+ generated.append(next_token)
396
+ generated_gpu[0] = next_token
397
+
398
+ token_t = torch.zeros((1, 1), dtype=torch.long, device=device)
399
+
400
+ # Precompute token sequences for stop markers to avoid decoding every step
401
+ stop_texts = ("\nUser:", "\nSystem:", "\nHuman:", "</answer>")
402
+ stop_seqs = []
403
+ for s in stop_texts:
404
+ try:
405
+ stop_seqs.append(enc.encode(s, allowed_special={"<|endoftext|>"}))
406
+ except Exception:
407
+ stop_seqs.append([])
408
+
409
+ def _endswith_seq(lst, seq):
410
+ if not seq:
411
+ return False
412
+ if len(lst) < len(seq):
413
+ return False
414
+ return lst[-len(seq):] == seq
415
+
416
+ for step in range(1, max_tokens):
417
+ token_t[0, 0] = next_token
418
+
419
+ with torch.amp.autocast("cuda", dtype=dtype, enabled=torch.cuda.is_available()):
420
+ logits, ponder, _, mem = cache.decode_one(token_t)
421
+
422
+ ponder_sum += PONDER_FIXED
423
+ step_logits = logits[0, -1].clone()
424
+
425
+ # Mask out invalid token IDs (same as prefill)
426
+ if step_logits.size(-1) > 100256:
427
+ step_logits[100256:] = float("-inf")
428
+ if blocked_tensor is not None and blocked_tensor.numel() > 0:
429
+ step_logits[blocked_tensor] = float("-inf")
430
+
431
+ # Standard recency penalty (moderate, gentle penalty to prevent immediate looping)
432
+ if not disable_repetition_filter and generated and rep_penalty > 1.0:
433
+ recent = generated[-128:]
434
+ recent_set = list(set(recent))
435
+ if recent_set:
436
+ recent_tensor = torch.tensor(recent_set, dtype=torch.long, device=device)
437
+ gathered = step_logits[recent_tensor]
438
+ pos_mask = gathered > 0
439
+ step_logits[recent_tensor] = torch.where(pos_mask, gathered / rep_penalty, gathered * rep_penalty)
440
+
441
+ next_token = _sample(step_logits, generated_gpu[:step], temperature,
442
+ 1.0, top_k, top_p, blocked_ids=blocked_tensor, generated_list=generated,
443
+ greedy=greedy, disable_repetition_filter=disable_repetition_filter,
444
+ disable_ngram_block=disable_ngram_block, disable_token_filter=disable_token_filter)
445
+
446
+ if next_token == enc.eot_token:
447
+ break
448
+
449
+ generated.append(next_token)
450
+ generated_gpu[step] = next_token
451
+
452
+ # Token-based stop checks (robust to BPE fragmentation)
453
+ recent_str = enc.decode([t for t in generated[-20:] if t < 100256])
454
+ stop_hit = False
455
+ for s in stop_texts:
456
+ if s in recent_str:
457
+ stop_hit = True
458
+
459
+ # Trim the generated list up to the stop text (but keep </answer> if it's the stop text)
460
+ if s == "</answer>":
461
+ # Let it yield the remaining chunk, then return
462
+ pass
463
+ else:
464
+ # We would need complex logic to trim exactly, but for simplicity, we just return
465
+ pass
466
+
467
+ if stream and len(generated) > last_yield_tok:
468
+ safe_gen = [t for t in generated[last_yield_tok:] if t < 100256]
469
+ if safe_gen:
470
+ chunk = enc.decode(safe_gen)
471
+ # Avoid printing the stop text if it's not </answer>
472
+ if s != "</answer>" and chunk.endswith(s):
473
+ chunk = chunk[:-len(s)]
474
+ yield chunk, PONDER_FIXED
475
+ return
476
+
477
+ # Yield streaming chunk
478
+ if _has_repeated_suffix(generated, min_size=1, max_size=6, repeats=3):
479
+ if stream and len(generated) > last_yield_tok:
480
+ safe_gen = [t for t in generated[last_yield_tok:] if t < 100256]
481
+ if safe_gen:
482
+ chunk = enc.decode(safe_gen)
483
+ yield chunk, PONDER_FIXED
484
+ break
485
+
486
+ # Stream: decode only the newly generated token slice
487
+ if stream:
488
+ if len(generated) > last_yield_tok:
489
+ safe_gen = [t for t in generated[last_yield_tok:] if t < 100256]
490
+ if safe_gen:
491
+ new_part = enc.decode(safe_gen)
492
+ if new_part:
493
+ yield new_part, PONDER_FIXED
494
+ last_yield_tok = len(generated)
495
+
496
+ if not stream:
497
+ safe_gen = [t for t in generated if t < 100256]
498
+ full = enc.decode(safe_gen) if safe_gen else ""
499
+ yield full, PONDER_FIXED
v3_modules.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CortexV7 v3 β€” New modules: YaRN, HyperConnections, MTP
3
+ These get imported into Model.py
4
+ """
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ import math
9
+ from typing import Optional, List, Tuple
10
+
11
+ try:
12
+ from flash_attn.ops.rms_norm import rms_norm
13
+ HAS_FLASH_RMSNORM = True
14
+ except ImportError:
15
+ HAS_FLASH_RMSNORM = False
16
+
17
+ class RMSNorm(nn.Module):
18
+ def __init__(self, dim: int, eps: float = 1e-6):
19
+ super().__init__()
20
+ self.weight = nn.Parameter(torch.ones(dim))
21
+ self.eps = eps
22
+
23
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
24
+ # Skip C++ Flash RMSNorm during torch.compile (causes graph breaks)
25
+ if HAS_FLASH_RMSNORM and x.is_cuda and x.dtype in (torch.float16, torch.bfloat16):
26
+ if not (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling()):
27
+ return rms_norm(x, self.weight, self.eps)
28
+
29
+ x_float = x.float()
30
+ norm = torch.rsqrt(x_float.pow(2).mean(-1, keepdim=True) + self.eps)
31
+ return (x_float * norm).to(x.dtype) * self.weight
32
+
33
+ # ─────────────────────────────────────────────────────────────────────────────
34
+ # YaRN-ENABLED ROTARY EMBEDDINGS
35
+ # ─────────────────────────────────────────────────────────────────────────────
36
+
37
+ class YaRNRotaryEmbedding(nn.Module):
38
+ """YaRN RoPE (Yet another RoPE extensioN).
39
+
40
+ Trains at original_max_len (2048). Extends to original_max_len * yarn_scale
41
+ (e.g. 8192) without quality loss via NTK-aware interpolation.
42
+
43
+ - High-freq dims: unchanged (encode local token patterns)
44
+ - Low-freq dims: interpolated (encode absolute position)
45
+ - Smooth ramp between the two controlled by beta_fast/beta_slow
46
+ """
47
+
48
+ def __init__(self, dim: int, max_seq_len: int = 8192, base: int = 10000,
49
+ original_max_len: int = 2048, yarn_scale: float = 4.0,
50
+ yarn_beta_fast: float = 32.0, yarn_beta_slow: float = 1.0):
51
+ super().__init__()
52
+ self.dim = dim
53
+ self.max_seq_len = max_seq_len
54
+ self.original_max_len = original_max_len
55
+ self.yarn_scale = yarn_scale
56
+
57
+ # NTK-aware frequency mixing
58
+ freq_extra = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
59
+ freq_inter = 1.0 / (yarn_scale * base ** (torch.arange(0, dim, 2).float() / dim))
60
+
61
+ low = max(int(math.floor(
62
+ dim * math.log(original_max_len / (yarn_beta_fast * 2 * math.pi))
63
+ / (2 * math.log(base)))), 0)
64
+ high = min(int(math.ceil(
65
+ dim * math.log(original_max_len / (yarn_beta_slow * 2 * math.pi))
66
+ / (2 * math.log(base)))), dim // 2 - 1)
67
+
68
+ mask = torch.zeros(dim // 2)
69
+ for i in range(dim // 2):
70
+ if i < low:
71
+ mask[i] = 0.0
72
+ elif i > high:
73
+ mask[i] = 1.0
74
+ else:
75
+ mask[i] = (i - low) / max(high - low, 1)
76
+
77
+ inv_freq = freq_extra * (1.0 - mask) + freq_inter * mask
78
+ self.register_buffer("inv_freq", inv_freq)
79
+
80
+ # Attention scaling for extended sequences
81
+ self.attn_scale = 0.1 * math.log(yarn_scale) + 1.0
82
+
83
+ self._cached_cos: Optional[torch.Tensor] = None
84
+ self._cached_sin: Optional[torch.Tensor] = None
85
+ self._cached_seq_len: int = 0
86
+
87
+ def forward(self, x: torch.Tensor, seq_len: Optional[int] = None):
88
+ if seq_len is None:
89
+ seq_len = x.shape[1]
90
+ if torch.compiler.is_compiling():
91
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
92
+ freqs = torch.outer(t, self.inv_freq)
93
+ return freqs.cos(), freqs.sin()
94
+ if seq_len > self._cached_seq_len or self._cached_cos is None:
95
+ self._cached_seq_len = seq_len
96
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
97
+ freqs = torch.outer(t, self.inv_freq)
98
+ self._cached_cos = freqs.cos()
99
+ self._cached_sin = freqs.sin()
100
+ return self._cached_cos[:seq_len], self._cached_sin[:seq_len]
101
+
102
+
103
+ # ─────────────────────────────────────────────────────────────────────────────
104
+ # HYPER-CONNECTIONS (ICLR 2025)
105
+ # ─────────────────────────────────────────────────────────────────────────────
106
+
107
+ class HyperConnection(nn.Module):
108
+ """Learnable residual connections replacing standard x + f(x).
109
+
110
+ Maintains n_streams parallel hidden streams. The "active" stream (index 0)
111
+ gets transformed by the sublayer, then all streams are contracted back
112
+ to a single representation via learned weights.
113
+
114
+ At initialization, behaves exactly like a standard residual connection.
115
+ During training, learns optimal cross-layer information routing.
116
+ """
117
+
118
+ def __init__(self, dim: int, n_streams: int = 2, layer_id: int = 0,
119
+ total_layers: int = 1):
120
+ super().__init__()
121
+ self.n_streams = n_streams
122
+ self.dim = dim
123
+
124
+ # Expansion: scale factors for creating each stream from input
125
+ alpha_init = torch.zeros(n_streams)
126
+ alpha_init[0] = 1.0 # active stream = full signal
127
+ for i in range(1, n_streams):
128
+ alpha_init[i] = 1.0 # residual streams = full signal too
129
+ self.alpha = nn.Parameter(alpha_init)
130
+
131
+ beta_init = torch.zeros(n_streams)
132
+ beta_init[0] = 1.0 # full sublayer contribution
133
+ beta_init[1] = 1.0 # full residual (starts exactly as standard x + f(x))
134
+ self.beta = nn.Parameter(beta_init)
135
+
136
+ def forward(self, x: torch.Tensor, sublayer_out: torch.Tensor) -> torch.Tensor:
137
+ """Apply hyper-connection: merge sublayer output with residual streams.
138
+
139
+ x: original input to the sublayer
140
+ sublayer_out: output of the sublayer (e.g. attention or FFN)
141
+ returns: merged output
142
+ """
143
+ # Stream 0 = transformed, streams 1+ = residual
144
+ result = self.beta[0] * sublayer_out
145
+ for i in range(1, self.n_streams):
146
+ result = result + self.beta[i] * self.alpha[i] * x
147
+
148
+ return result
149
+
150
+
151
+ # ─────────────────────────────────────────────────────────────────────────────
152
+ # MULTI-TOKEN PREDICTION HEAD (DeepSeek-V3 style)
153
+ # ─────────────────────────────────────────────────────────────────────────────
154
+
155
+ class MTPHead(nn.Module):
156
+ """Lightweight sequential MTP head.
157
+
158
+ Takes hidden state from previous depth + ground-truth embedding of the
159
+ target token, projects them together, and produces a new hidden state
160
+ that gets projected to vocabulary via the shared output head.
161
+
162
+ Each MTP head adds only ~3.3M params at dim=1280.
163
+ """
164
+
165
+ def __init__(self, dim: int):
166
+ super().__init__()
167
+ self.proj = nn.Linear(dim * 2, dim, bias=False)
168
+ self.norm = RMSNorm(dim)
169
+ nn.init.normal_(self.proj.weight, std=0.02)
170
+
171
+ def forward(self, h_prev: torch.Tensor,
172
+ token_embed: torch.Tensor) -> torch.Tensor:
173
+ """
174
+ h_prev: [B, S, dim] hidden state from previous depth
175
+ token_embed: [B, S, dim] embedding of ground-truth token at this offset
176
+ returns: [B, S, dim] new hidden state for vocab projection
177
+ """
178
+ combined = torch.cat([h_prev, token_embed], dim=-1)
179
+ return self.norm(self.proj(combined))