CLIWorks commited on
Commit
3b599e1
·
verified ·
1 Parent(s): 56d3752

Upload tk-spider.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tk-spider.py +1659 -0
tk-spider.py ADDED
@@ -0,0 +1,1659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Spider: MoE + RDT (Recurrent-Depth Transformer) architecture v5.
3
+
4
+ Canonical architecture ported from mythos-fineweb-moe.py (SpiderPortal v5-Dense)
5
+ with the following adaptations per Phase 02 decisions:
6
+
7
+ - Full Spider rebrand (no SpiderPortal/SpiderPortal prefix) per D-07
8
+ - Byte-level vocab: 272 tokens (256 bytes + 16 specials) per D-06
9
+ - MLA (Multi-Latent Attention) with compressed KV cache per D-10
10
+ - Engram conditional memory at recurrent layers 1 and 4
11
+ - MoE: 16 routed experts + 1 shared expert, top-1 routing
12
+ - Sliding window attention (sliding_window=8192) with 256k context (YaRN factor=8.0)
13
+ - Weight-tied embeddings per v5 canonical config (tie_word_embeddings=True)
14
+ - LTI Injection + ACT Halting + LoRA Adapter for RDT loops
15
+ - BoundaryPredictor + downsample/upsample for FlexiToken integration
16
+ - 272-token byte-level vocab with sentinel tokens for multimodal (D-11)
17
+
18
+ Architecture: RDT (2 prelude + 6 recurrent + 2 coda) with:
19
+ - 2x Prelude (MLA + dense FFN)
20
+ - 6x Recurrent (MLA + Engram@L1,L4 + MoE) -- with gradient checkpointing
21
+ - 2x Coda (MLA + dense FFN)
22
+ - LTI Injection + ACT Halting + LoRA Adapter
23
+
24
+ Config: hidden_size=2048, 6 recurrent layers, 32 experts, top-2 routing
25
+ """
26
+
27
+ import math
28
+ import os
29
+ import sys as _sys
30
+ from dataclasses import dataclass, field
31
+ from typing import Dict, List, Optional, Tuple
32
+
33
+ import torch
34
+ import torch.nn as nn
35
+ import torch.nn.functional as F
36
+ from torch.nn import CrossEntropyLoss
37
+
38
+ try:
39
+ _sys.path.insert(0, os.path.expanduser("~/TileKernels"))
40
+ import tile_kernels as _tk
41
+ _TK_AVAILABLE = True
42
+ except Exception:
43
+ _tk = None
44
+ _TK_AVAILABLE = False
45
+
46
+
47
+ # ============================================================================
48
+ # Spider Configuration
49
+ # ============================================================================
50
+
51
+ @dataclass
52
+ class SpiderConfig:
53
+ """Spider model configuration (hidden_size=2048, byte-level vocab).
54
+
55
+ Based on mythos-fineweb-moe.py SpiderPortalConfig with byte-level
56
+ tokenization, MLA attention, and Engram memory.
57
+ """
58
+ # Core architecture
59
+ vocab_size: int = 272 # 256 bytes + 16 specials (D-06)
60
+ hidden_size: int = 2048
61
+ num_hidden_layers: int = 6 # recurrent layers
62
+ num_attention_heads: int = 16
63
+ num_key_value_heads: int = 4 # not used directly in MLA but kept for compat
64
+ intermediate_size: int = 1024
65
+ hidden_act: str = "silu"
66
+
67
+ # MoE configuration (D-20, D-21: shared-projection MoE)
68
+ num_experts: int = 32
69
+ num_experts_per_tok: int = 2
70
+ num_shared_experts: int = 1
71
+ router_aux_loss_coef: float = 0.05
72
+ shared_intermediate_size: int = 6144
73
+ expert_core_rank: int = 256
74
+ shared_expert_intermediate_size: int = 7424
75
+ prelude_coda_intermediate_size: int = 4096
76
+
77
+ # RDT configuration
78
+ max_loop_iters: int = 16
79
+ act_threshold: float = 0.5
80
+ prelude_layers: int = 2
81
+ coda_layers: int = 2
82
+ lora_rank: int = 128
83
+ loop_embed_dim: int = 128
84
+
85
+ # MLA parameters (DeepSeek-V2 style, scaled for hidden_size=2048)
86
+ kv_lora_rank: int = 128
87
+ q_lora_rank: int = 256
88
+ qk_rope_head_dim: int = 64
89
+ qk_nope_head_dim: int = 64
90
+ v_head_dim: int = 64
91
+
92
+ # Engram parameters (DeepSeek conditional memory, offloaded to CPU)
93
+ engram_layers: List[int] = field(default_factory=lambda: [1, 4])
94
+ engram_ngram_orders: Tuple[int, ...] = (2, 3)
95
+ engram_hash_heads: int = 4
96
+ engram_table_size: int = 8191 # prime, sized for byte vocab=272
97
+ engram_conv_kernel: int = 4
98
+ engram_conv_dilation: int = 3
99
+ engram_dim: int = 128 # per-head embedding dimension
100
+ engram_offload: bool = True # offload embed table to CPU (DeepSeek style)
101
+
102
+ # Attention / RoPE
103
+ max_position_embeddings: int = 262144 # 256k context
104
+ rope_theta: float = 10000000.0
105
+ rope_scaling: Optional[Dict] = field(default_factory=lambda: {
106
+ "type": "yarn",
107
+ "factor": 8.0,
108
+ "original_max_position_embeddings": 32768,
109
+ })
110
+ sliding_window: int = 8192 # local attention window
111
+ attention_dropout: float = 0.0
112
+ rms_norm_eps: float = 1e-6
113
+ initializer_range: float = 0.02
114
+
115
+ # Embeddings / head
116
+ tie_word_embeddings: bool = True # per v5 canonical config
117
+
118
+ # Multimodal
119
+ vision_hidden_size: int = 2048
120
+ audio_hidden_size: int = 512
121
+ vision_num_frames: int = 60
122
+ vision_tokens_per_frame: int = 256
123
+ vision_temporal_tokens: int = 64
124
+ vision_temporal_layers: int = 2
125
+
126
+ # Metadata
127
+ model_type: str = "spider"
128
+ torch_dtype: str = "bfloat16"
129
+
130
+ # BoundaryPredictor (for FlexiToken integration)
131
+ bp_d_inner: int = 8192
132
+
133
+ @property
134
+ def head_dim(self):
135
+ return self.qk_nope_head_dim + self.qk_rope_head_dim # 128
136
+
137
+
138
+ def spider_flexitokens_997m() -> SpiderConfig:
139
+ """Spider-FLEXITOKENS 995.1M config per D-20."""
140
+ return SpiderConfig()
141
+
142
+
143
+ # ============================================================================
144
+ # Sentinel Token Vocabulary (D-06, D-11)
145
+ # ============================================================================
146
+
147
+ # 272-token vocab: 256 bytes + 16 specials
148
+ # Sentinel tokens at indices 259-264 mark modality region boundaries
149
+ SENTINEL_TOKENS = {
150
+ 'PAD': 256, 'BOS': 257, 'EOS': 258,
151
+ 'IMG_START': 259, 'IMG_END': 260,
152
+ 'AUD_START': 261, 'AUD_END': 262,
153
+ 'VID_START': 263, 'VID_END': 264,
154
+ 'MASK': 265, 'im_start': 266, 'im_end': 267,
155
+ 'prefix': 268, 'suffix': 269, 'middle': 270,
156
+ 'THINK': 271,
157
+ }
158
+
159
+ # Sentinel pairs for modality regions (start_id, end_id)
160
+ _SENTINEL_PAIRS = [
161
+ (SENTINEL_TOKENS['IMG_START'], SENTINEL_TOKENS['IMG_END']), # (259, 260)
162
+ (SENTINEL_TOKENS['AUD_START'], SENTINEL_TOKENS['AUD_END']), # (261, 262)
163
+ (SENTINEL_TOKENS['VID_START'], SENTINEL_TOKENS['VID_END']), # (263, 264)
164
+ ]
165
+
166
+ # Set of modality sentinel token IDs (259-264 only)
167
+ _MODALITY_SENTINEL_IDS = {259, 260, 261, 262, 263, 264}
168
+
169
+ # Reverse mapping (computed once at module level, per IN-01)
170
+ _TOKEN_NAMES_BY_ID = {v: k for k, v in SENTINEL_TOKENS.items()}
171
+
172
+
173
+ def is_sentinel_token(token_id: int) -> bool:
174
+ """Return True if token_id is one of the 6 modality sentinel tokens (259-264).
175
+
176
+ These are the sentinel tokens that mark modality region boundaries:
177
+ IMG_START/END, AUD_START/END, VID_START/END.
178
+ Other special tokens (PAD, BOS, EOS, MASK, etc.) are NOT modality sentinels.
179
+ """
180
+ return token_id in _MODALITY_SENTINEL_IDS
181
+
182
+
183
+ def create_modality_mask(input_ids: torch.Tensor, strict: bool = True) -> torch.Tensor:
184
+ """Create boolean mask (B×L) marking sentinel and modality token positions.
185
+
186
+ Per D-11: Sentinel-gated passthrough ensures modality tokens bypass the
187
+ BoundaryPredictor entirely. This mask marks positions where:
188
+ - Sentinel tokens (IMG_START/END, AUD_START/END, VID_START/END) appear
189
+ - Modality tokens (between sentinel pairs) appear
190
+
191
+ The BoundaryPredictor uses this mask to force boundary=1.0 at these
192
+ positions, ensuring no boundary merging across modality boundaries.
193
+
194
+ Args:
195
+ input_ids: Token IDs of shape [B, L] with values in 0-271 range.
196
+ strict: If True, raise on mismatched sentinel pairs (training mode).
197
+ If False, skip mismatched pairs gracefully (generation mode).
198
+
199
+ Returns:
200
+ Boolean tensor of shape [B, L], True at sentinel+modality positions.
201
+
202
+ Raises:
203
+ ValueError: If strict=True and sentinel pairs are mismatched.
204
+ """
205
+ B, L = input_ids.shape
206
+ mask = torch.zeros(B, L, dtype=torch.bool, device=input_ids.device)
207
+
208
+ # Mark direct sentinel token positions
209
+ for sid in _MODALITY_SENTINEL_IDS:
210
+ mask |= (input_ids == sid)
211
+
212
+ # Mark regions between sentinel pairs (inclusive of sentinels)
213
+ for start_id, end_id in _SENTINEL_PAIRS:
214
+ for b in range(B):
215
+ starts = (input_ids[b] == start_id).nonzero(as_tuple=True)[0]
216
+ ends = (input_ids[b] == end_id).nonzero(as_tuple=True)[0]
217
+
218
+ # T-02-04 mitigation: validate sentinel pairs are matched (strict mode only)
219
+ if strict and len(starts) != len(ends):
220
+ raise ValueError(
221
+ f"Batch {b}: mismatched sentinel pairs — "
222
+ f"{len(starts)} {_TOKEN_NAMES_BY_ID[start_id]}(s) vs "
223
+ f"{len(ends)} {_TOKEN_NAMES_BY_ID[end_id]}(s). "
224
+ f"Every {_TOKEN_NAMES_BY_ID[start_id]} must have a matching "
225
+ f"{_TOKEN_NAMES_BY_ID[end_id]}."
226
+ )
227
+
228
+ # Match pairs min(starts, ends) — skip unmatched in non-strict mode
229
+ n_pairs = min(len(starts), len(ends))
230
+ for i in range(n_pairs):
231
+ s, e = starts[i].item(), ends[i].item()
232
+ if s > e:
233
+ if strict:
234
+ raise ValueError(
235
+ f"Batch {b}: {_TOKEN_NAMES_BY_ID[start_id]} at position {s} "
236
+ f"appears after {_TOKEN_NAMES_BY_ID[end_id]} at position {e}. "
237
+ f"Sentinel pairs must be properly ordered."
238
+ )
239
+ continue
240
+ mask[b, s:e + 1] = True
241
+
242
+ return mask
243
+
244
+
245
+ # ============================================================================
246
+ # RMSNorm
247
+ # ============================================================================
248
+
249
+ class SpiderRMSNorm(nn.Module):
250
+ """RMS normalization (bf16-only, no dtype conversions)."""
251
+
252
+ def __init__(self, hidden_size, eps=1e-6):
253
+ super().__init__()
254
+ self.weight = nn.Parameter(torch.ones(hidden_size, dtype=torch.float32)) # IN-02: RMSNorm weight is float32 per convention
255
+ self.variance_epsilon = eps
256
+
257
+ def forward(self, hidden_states):
258
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
259
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
260
+ return self.weight * hidden_states
261
+
262
+
263
+ # ============================================================================
264
+ # MLA: Multi-Latent Attention (DeepSeek-V2 style)
265
+ # ============================================================================
266
+
267
+ class SpiderMLA(nn.Module):
268
+ """Multi-Latent Attention with compressed KV cache.
269
+
270
+ For hidden_size=2048, num_heads=16:
271
+ - qk_nope_head_dim=64, qk_rope_head_dim=64 -> total head_dim=128
272
+ - kv_lora_rank=128 -> 10.7x compression vs full 2048-dim KV
273
+ - v_head_dim=64 -> value projection
274
+ - sliding_window=8192 -> local attention window
275
+ """
276
+
277
+ def __init__(self, config: SpiderConfig):
278
+ super().__init__()
279
+ self.config = config
280
+ self.hidden_size = config.hidden_size
281
+ self.num_heads = config.num_attention_heads
282
+ self.kv_lora_rank = config.kv_lora_rank
283
+ self.q_lora_rank = config.q_lora_rank
284
+ self.qk_rope_head_dim = config.qk_rope_head_dim
285
+ self.qk_nope_head_dim = config.qk_nope_head_dim
286
+ self.v_head_dim = config.v_head_dim
287
+ self.head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
288
+ self.sliding_window = getattr(config, 'sliding_window', 0)
289
+
290
+ # Q projection: optional low-rank -> full Q
291
+ if self.q_lora_rank > 0:
292
+ self.q_a_proj = nn.Linear(config.hidden_size, self.q_lora_rank, bias=False)
293
+ self.q_a_layernorm = SpiderRMSNorm(self.q_lora_rank)
294
+ self.q_b_proj = nn.Linear(self.q_lora_rank, self.num_heads * self.head_dim, bias=False)
295
+ else:
296
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
297
+
298
+ # KV compression: hidden -> kv_lora_rank (shared latent)
299
+ self.kv_a_proj_with_mqa = nn.Linear(
300
+ config.hidden_size,
301
+ self.kv_lora_rank + self.qk_rope_head_dim,
302
+ bias=False,
303
+ )
304
+ self.kv_a_layernorm = SpiderRMSNorm(self.kv_lora_rank)
305
+ # Decompress: kv_lora_rank -> nope heads + v heads
306
+ self.kv_b_proj = nn.Linear(
307
+ self.kv_lora_rank,
308
+ self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
309
+ bias=False,
310
+ )
311
+ # Output projection: [hidden_size, num_heads * v_head_dim]
312
+ # Per D-08 and MLA architecture: o_proj maps from num_heads*v_head_dim back to hidden_size
313
+ self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=False)
314
+
315
+ # RoPE frequencies
316
+ rope_scaling = getattr(config, 'rope_scaling', None)
317
+ if rope_scaling and rope_scaling.get("type") == "yarn":
318
+ factor = rope_scaling.get("factor", 1.0)
319
+ orig_max_pos = rope_scaling.get(
320
+ "original_max_position_embeddings", config.max_position_embeddings
321
+ )
322
+ inv_freq = self._compute_yarn_inv_freq(
323
+ self.qk_rope_head_dim, config.rope_theta, factor, orig_max_pos
324
+ )
325
+ else:
326
+ inv_freq = 1.0 / (
327
+ config.rope_theta
328
+ ** (torch.arange(0, self.qk_rope_head_dim, 2).float() / self.qk_rope_head_dim)
329
+ )
330
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
331
+
332
+ @staticmethod
333
+ def _compute_yarn_inv_freq(head_dim, rope_theta, factor, orig_max, beta_fast=32.0, beta_slow=1.0):
334
+ dim = head_dim
335
+ orig_inv_freq = 1.0 / (rope_theta ** (torch.arange(0, dim, 2).float() / dim))
336
+ pos_freqs = torch.arange(0, dim, 2).float() / dim
337
+ beta = (pos_freqs * math.log(rope_theta) / math.log(orig_max))
338
+ scale = torch.where(
339
+ beta < beta_slow, torch.ones_like(beta),
340
+ torch.where(
341
+ beta > beta_fast, torch.ones_like(beta) / factor,
342
+ 1.0 - (beta - beta_slow) / (beta_fast - beta_slow) * (1.0 - 1.0 / factor)
343
+ )
344
+ )
345
+ return orig_inv_freq * scale
346
+
347
+ def _rotate_half(self, x):
348
+ x1 = x[..., :x.shape[-1] // 2]
349
+ x2 = x[..., x.shape[-1] // 2:]
350
+ return torch.cat((-x2, x1), dim=-1)
351
+
352
+ def _apply_rotary(self, x, cos, sin):
353
+ return (x * cos) + (self._rotate_half(x) * sin)
354
+
355
+ def forward(
356
+ self,
357
+ hidden_states: torch.Tensor,
358
+ attention_mask=None,
359
+ position_ids=None,
360
+ past_key_value=None,
361
+ use_cache=False,
362
+ ):
363
+ bsz, q_len, _ = hidden_states.size()
364
+
365
+ # Q projection
366
+ if self.q_lora_rank > 0:
367
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
368
+ else:
369
+ q = self.q_proj(hidden_states)
370
+ q = q.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
371
+ q_nope, q_rope = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
372
+
373
+ # KV: compress to latent, then decompress
374
+ kv_hidden = self.kv_a_proj_with_mqa(hidden_states)
375
+ kv_latent, k_rope = torch.split(
376
+ kv_hidden, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
377
+ )
378
+ kv_latent_norm = self.kv_a_layernorm(kv_latent)
379
+ kv_b_out = self.kv_b_proj(kv_latent_norm)
380
+ k_nope, v = torch.split(
381
+ kv_b_out,
382
+ [self.num_heads * self.qk_nope_head_dim, self.num_heads * self.v_head_dim],
383
+ dim=-1,
384
+ )
385
+
386
+ k_nope = k_nope.view(bsz, q_len, self.num_heads, self.qk_nope_head_dim).transpose(1, 2)
387
+ v = v.view(bsz, q_len, self.num_heads, self.v_head_dim).transpose(1, 2)
388
+ k_rope = k_rope.unsqueeze(1) # [B, 1, L, qk_rope_head_dim]
389
+
390
+ # RoPE on Q and K rope parts
391
+ if position_ids is None:
392
+ position_ids = torch.arange(q_len, device=hidden_states.device).unsqueeze(0).expand(bsz, -1)
393
+ max_pos = position_ids.max().item() + 1
394
+ seq_len = max(max_pos, q_len)
395
+ t = torch.arange(seq_len, device=hidden_states.device, dtype=self.inv_freq.dtype)
396
+ freqs = torch.outer(t, self.inv_freq)
397
+ emb = torch.cat((freqs, freqs), dim=-1)
398
+ cos, sin = emb.cos(), emb.sin()
399
+ cos_full = cos[position_ids].unsqueeze(1)
400
+ sin_full = sin[position_ids].unsqueeze(1)
401
+
402
+ q_rope = self._apply_rotary(q_rope, cos_full, sin_full)
403
+ k_rope = self._apply_rotary(k_rope, cos_full, sin_full)
404
+
405
+ # Assemble full K
406
+ k_rope_expanded = k_rope.expand(-1, self.num_heads, -1, -1)
407
+ k_full = torch.cat([k_nope, k_rope_expanded], dim=-1)
408
+ q_full = torch.cat([q_nope, q_rope], dim=-1)
409
+
410
+ # KV cache
411
+ past_kv = None
412
+ if past_key_value is not None:
413
+ k_full = torch.cat([past_key_value[0], k_full], dim=2)
414
+ v = torch.cat([past_key_value[1], v], dim=2)
415
+ if use_cache:
416
+ past_kv = (k_full, v)
417
+
418
+ # Attention with SDPA
419
+ attn_mask = None
420
+ if self.sliding_window > 0 and k_full.shape[2] > self.sliding_window:
421
+ kv_len = k_full.shape[2]
422
+ q_positions = torch.arange(kv_len - q_len, kv_len, device=q_full.device)
423
+ k_positions = torch.arange(kv_len, device=q_full.device)
424
+ diff = q_positions.unsqueeze(1) - k_positions.unsqueeze(0)
425
+ causal = diff >= 0
426
+ window = diff < self.sliding_window
427
+ attn_mask = (causal & window).float().unsqueeze(0).unsqueeze(0)
428
+ attn_mask = attn_mask.masked_fill(attn_mask == 0, float('-inf'))
429
+
430
+ attn_output = F.scaled_dot_product_attention(
431
+ q_full, k_full, v,
432
+ attn_mask=attn_mask,
433
+ dropout_p=self.config.attention_dropout if self.training else 0.0,
434
+ is_causal=(attn_mask is None),
435
+ )
436
+ attn_output = attn_output.transpose(1, 2).contiguous()
437
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
438
+ return self.o_proj(attn_output), past_kv
439
+
440
+
441
+ # ============================================================================
442
+ # Engram: Conditional Memory via Scalable Lookup (DeepSeek style)
443
+ # ============================================================================
444
+
445
+ def _tokenizer_compress(token_ids, vocab_size=272):
446
+ """Simulate NFKC + lowercase canonical ID projection.
447
+
448
+ Per D-06: vocab_size=272 for byte-level Spider vocab.
449
+ """
450
+ return token_ids % (vocab_size * 77 // 100)
451
+
452
+
453
+ class SpiderEngram(nn.Module):
454
+ """Conditional memory module via NN-gram lookup.
455
+
456
+ Applied only at specific recurrent layers (config.engram_layers).
457
+ Ported from SpiderPortalEngram in mythos-fineweb-moe.py.
458
+ """
459
+
460
+ def __init__(self, config: SpiderConfig):
461
+ super().__init__()
462
+ self.config = config
463
+ self.ngram_orders = list(config.engram_ngram_orders)
464
+ self.num_heads_per_order = config.engram_hash_heads
465
+ self.table_size = config.engram_table_size
466
+ self.d_mem = config.engram_dim
467
+
468
+ self.total_mem_dim = len(self.ngram_orders) * self.num_heads_per_order * self.d_mem
469
+
470
+ # Stacked embedding table with offsets: [orders, heads, table_size, d_mem]
471
+ # Per DeepSeek Engram: static memory, offloaded to CPU, accessed via deterministic hash.
472
+ embed_data = torch.randn(len(self.ngram_orders), self.num_heads_per_order, self.table_size, self.d_mem) * 0.02
473
+ if config.engram_offload:
474
+ self.register_buffer("embed", embed_data, persistent=True)
475
+ else:
476
+ self.embed = nn.Parameter(embed_data)
477
+
478
+ seeds = []
479
+ for _order in self.ngram_orders:
480
+ for h in range(self.num_heads_per_order):
481
+ seeds.append((h + 1) * 2654435761)
482
+ self.register_buffer("hash_seeds", torch.tensor(seeds, dtype=torch.int64), persistent=False)
483
+
484
+ self.W_k = nn.Linear(self.total_mem_dim, config.hidden_size, bias=False)
485
+ self.W_v = nn.Linear(self.total_mem_dim, config.hidden_size, bias=False)
486
+
487
+ self.conv = nn.Conv1d(
488
+ config.hidden_size, config.hidden_size,
489
+ kernel_size=config.engram_conv_kernel,
490
+ padding=config.engram_conv_kernel - 1,
491
+ groups=config.hidden_size,
492
+ )
493
+ self.conv_dilation = config.engram_conv_dilation
494
+
495
+ with torch.no_grad():
496
+ self.conv.weight.zero_()
497
+ if self.conv.bias is not None:
498
+ self.conv.bias.zero_()
499
+
500
+ self.q_norm = SpiderRMSNorm(config.hidden_size)
501
+ self.k_norm = SpiderRMSNorm(config.hidden_size)
502
+
503
+ def _compute_hash(self, compressed, n, head_counter, bsz, seq_len):
504
+ """Compute n-gram hash indices (PyTorch-only path, no Numba/CUDA dependency)."""
505
+ pad = torch.zeros(bsz, n - 1, dtype=compressed.dtype, device=compressed.device)
506
+ padded = torch.cat([pad, compressed], dim=1)
507
+ ngrams = torch.stack([padded[:, i : i + seq_len] for i in range(n)], dim=-1)
508
+ h_val = torch.zeros(bsz, seq_len, dtype=torch.int64, device=compressed.device)
509
+ for i in range(n):
510
+ h_val = h_val * 31 + ngrams[:, :, i].to(torch.int64)
511
+ h_val = h_val % self.table_size
512
+ return h_val
513
+
514
+ def _retrieve(self, token_ids):
515
+ """Retrieve memory vectors for a batch of token sequences."""
516
+ bsz, seq_len = token_ids.shape
517
+ compressed = _tokenizer_compress(token_ids)
518
+
519
+ # PyTorch fallback (CPU and GPU, no external kernel dependency)
520
+ all_parts = []
521
+ head_counter = 0
522
+ for order_idx, n in enumerate(self.ngram_orders):
523
+ h_val = self._compute_hash(compressed, n, head_counter, bsz, seq_len)
524
+ seeds_slice = self.hash_seeds[head_counter : head_counter + self.num_heads_per_order]
525
+ indices_pt = (h_val.unsqueeze(-1) * seeds_slice.view(1, 1, -1)) % self.table_size
526
+ emb_table = self.embed[order_idx]
527
+ idx = indices_pt.permute(0, 2, 1).unsqueeze(-1).expand(-1, -1, -1, self.d_mem)
528
+ mem = torch.gather(emb_table.unsqueeze(0).expand(bsz, -1, -1, -1), dim=2, index=idx)
529
+ mem = mem.permute(0, 2, 1, 3).reshape(bsz, seq_len, self.num_heads_per_order * self.d_mem)
530
+ all_parts.append(mem)
531
+ head_counter += self.num_heads_per_order
532
+ return torch.cat(all_parts, dim=-1)
533
+
534
+ def forward(self, hidden_states, token_ids, layer_id: int):
535
+ mem = self._retrieve(token_ids)
536
+
537
+ q = hidden_states
538
+ k = self.W_k(mem)
539
+ v = self.W_v(mem)
540
+ q_norm = self.q_norm(q)
541
+ k_norm = self.k_norm(k)
542
+ alpha = torch.sigmoid(
543
+ (q_norm * k_norm).sum(dim=-1, keepdim=True) / math.sqrt(q.shape[-1])
544
+ )
545
+ v_gated = alpha * v
546
+ v_gated_t = v_gated.transpose(1, 2)
547
+ conv_out = self.conv(v_gated_t)
548
+ conv_out = conv_out[:, :, :v_gated_t.shape[-1]]
549
+ conv_out = conv_out.transpose(1, 2)
550
+
551
+ y = F.silu(conv_out) + v_gated
552
+ return y
553
+
554
+
555
+ # ============================================================================
556
+ # FFN Expert (SwiGLU)
557
+ # ============================================================================
558
+
559
+ class SpiderExpert(nn.Module):
560
+ """SwiGLU FFN expert for dense layers and MoE shared expert."""
561
+
562
+ def __init__(self, config: SpiderConfig, intermediate_size=None):
563
+ super().__init__()
564
+ inter_size = intermediate_size or config.intermediate_size
565
+ self.gate_proj = nn.Linear(config.hidden_size, inter_size, bias=False)
566
+ self.up_proj = nn.Linear(config.hidden_size, inter_size, bias=False)
567
+ self.down_proj = nn.Linear(inter_size, config.hidden_size, bias=False)
568
+ self.act_fn = nn.SiLU()
569
+
570
+ def forward(self, hidden_states):
571
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
572
+
573
+
574
+ # ============================================================================
575
+ # Shared-Projection MoE (D-20, D-21: top-2 routing with shared projections)
576
+ # ============================================================================
577
+
578
+ class SimpleMoE(nn.Module):
579
+ """Mixture of Experts with top-1 routing and shared expert.
580
+
581
+ Uses TileKernels for fused routing when available.
582
+ """
583
+
584
+ def __init__(self, config: SpiderConfig):
585
+ super().__init__()
586
+ self.num_experts = config.num_experts
587
+ self.num_experts_per_tok = config.num_experts_per_tok
588
+
589
+ # Shared expert
590
+ self.shared_expert = SpiderExpert(config, intermediate_size=config.intermediate_size)
591
+
592
+ # Routed experts
593
+ self.experts = nn.ModuleList([
594
+ SpiderExpert(config, intermediate_size=config.intermediate_size)
595
+ for _ in range(config.num_experts)
596
+ ])
597
+
598
+ # Router
599
+ self.router = nn.Linear(config.hidden_size, config.num_experts, bias=True)
600
+ self.router.bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32))
601
+
602
+ def _forward_tilekernels(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
603
+ B, L, D = x.shape
604
+ num_tokens = B * L
605
+
606
+ shared_out = self.shared_expert(x)
607
+
608
+ router_logits = self.router(x)
609
+ router_probs = F.softmax(router_logits.float(), dim=-1)
610
+ router_probs_2d = router_probs.reshape(num_tokens, self.num_experts).contiguous()
611
+
612
+ topk_idx = _tk.moe.topk_gate(router_probs_2d, num_topk=1)
613
+ topk_weights = torch.gather(router_probs_2d, -1, topk_idx)
614
+ _, topk_weights_norm = _tk.moe.normalize_weight(topk_weights)
615
+
616
+ (pos_to_expert, pos_to_token, pos_to_token_topk,
617
+ token_topk_to_pos, expert_start, expert_end,
618
+ num_tokens_per_expert, ntp_list) = _tk.moe.get_fused_mapping_kernel.get_fused_mapping(
619
+ topk_idx, self.num_experts, num_expanded_tokens=0, alignment=64,
620
+ )
621
+
622
+ x_flat = x.reshape(num_tokens, D).contiguous()
623
+ x_expanded = _tk.moe.expand_to_fused(x_flat, token_topk_to_pos, pos_to_expert)
624
+
625
+ expanded_out = torch.empty_like(x_expanded)
626
+ for e in range(self.num_experts):
627
+ es = expert_start[e].item()
628
+ ee = expert_end[e].item()
629
+ if es >= ee:
630
+ continue
631
+ expanded_out[es:ee] = self.experts[e](x_expanded[es:ee])
632
+
633
+ routed_out = _tk.moe.reduce_fused(expanded_out, topk_weights_norm, token_topk_to_pos)
634
+ routed_out = routed_out.reshape(B, L, D)
635
+
636
+ z_loss = (router_logits.logsumexp(dim=-1) ** 2).mean()
637
+ return shared_out + routed_out, z_loss
638
+
639
+ def _forward_python(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
640
+ B, L, D = x.shape
641
+
642
+ shared_out = self.shared_expert(x)
643
+
644
+ router_logits = self.router(x)
645
+ router_probs = F.softmax(router_logits, dim=-1)
646
+
647
+ top1_indices = router_probs.argmax(dim=-1)
648
+ top1_probs = router_probs.gather(-1, top1_indices.unsqueeze(-1)).squeeze(-1)
649
+
650
+ x_flat = x.reshape(B * L, D)
651
+ top1_flat = top1_indices.reshape(B * L)
652
+
653
+ expert_outs = torch.zeros_like(x_flat)
654
+ for e in range(self.num_experts):
655
+ mask = (top1_flat == e)
656
+ if mask.any():
657
+ expert_input = x_flat[mask]
658
+ expert_out = self.experts[e](expert_input)
659
+ expert_outs[mask] = expert_out
660
+
661
+ expert_outs = expert_outs.reshape(B, L, D)
662
+ routed_out = expert_outs * top1_probs.unsqueeze(-1)
663
+
664
+ z_loss = (router_logits.logsumexp(dim=-1) ** 2).mean()
665
+ return shared_out + routed_out, z_loss
666
+
667
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
668
+ if _TK_AVAILABLE and x.is_cuda:
669
+ return self._forward_tilekernels(x)
670
+ return self._forward_python(x)
671
+
672
+
673
+ # ============================================================================
674
+ # Shared-Projection MoE (D-20, D-21: top-2 routing with shared projections)
675
+ # ============================================================================
676
+
677
+ class SharedProjectionMoE(nn.Module):
678
+ """Mixture of Experts with shared projections and low-rank expert cores.
679
+
680
+ Per D-20: 32 experts, top-2 routing, shared_intermediate_size=6144.
681
+ Per D-21: Shared up/down projections computed once per token, rank-192
682
+ expert cores specialize on the shared representation.
683
+
684
+ Architecture:
685
+ - shared_up: Linear(hidden, shared_inter) — computed once for all experts
686
+ - shared_down: Linear(shared_inter, hidden) — computed once for all experts
687
+ - W_gate: [num_experts, hidden, expert_core_rank] — per-expert gating
688
+ - W_transform: [num_experts, expert_core_rank, shared_inter] — per-expert transform
689
+ - shared_expert: SpiderExpert(hidden, shared_expert_inter=4096) — always active
690
+
691
+ Forward: shared_hidden = SiLU(shared_up(x))
692
+ routed_out = sum(top2_weights * shared_down(core_i(shared_hidden)))
693
+ output = routed_out + shared_expert(x)
694
+
695
+ Uses TileKernels for fused routing (topk_gate, normalize_weight,
696
+ get_fused_mapping, expand_to_fused, reduce_fused, aux_fi) when available.
697
+ Falls back to Python loop otherwise.
698
+ """
699
+
700
+ def __init__(self, config: SpiderConfig):
701
+ super().__init__()
702
+ self.num_experts = config.num_experts
703
+ self.num_experts_per_tok = config.num_experts_per_tok
704
+ self.shared_inter = config.shared_intermediate_size
705
+ self.expert_core_rank = config.expert_core_rank
706
+ self.hidden_size = config.hidden_size
707
+
708
+ self.shared_up = nn.Linear(config.hidden_size, config.shared_intermediate_size, bias=False)
709
+ self.shared_down = nn.Linear(config.shared_intermediate_size, config.hidden_size, bias=False)
710
+
711
+ self.W_gate = nn.Parameter(
712
+ torch.randn(config.num_experts, config.hidden_size, config.expert_core_rank) * 0.02
713
+ )
714
+ self.W_transform = nn.Parameter(
715
+ torch.randn(config.num_experts, config.expert_core_rank, config.shared_intermediate_size) * 0.02
716
+ )
717
+
718
+ self.shared_expert = SpiderExpert(config, intermediate_size=config.shared_expert_intermediate_size)
719
+
720
+ self.router = nn.Linear(config.hidden_size, config.num_experts, bias=True)
721
+ self.router.bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32))
722
+
723
+ def _forward_tilekernels(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
724
+ B, L, D = x.shape
725
+ num_tokens = B * L
726
+
727
+ shared_hidden = F.silu(self.shared_up(x))
728
+ shared_out = self.shared_expert(x)
729
+
730
+ router_logits = self.router(x)
731
+ router_probs = F.softmax(router_logits.float(), dim=-1)
732
+ router_probs_2d = router_probs.reshape(num_tokens, self.num_experts).contiguous()
733
+
734
+ top2_indices = _tk.moe.topk_gate(router_probs_2d, num_topk=self.num_experts_per_tok)
735
+ top2_weights = torch.gather(router_probs_2d, -1, top2_indices)
736
+ _, top2_weights_norm = _tk.moe.normalize_weight(top2_weights)
737
+
738
+ (pos_to_expert, pos_to_token, pos_to_token_topk,
739
+ token_topk_to_pos, expert_start, expert_end,
740
+ num_tokens_per_expert, ntp_list) = _tk.moe.get_fused_mapping_kernel.get_fused_mapping(
741
+ top2_indices, self.num_experts, num_expanded_tokens=0, alignment=64,
742
+ )
743
+
744
+ x_flat = x.reshape(num_tokens, D).contiguous()
745
+ sh_flat = shared_hidden.reshape(num_tokens, self.shared_inter).contiguous()
746
+
747
+ x_expanded = _tk.moe.expand_to_fused(x_flat, token_topk_to_pos, pos_to_expert)
748
+ sh_expanded = _tk.moe.expand_to_fused(sh_flat, token_topk_to_pos, pos_to_expert)
749
+
750
+ expanded_out = torch.empty_like(x_expanded)
751
+ for e in range(self.num_experts):
752
+ es = expert_start[e].item()
753
+ ee = expert_end[e].item()
754
+ if es >= ee:
755
+ continue
756
+ expert_x = x_expanded[es:ee]
757
+ expert_sh = sh_expanded[es:ee]
758
+ gate = expert_x @ self.W_gate[e]
759
+ core = gate @ self.W_transform[e]
760
+ expanded_out[es:ee] = self.shared_down(core * expert_sh)
761
+
762
+ routed_out = _tk.moe.reduce_fused(expanded_out, top2_weights_norm, token_topk_to_pos)
763
+ routed_out = routed_out.reshape(B, L, D)
764
+
765
+ z_loss = (router_logits.logsumexp(dim=-1) ** 2).mean()
766
+
767
+ return shared_out + routed_out, z_loss
768
+
769
+ def _forward_python(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
770
+ B, L, D = x.shape
771
+
772
+ shared_hidden = F.silu(self.shared_up(x))
773
+ shared_out = self.shared_expert(x)
774
+
775
+ router_logits = self.router(x)
776
+ router_probs = F.softmax(router_logits, dim=-1)
777
+
778
+ top2_probs, top2_indices = router_probs.topk(self.num_experts_per_tok, dim=-1)
779
+ top2_probs = top2_probs / top2_probs.sum(dim=-1, keepdim=True)
780
+
781
+ x_flat = x.reshape(B * L, D)
782
+ shared_hidden_flat = shared_hidden.reshape(B * L, self.shared_inter)
783
+
784
+ routed_out = torch.zeros(B * L, D, device=x.device, dtype=x.dtype)
785
+
786
+ for k in range(self.num_experts_per_tok):
787
+ expert_indices = top2_indices[:, :, k].reshape(B * L)
788
+ expert_weights = top2_probs[:, :, k].reshape(B * L)
789
+
790
+ for e in range(self.num_experts):
791
+ mask = (expert_indices == e)
792
+ if not mask.any():
793
+ continue
794
+ expert_input = x_flat[mask]
795
+ expert_sh = shared_hidden_flat[mask]
796
+
797
+ gate = expert_input @ self.W_gate[e]
798
+ core = gate @ self.W_transform[e]
799
+ expert_output = self.shared_down(core * expert_sh)
800
+
801
+ routed_out[mask] += expert_weights[mask].unsqueeze(-1) * expert_output
802
+
803
+ routed_out = routed_out.reshape(B, L, D)
804
+
805
+ z_loss = (router_logits.logsumexp(dim=-1) ** 2).mean()
806
+
807
+ return shared_out + routed_out, z_loss
808
+
809
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
810
+ if _TK_AVAILABLE and x.is_cuda:
811
+ return self._forward_tilekernels(x)
812
+ return self._forward_python(x)
813
+
814
+
815
+ # ============================================================================
816
+ # Prelude/Coda Dense Layer (uses MLA)
817
+ # ============================================================================
818
+
819
+ class SpiderDenseLayer(nn.Module):
820
+ """Prelude/coda dense layer with MLA attention."""
821
+
822
+ def __init__(self, config: SpiderConfig):
823
+ super().__init__()
824
+ self.self_attn = SpiderMLA(config)
825
+ dense_intermediate = config.prelude_coda_intermediate_size
826
+ self.ffn = SpiderExpert(config, intermediate_size=dense_intermediate)
827
+ self.input_layernorm = SpiderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
828
+ self.post_attention_layernorm = SpiderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
829
+
830
+ def forward(
831
+ self,
832
+ hidden_states,
833
+ attention_mask=None,
834
+ position_ids=None,
835
+ past_key_value=None,
836
+ use_cache=False,
837
+ ):
838
+ attn_input = self.input_layernorm(hidden_states)
839
+ attn_output, past_kv = self.self_attn(
840
+ attn_input, attention_mask=attention_mask,
841
+ position_ids=position_ids,
842
+ past_key_value=past_key_value,
843
+ use_cache=use_cache,
844
+ )
845
+ hidden_states = hidden_states + attn_output
846
+ ffn_input = self.post_attention_layernorm(hidden_states)
847
+ ffn_output = self.ffn(ffn_input)
848
+ hidden_states = hidden_states + ffn_output
849
+ return hidden_states, past_kv
850
+
851
+
852
+ # ============================================================================
853
+ # Recurrent Layer (uses MLA + optional Engram + MoE)
854
+ # ============================================================================
855
+
856
+ class SpiderRecurrentLayer(nn.Module):
857
+ """Recurrent layer with MLA attention, optional Engram memory, and MoE."""
858
+
859
+ def __init__(self, config: SpiderConfig, layer_idx: int, has_engram: bool = False):
860
+ super().__init__()
861
+ self.layer_idx = layer_idx
862
+ self.has_engram = has_engram
863
+ self.self_attn = SpiderMLA(config)
864
+ if has_engram:
865
+ self.engram = SpiderEngram(config)
866
+ self.moe = SharedProjectionMoE(config)
867
+ self.input_layernorm = SpiderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
868
+ self.post_attention_layernorm = SpiderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
869
+ self.post_engram_layernorm = (
870
+ SpiderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
871
+ if has_engram else None
872
+ )
873
+
874
+ def forward(
875
+ self,
876
+ hidden_states,
877
+ token_ids=None,
878
+ attention_mask=None,
879
+ position_ids=None,
880
+ past_key_value=None,
881
+ use_cache=False,
882
+ ):
883
+ attn_input = self.input_layernorm(hidden_states)
884
+ attn_output, past_kv = self.self_attn(
885
+ attn_input, attention_mask=attention_mask,
886
+ position_ids=position_ids,
887
+ past_key_value=past_key_value,
888
+ use_cache=use_cache,
889
+ )
890
+ hidden_states = hidden_states + attn_output
891
+
892
+ if self.has_engram and token_ids is not None:
893
+ engram_out = self.engram(hidden_states, token_ids, layer_id=self.layer_idx)
894
+ hidden_states = hidden_states + engram_out
895
+ if self.post_engram_layernorm is not None:
896
+ hidden_states = self.post_engram_layernorm(hidden_states)
897
+
898
+ ffn_input = self.post_attention_layernorm(hidden_states)
899
+ ffn_output, aux_loss = self.moe(ffn_input)
900
+ hidden_states = hidden_states + ffn_output
901
+ return hidden_states, aux_loss, past_kv
902
+
903
+
904
+ # ============================================================================
905
+ # BoundaryPredictor (D-04, D-11)
906
+ # ============================================================================
907
+
908
+ class BoundaryPredictor(nn.Module):
909
+ """Boundary predictor for learnable byte-level tokenization.
910
+
911
+ 2-layer MLP that predicts merge boundaries between tokens.
912
+ Per D-11: When modality_mask is provided, forces boundary=1.0 at
913
+ sentinel and modality token positions, preventing cross-modality merges.
914
+
915
+ Architecture: Linear(d_model, d_inner) -> GELU -> Linear(d_inner, 1)
916
+ Uses Gumbel-Softmax straight-through estimator for differentiable
917
+ boundary decisions (ported from FLEXITOKENS fxt.py).
918
+ """
919
+
920
+ def __init__(
921
+ self,
922
+ config: SpiderConfig,
923
+ temp: float = 1.0,
924
+ threshold: float = 0.5,
925
+ ):
926
+ super().__init__()
927
+ self.temp = temp
928
+ self.threshold = threshold
929
+
930
+ self.boundary_predictor = nn.Sequential(
931
+ nn.Linear(config.hidden_size, config.bp_d_inner),
932
+ nn.GELU(),
933
+ nn.Linear(config.bp_d_inner, 1),
934
+ )
935
+
936
+ def forward(self, hidden, modality_mask=None):
937
+ """Predict boundary decisions for token merging.
938
+
939
+ Args:
940
+ hidden: Hidden states of shape [B, L, D] (batch-first per D-08).
941
+ modality_mask: Optional boolean tensor [B, L], True at positions
942
+ where sentinel/modality tokens appear. Per D-11,
943
+ forces boundary=1.0 at these positions.
944
+
945
+ Returns:
946
+ Tuple of (soft_boundaries, hard_boundaries), each [B, L].
947
+ - soft_boundaries: Differentiable boundary probabilities
948
+ - hard_boundaries: Binary boundary decisions (straight-through)
949
+ """
950
+ boundary_logits = self.boundary_predictor(hidden).squeeze(-1)
951
+ boundary_probs = torch.sigmoid(boundary_logits)
952
+
953
+ # Gumbel-Softmax straight-through for differentiable boundary decisions
954
+ bernoulli = torch.distributions.relaxed_bernoulli.RelaxedBernoulli(
955
+ temperature=self.temp,
956
+ probs=boundary_probs,
957
+ )
958
+ soft_boundaries = bernoulli.rsample()
959
+
960
+ hard_boundaries = (soft_boundaries > self.threshold).float()
961
+ # Straight-through estimator: gradient flows through soft, forward uses hard
962
+ hard_boundaries = (
963
+ hard_boundaries - soft_boundaries.detach() + soft_boundaries
964
+ )
965
+
966
+ # Per D-11: Force boundaries at sentinel/modality positions
967
+ if modality_mask is not None:
968
+ soft_boundaries = soft_boundaries.masked_fill(modality_mask, 1.0)
969
+ hard_boundaries = hard_boundaries.masked_fill(modality_mask, 1.0)
970
+
971
+ return soft_boundaries, hard_boundaries
972
+
973
+
974
+ # ============================================================================
975
+ # Downsample / Upsample (D-05, D-08, D-11)
976
+ # ============================================================================
977
+
978
+ def _downsample_common(boundaries: torch.Tensor, upsample: bool = False):
979
+ """Common helper for downsample/upsample einsum weight computation.
980
+
981
+ Computes the assignment matrix that maps original positions to groups.
982
+ Based on FLEXITOKENS shortening.py, adapted for batch-first (B*L*D) layout.
983
+
984
+ Args:
985
+ boundaries: [B, L] binary boundary tensor (1 = new group starts)
986
+ upsample: If True, compute upsample weights; else downsample weights
987
+
988
+ Returns:
989
+ Assignment tensor [B, L, S] or None if n_segments == 0
990
+ """
991
+ boundaries = boundaries.clone()
992
+ n_segments = int(boundaries.sum(dim=-1).max().item())
993
+
994
+ if upsample:
995
+ n_segments += 1
996
+
997
+ if n_segments == 0:
998
+ return None
999
+
1000
+ tmp = torch.zeros_like(boundaries).unsqueeze(2) + torch.arange(
1001
+ start=0, end=n_segments, device=boundaries.device, dtype=boundaries.dtype
1002
+ )
1003
+ hh1 = boundaries.cumsum(dim=-1)
1004
+
1005
+ if not upsample:
1006
+ hh1 -= boundaries # Subtract current boundary so position belongs to previous group
1007
+
1008
+ foo = tmp - hh1.unsqueeze(-1)
1009
+
1010
+ # WR-01 fix: zero out unused columns for batch items with fewer segments
1011
+ # When n_segments is set to the max across the batch, items with fewer
1012
+ # segments have unused columns that would produce NaN on normalization.
1013
+ item_segment_counts = boundaries.sum(dim=-1)
1014
+ for b in range(boundaries.shape[0]):
1015
+ item_segs = int(item_segment_counts[b].item())
1016
+ if upsample:
1017
+ item_segs += 1
1018
+ if item_segs < n_segments:
1019
+ foo[b, :, item_segs:] = 0
1020
+
1021
+ return foo
1022
+
1023
+
1024
+ def _downsample_final(foo: torch.Tensor, upsample: bool = False) -> torch.Tensor:
1025
+ """Normalize assignment weights for downsample/upsample einsum."""
1026
+ autoregressive = foo != 0
1027
+ lel = 1.0 - foo.float()
1028
+ lel[autoregressive] = 0.0
1029
+ dim = 2 if upsample else 1
1030
+ lel = lel / (lel.sum(dim=dim, keepdim=True) + 1e-9)
1031
+ return lel.to(foo.dtype)
1032
+
1033
+
1034
+ def downsample(boundaries: torch.Tensor, hidden: torch.Tensor, null_group: torch.Tensor) -> torch.Tensor:
1035
+ """Downsample hidden states using boundary decisions.
1036
+
1037
+ Per D-05: Exact einsum port from FLEXITOKENS shortening.py.
1038
+ Per D-08: Batch-first layout [B, L, D].
1039
+ Per D-11: Sentinel tokens forced to boundary=1 by modality_mask ->
1040
+ downsample treats each sentinel+modality group as a separate merge
1041
+ group -> groups appear intact in shortened sequence.
1042
+
1043
+ Args:
1044
+ boundaries: [B, L] binary boundary tensor (1 = new group starts)
1045
+ hidden: [B, L, D] hidden states (batch-first per D-08)
1046
+ null_group: [1, B, D] null group token prepended to output
1047
+
1048
+ Returns:
1049
+ shortened_hidden: [S, B, D] shortened sequence (LBD format for
1050
+ compatibility with FLEXITOKENS upsample which expects SBD input)
1051
+ """
1052
+ foo = _downsample_common(boundaries, upsample=False)
1053
+ if foo is None:
1054
+ return null_group.repeat(1, hidden.size(0), 1)
1055
+ else:
1056
+ bar = _downsample_final(foo, upsample=False)
1057
+ # Einsum: B*L*D @ B*L*S -> B*S*D, then transpose to S*B*D
1058
+ shortened_hidden = torch.einsum('bld,bls->bsd', hidden, bar.to(hidden.dtype))
1059
+ shortened_hidden = shortened_hidden.permute(1, 0, 2)
1060
+ # Prepend null_group: [1, B, D] -> cat along dim=0 -> [S+1, B, D]
1061
+ shortened_hidden = torch.cat([null_group, shortened_hidden], dim=0)
1062
+ return shortened_hidden
1063
+
1064
+
1065
+ def upsample(boundaries: torch.Tensor, shortened_hidden: torch.Tensor) -> torch.Tensor:
1066
+ """Upsample shortened hidden states back to original sequence length.
1067
+
1068
+ Per D-05: Exact einsum port from FLEXITOKENS shortening.py.
1069
+ Per D-08: Batch-first layout.
1070
+
1071
+ Args:
1072
+ boundaries: [B, L] binary boundary tensor
1073
+ shortened_hidden: [S, B, D] shortened sequence
1074
+
1075
+ Returns:
1076
+ upsampled_hidden: [B, L, D] upsampled sequence
1077
+ """
1078
+ foo = _downsample_common(boundaries, upsample=True)
1079
+ bar = _downsample_final(foo, upsample=True)
1080
+ upsampled_hidden = torch.einsum('sbd,bls->bld', shortened_hidden, bar.to(shortened_hidden.dtype))
1081
+ return upsampled_hidden
1082
+
1083
+
1084
+ # ============================================================================
1085
+ # LTI Injection, ACT Halting, LoRA Adapter
1086
+ # ============================================================================
1087
+
1088
+ class LTIInjection(nn.Module):
1089
+ """Linear Time-Invariant injection module."""
1090
+
1091
+ def __init__(self, config: SpiderConfig):
1092
+ super().__init__()
1093
+ self.hidden_size = config.hidden_size
1094
+ self.log_A = nn.Parameter(torch.full((config.hidden_size,), -2.0))
1095
+ self.delta_t = nn.Parameter(torch.tensor(1.0))
1096
+ self.B = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
1097
+ with torch.no_grad():
1098
+ self.B.weight.data.normal_(mean=0.0, std=0.01)
1099
+
1100
+ def get_A(self):
1101
+ return -torch.exp(self.log_A)
1102
+
1103
+ def forward(self, h_t, e):
1104
+ A = self.get_A()
1105
+ return A * h_t + self.B(e)
1106
+
1107
+
1108
+ class ACTHalting(nn.Module):
1109
+ """Adaptive Computation Time halting module."""
1110
+
1111
+ def __init__(self, config: SpiderConfig):
1112
+ super().__init__()
1113
+ self.halt_predictor = nn.Linear(config.hidden_size, 1)
1114
+ self.threshold = config.act_threshold
1115
+
1116
+ def forward(self, hidden_states):
1117
+ return torch.sigmoid(self.halt_predictor(hidden_states))
1118
+
1119
+
1120
+ class LoRAAdapter(nn.Module):
1121
+ """LoRA adapter for per-loop adaptation in recurrent layers.
1122
+
1123
+ Per CR-01 fix: up-projection (self.B) is initialized to EXACTLY ZERO
1124
+ so that LoRA adapter output is zero at initialization -- meaning the
1125
+ model starts behaving identically to the base model. This follows
1126
+ standard LoRA convention (Hu et al., 2021).
1127
+ """
1128
+
1129
+ def __init__(self, config: SpiderConfig):
1130
+ super().__init__()
1131
+ rank = config.lora_rank
1132
+ self.down = nn.Linear(config.hidden_size, rank, bias=False)
1133
+ self.B = nn.Parameter(torch.zeros(rank, config.hidden_size, dtype=torch.float32)) # CR-01 fix: zeros, not randn*0.02; IN-02
1134
+ self.scale = nn.Embedding(config.max_loop_iters, rank)
1135
+ with torch.no_grad():
1136
+ self.scale.weight.data.zero_()
1137
+ self.down.weight.data.normal_(mean=0.0, std=0.001)
1138
+
1139
+ def forward(self, x, loop_t):
1140
+ max_t = self.scale.num_embeddings - 1
1141
+ t_idx = min(loop_t, max_t)
1142
+ s = self.scale(torch.tensor(t_idx, device=x.device))
1143
+ down = self.down(x) * s
1144
+ return down @ self.B
1145
+
1146
+
1147
+ def _loop_index_embedding(h, loop_t, loop_dim, theta=10000.0):
1148
+ """Sinusoidal loop index embedding for RDT depth differentiation."""
1149
+ freqs = 1.0 / (theta ** (torch.arange(0, loop_dim, 2, device=h.device, dtype=h.dtype) / loop_dim))
1150
+ angles = loop_t * freqs
1151
+ emb = torch.cat([angles.sin(), angles.cos()], dim=-1)[:loop_dim]
1152
+ emb_full = torch.zeros(h.shape[-1], device=h.device, dtype=h.dtype)
1153
+ emb_full[:loop_dim] = emb
1154
+ return h + emb_full.unsqueeze(0).unsqueeze(0)
1155
+
1156
+
1157
+ def _checkpoint(func, *args, **kwargs):
1158
+ """Gradient checkpointing wrapper -- saves VRAM at ~20% compute cost."""
1159
+ if torch.is_grad_enabled():
1160
+ return torch.utils.checkpoint.checkpoint(func, *args, use_reentrant=False, **kwargs)
1161
+ return func(*args, **kwargs)
1162
+
1163
+
1164
+ # ============================================================================
1165
+ # Full Spider Model (with FlexiToken integration)
1166
+ # ============================================================================
1167
+
1168
+ class SpiderModel(nn.Module):
1169
+ """Full RDT model with MLA attention + Engram memory + FlexiToken.
1170
+
1171
+ Architecture:
1172
+ 2x Prelude (MLA + dense FFN)
1173
+ 6x Recurrent (MLA + Engram@L1,L4 + MoE) -- with gradient checkpointing
1174
+ 2x Coda (MLA + dense FFN)
1175
+ LTI Injection + ACT Halting + LoRA Adapter
1176
+ BoundaryPredictor + downsample/upsample for FlexiToken
1177
+ """
1178
+
1179
+ def __init__(self, config: SpiderConfig):
1180
+ super().__init__()
1181
+ self.config = config
1182
+ self.prelude_layers = nn.ModuleList([
1183
+ SpiderDenseLayer(config) for _ in range(config.prelude_layers)
1184
+ ])
1185
+ self.recurrent_layers = nn.ModuleList([
1186
+ SpiderRecurrentLayer(config, i, has_engram=(i in config.engram_layers))
1187
+ for i in range(config.num_hidden_layers)
1188
+ ])
1189
+ self.coda_layers = nn.ModuleList([
1190
+ SpiderDenseLayer(config) for _ in range(config.coda_layers)
1191
+ ])
1192
+ self.norm = SpiderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1193
+ self.injection = LTIInjection(config)
1194
+ self.act_halting = ACTHalting(config)
1195
+ self.lora_adapter = LoRAAdapter(config)
1196
+ self.loop_embed_dim = config.loop_embed_dim
1197
+ self._gradient_checkpointing = False
1198
+
1199
+ def gradient_checkpointing_enable(self):
1200
+ self._gradient_checkpointing = True
1201
+
1202
+ def gradient_checkpointing_disable(self):
1203
+ self._gradient_checkpointing = False
1204
+
1205
+ def forward(
1206
+ self,
1207
+ hidden_states,
1208
+ input_embedding=None,
1209
+ attention_mask=None,
1210
+ position_ids=None,
1211
+ past_key_values=None,
1212
+ use_cache=False,
1213
+ n_loops=None,
1214
+ token_ids=None,
1215
+ hard_boundaries=None,
1216
+ ):
1217
+ n_loops = n_loops or 1
1218
+ input_embedding = input_embedding if input_embedding is not None else hidden_states
1219
+
1220
+ # Prelude layers
1221
+ for layer in self.prelude_layers:
1222
+ if self._gradient_checkpointing and torch.is_grad_enabled():
1223
+ hidden_states, _ = _checkpoint(
1224
+ layer, hidden_states,
1225
+ attention_mask=attention_mask,
1226
+ position_ids=position_ids,
1227
+ )
1228
+ else:
1229
+ hidden_states, _ = layer(
1230
+ hidden_states, attention_mask=attention_mask,
1231
+ position_ids=position_ids,
1232
+ )
1233
+
1234
+ # FlexiToken: if hard_boundaries provided, downsample before recurrent core
1235
+ if hard_boundaries is not None:
1236
+ # Apply norm before downsample
1237
+ hidden_normed = self.norm(hidden_states)
1238
+ null_group = torch.zeros(
1239
+ 1, hidden_states.shape[0], hidden_states.shape[-1],
1240
+ device=hidden_states.device, dtype=hidden_states.dtype,
1241
+ )
1242
+ shortened = downsample(hard_boundaries, hidden_normed, null_group)
1243
+ # shortened: [S, B, D] -> [B, S, D]
1244
+ hidden_states = shortened.permute(1, 0, 2)
1245
+
1246
+ # Shorten token_ids to match downsampled sequence length.
1247
+ # Take the first token in each boundary group so the Engram
1248
+ # hash-based lookup gets a representative token per group.
1249
+ # hard_boundaries: [B, L], cumsum gives group index per position.
1250
+ # Pick the first position (where boundary=1) of each group.
1251
+ if token_ids is not None:
1252
+ group_ids = hard_boundaries.cumsum(dim=-1) # [B, L], 1-based group indices
1253
+ n_groups = int(group_ids.max().item()) # number of groups
1254
+ B = hard_boundaries.shape[0]
1255
+ # For each group g (1..n_groups), find the first position where group_ids == g
1256
+ short_ids = torch.zeros(B, n_groups, device=token_ids.device, dtype=token_ids.dtype)
1257
+ for g in range(1, n_groups + 1):
1258
+ # mask of positions belonging to group g
1259
+ mask = (group_ids == g)
1260
+ # first position in group g
1261
+ first_pos = mask.float().argmax(dim=-1) # [B]
1262
+ short_ids[:, g - 1] = token_ids.gather(1, first_pos.unsqueeze(1)).squeeze(1)
1263
+ # Prepend a dummy token (0) for the null_group entry
1264
+ null_token = torch.zeros(B, 1, device=token_ids.device, dtype=token_ids.dtype)
1265
+ token_ids = torch.cat([null_token, short_ids], dim=1) # [B, S+1]
1266
+
1267
+ # After downsample, input_embedding must match the shortened sequence length
1268
+ input_embedding = hidden_states.clone()
1269
+
1270
+ # Recurrent core with RDT looping
1271
+ e = hidden_states.clone()
1272
+ B, T_seq, D = hidden_states.shape
1273
+ halted = torch.zeros(B, T_seq, device=hidden_states.device, dtype=torch.bool)
1274
+ cumulative_p = torch.zeros(B, T_seq, device=hidden_states.device, dtype=hidden_states.dtype)
1275
+ h_out = torch.zeros_like(hidden_states)
1276
+ total_aux_loss = 0.0
1277
+ past_key_values = past_key_values if past_key_values is not None else [None] * len(self.recurrent_layers)
1278
+
1279
+ for t in range(n_loops):
1280
+ h_loop = _loop_index_embedding(hidden_states, t, self.loop_embed_dim)
1281
+ if t > 0:
1282
+ injection = self.injection(hidden_states, input_embedding)
1283
+ hidden_states = hidden_states + injection
1284
+
1285
+ new_past_key_values = []
1286
+ for i, layer in enumerate(self.recurrent_layers):
1287
+ hidden_states, aux_loss, past_kv = _checkpoint(
1288
+ layer, hidden_states,
1289
+ token_ids=token_ids,
1290
+ attention_mask=attention_mask,
1291
+ position_ids=position_ids,
1292
+ past_key_value=past_key_values[i] if t == 0 else None,
1293
+ use_cache=use_cache,
1294
+ )
1295
+ total_aux_loss = total_aux_loss + aux_loss
1296
+ new_past_key_values.append(past_kv)
1297
+
1298
+ lora_delta = self.lora_adapter(hidden_states, t)
1299
+ hidden_states = hidden_states + lora_delta
1300
+
1301
+ halt_prob = self.act_halting(hidden_states).squeeze(-1)
1302
+ still_running = ~halted
1303
+ remainder = (1.0 - cumulative_p).clamp(min=0)
1304
+ weight = torch.where(
1305
+ cumulative_p + halt_prob >= self.config.act_threshold,
1306
+ remainder, halt_prob,
1307
+ )
1308
+ weight = weight * still_running.to(hidden_states.dtype)
1309
+ h_out = h_out + weight.unsqueeze(-1) * hidden_states
1310
+ cumulative_p = cumulative_p + halt_prob * still_running.to(hidden_states.dtype)
1311
+ halted = halted | (cumulative_p >= self.config.act_threshold)
1312
+ if halted.all() and not self.training:
1313
+ break
1314
+
1315
+ never_halted = (~halted).to(hidden_states.dtype).unsqueeze(-1)
1316
+ hidden_states = h_out + never_halted * hidden_states
1317
+
1318
+ # FlexiToken: if hard_boundaries provided, upsample after recurrent core
1319
+ if hard_boundaries is not None:
1320
+ hidden_states_sbd = hidden_states.permute(1, 0, 2) # [S, B, D]
1321
+ hidden_states = upsample(hard_boundaries, hidden_states_sbd) # [B, L, D]
1322
+
1323
+ # Coda layers
1324
+ for layer in self.coda_layers:
1325
+ if self._gradient_checkpointing and torch.is_grad_enabled():
1326
+ hidden_states, _ = _checkpoint(
1327
+ layer, hidden_states,
1328
+ attention_mask=attention_mask,
1329
+ position_ids=position_ids,
1330
+ )
1331
+ else:
1332
+ hidden_states, _ = layer(
1333
+ hidden_states, attention_mask=attention_mask,
1334
+ position_ids=position_ids,
1335
+ )
1336
+
1337
+ hidden_states = self.norm(hidden_states)
1338
+ return hidden_states, total_aux_loss, new_past_key_values
1339
+
1340
+
1341
+ # ============================================================================
1342
+ # SpiderForConditionalGeneration
1343
+ # ============================================================================
1344
+
1345
+ class SpiderForConditionalGeneration(nn.Module):
1346
+ """Spider model with embedding, LM head, and FlexiToken boundary prediction.
1347
+
1348
+ Forward flow:
1349
+ 1. embed_tokens(input_ids) -> hidden_states
1350
+ 2. Inject modality features at sentinel positions
1351
+ 3. Prelude layers
1352
+ 4. BoundaryPredictor with modality_mask -> boundaries
1353
+ 5. SpiderModel (downsample -> recurrent -> upsample -> coda)
1354
+ 6. lm_head -> logits
1355
+ """
1356
+
1357
+ def __init__(self, config: SpiderConfig):
1358
+ super().__init__()
1359
+ self.config = config
1360
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
1361
+ self.boundary_predictor = BoundaryPredictor(config)
1362
+ self.model = SpiderModel(config)
1363
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1364
+ if config.tie_word_embeddings:
1365
+ self.lm_head.weight = self.embed_tokens.weight
1366
+ self.apply(self._init_weights)
1367
+
1368
+ def gradient_checkpointing_enable(self):
1369
+ self.model.gradient_checkpointing_enable()
1370
+
1371
+ def gradient_checkpointing_disable(self):
1372
+ self.model.gradient_checkpointing_disable()
1373
+
1374
+ def enable_input_require_grads(self):
1375
+ def _make_inputs_require_grad(module, input, output):
1376
+ output.requires_grad_(True)
1377
+ self.embed_tokens.register_forward_hook(_make_inputs_require_grad)
1378
+
1379
+ def _init_weights(self, module):
1380
+ if isinstance(module, nn.Linear):
1381
+ if hasattr(self, 'model') and module is self.model.injection.B:
1382
+ return # LTI injection B has its own init
1383
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1384
+ if module.bias is not None:
1385
+ module.bias.data.zero_()
1386
+ elif isinstance(module, nn.Embedding):
1387
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1388
+
1389
+ def _inject_modality_features(
1390
+ self,
1391
+ hidden_states: torch.Tensor,
1392
+ input_ids: torch.Tensor,
1393
+ features: list,
1394
+ modality: str = 'IMG',
1395
+ ) -> torch.Tensor:
1396
+ """Replace placeholder embeddings with actual encoder features at modality regions.
1397
+
1398
+ Per D-11: Modality tokens (vision, audio, video) are injected at
1399
+ sentinel-marked positions. Between sentinel pairs, the initial
1400
+ embeddings are placeholders -- this method replaces them with the
1401
+ actual encoder features.
1402
+
1403
+ T-02-06 mitigation: Validates feature shape and sentinel pair count.
1404
+ """
1405
+ start_token = SENTINEL_TOKENS[f'{modality}_START']
1406
+ end_token = SENTINEL_TOKENS[f'{modality}_END']
1407
+
1408
+ for b in range(hidden_states.shape[0]):
1409
+ starts = (input_ids[b] == start_token).nonzero(as_tuple=True)[0]
1410
+ ends = (input_ids[b] == end_token).nonzero(as_tuple=True)[0]
1411
+
1412
+ if len(starts) != len(ends):
1413
+ raise ValueError(
1414
+ f"Batch {b}: mismatched {modality} sentinel pairs -- "
1415
+ f"{len(starts)} {_TOKEN_NAMES_BY_ID[start_token]}(s) vs "
1416
+ f"{len(ends)} {_TOKEN_NAMES_BY_ID[end_token]}(s)."
1417
+ )
1418
+ if len(starts) != len(features):
1419
+ raise ValueError(
1420
+ f"Batch {b}: {modality} sentinel pair count ({len(starts)}) "
1421
+ f"doesn't match feature count ({len(features)})."
1422
+ )
1423
+
1424
+ for s, e, feat in zip(starts, ends, features):
1425
+ num_tokens = e - s - 1
1426
+ if feat.shape[0] != num_tokens:
1427
+ raise ValueError(
1428
+ f"Batch {b}: {modality} feature has {feat.shape[0]} tokens "
1429
+ f"but sentinel region has {num_tokens} positions "
1430
+ f"(from pos {s+1} to {e-1})."
1431
+ )
1432
+ if feat.shape[1] != hidden_states.shape[-1]:
1433
+ raise ValueError(
1434
+ f"Batch {b}: {modality} feature hidden_size {feat.shape[1]} "
1435
+ f"doesn't match model hidden_size {hidden_states.shape[-1]}."
1436
+ )
1437
+ hidden_states[b, s + 1:e] = feat.to(hidden_states.dtype)
1438
+
1439
+ return hidden_states
1440
+
1441
+ def forward(
1442
+ self,
1443
+ input_ids: torch.Tensor,
1444
+ attention_mask=None,
1445
+ position_ids=None,
1446
+ labels=None,
1447
+ n_loops=None,
1448
+ use_cache=False,
1449
+ vision_features=None,
1450
+ audio_features=None,
1451
+ video_features=None,
1452
+ **kwargs,
1453
+ ):
1454
+ hidden_states = self.embed_tokens(input_ids)
1455
+ model_dtype = next(self.model.parameters()).dtype
1456
+ hidden_states = hidden_states.to(model_dtype)
1457
+ input_embedding = hidden_states.clone()
1458
+
1459
+ # Inject modality features at sentinel positions
1460
+ if vision_features is not None:
1461
+ hidden_states = self._inject_modality_features(
1462
+ hidden_states, input_ids, vision_features, 'IMG'
1463
+ )
1464
+ if audio_features is not None:
1465
+ hidden_states = self._inject_modality_features(
1466
+ hidden_states, input_ids, audio_features, 'AUD'
1467
+ )
1468
+ if video_features is not None:
1469
+ hidden_states = self._inject_modality_features(
1470
+ hidden_states, input_ids, video_features, 'VID'
1471
+ )
1472
+
1473
+ # Create modality mask and predict boundaries
1474
+ modality_mask = create_modality_mask(input_ids, strict=(labels is not None))
1475
+ soft_boundaries, hard_boundaries = self.boundary_predictor(
1476
+ hidden_states, modality_mask=modality_mask
1477
+ )
1478
+
1479
+ # Run model with FlexiToken boundaries
1480
+ hidden_states, aux_loss, past_kv = self.model(
1481
+ hidden_states,
1482
+ input_embedding=input_embedding,
1483
+ attention_mask=None,
1484
+ position_ids=position_ids,
1485
+ use_cache=use_cache,
1486
+ n_loops=n_loops,
1487
+ token_ids=input_ids,
1488
+ hard_boundaries=hard_boundaries,
1489
+ )
1490
+
1491
+ logits = self.lm_head(hidden_states)
1492
+ loss = None
1493
+ if labels is not None:
1494
+ shift_logits = logits[..., :-1, :].contiguous()
1495
+ shift_labels = labels[..., 1:].contiguous()
1496
+ loss_fct = CrossEntropyLoss()
1497
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1498
+
1499
+ return {
1500
+ "loss": loss,
1501
+ "logits": logits,
1502
+ "aux_loss": aux_loss,
1503
+ "past_key_values": past_kv,
1504
+ "soft_boundaries": soft_boundaries,
1505
+ "hard_boundaries": hard_boundaries,
1506
+ }
1507
+
1508
+ @torch.inference_mode()
1509
+ def generate(
1510
+ self,
1511
+ input_ids: torch.Tensor,
1512
+ max_new_tokens: int = 100,
1513
+ temperature: float = 1.0,
1514
+ top_k: Optional[int] = None,
1515
+ n_loops: int = 1,
1516
+ use_cache: bool = True,
1517
+ boundary_mode: str = 'adaptive',
1518
+ ) -> torch.Tensor:
1519
+ """Token-level generation with compressed-prefix KV cache per D-28.
1520
+
1521
+ Strategy: Encode the prefix through prelude + BP + downsample to get
1522
+ a compressed KV cache, then autoregressively decode byte-by-byte using
1523
+ that cached prefix. The speedup comes from the prefix being shorter in
1524
+ the KV cache (~3.3x fewer entries for English text).
1525
+
1526
+ Flow:
1527
+ 1. Embed prefix → prelude layers → BP → downsample → recurrent core
1528
+ → collect KV cache for compressed prefix
1529
+ 2. Coda + lm_head on last position → sample first new byte
1530
+ 3. For each subsequent byte: embed → recurrent (with KV cache) → coda
1531
+ → lm_head → sample → append
1532
+ 4. Stop at max_new_tokens or EOS
1533
+
1534
+ Args:
1535
+ input_ids: Prefix token IDs [B, L] (byte values 0-255 + BOS/EOS)
1536
+ max_new_tokens: Maximum number of new bytes to generate
1537
+ temperature: Sampling temperature (0 = greedy, 1.0 = default)
1538
+ top_k: If set, only sample from top-k logits
1539
+ n_loops: Number of recurrent loops during generation
1540
+ use_cache: Use KV cache for incremental decoding
1541
+ boundary_mode: 'adaptive' (threshold) or 'fixed' (top-k) for BP
1542
+
1543
+ Returns:
1544
+ Generated token IDs [B, N] where N ≤ max_new_tokens
1545
+ """
1546
+ B = input_ids.shape[0]
1547
+ device = input_ids.device
1548
+ model_dtype = next(self.model.parameters()).dtype
1549
+
1550
+ # --- Step 1: Encode prefix and collect KV cache ---
1551
+ hidden_states = self.embed_tokens(input_ids).to(model_dtype)
1552
+
1553
+ # Prelude layers (byte-level, no compression)
1554
+ for layer in self.model.prelude_layers:
1555
+ hidden_states, _ = layer(hidden_states)
1556
+
1557
+ # Boundary prediction on prefix (strict=False for generation)
1558
+ modality_mask = create_modality_mask(input_ids, strict=False)
1559
+ soft_boundaries, hard_boundaries = self.boundary_predictor(
1560
+ hidden_states, modality_mask=modality_mask
1561
+ )
1562
+
1563
+ # Apply boundary mode
1564
+ if boundary_mode == 'adaptive':
1565
+ hard_boundaries = (soft_boundaries > 0.5).float()
1566
+ hard_boundaries = hard_boundaries - soft_boundaries.detach() + soft_boundaries
1567
+ elif boundary_mode == 'fixed':
1568
+ k = max(1, int(soft_boundaries.shape[-1] / 3.3))
1569
+ topk_vals, topk_idx = soft_boundaries.topk(k, dim=-1)
1570
+ hard_boundaries = torch.zeros_like(soft_boundaries)
1571
+ hard_boundaries.scatter_(-1, topk_idx, 1.0)
1572
+ hard_boundaries = hard_boundaries - soft_boundaries.detach() + soft_boundaries
1573
+
1574
+ # Downsample prefix for compressed KV cache
1575
+ hidden_normed = self.model.norm(hidden_states)
1576
+ null_group = torch.zeros(
1577
+ 1, B, hidden_states.shape[-1], device=device, dtype=hidden_states.dtype
1578
+ )
1579
+ shortened = downsample(hard_boundaries, hidden_normed, null_group)
1580
+ hidden_states = shortened.permute(1, 0, 2) # [B, S, D]
1581
+ input_embedding = hidden_states.clone()
1582
+
1583
+ # Run through recurrent core + coda (hard_boundaries=None skips downsample/upsample)
1584
+ hidden_states, _, past_key_values = self.model(
1585
+ hidden_states,
1586
+ input_embedding=input_embedding,
1587
+ use_cache=use_cache,
1588
+ n_loops=n_loops,
1589
+ hard_boundaries=None,
1590
+ )
1591
+
1592
+ # Get logits for last position of prefix (norm + lm_head only, coda already applied)
1593
+ logits = self.lm_head(hidden_states[:, -1:, :]) # [B, 1, vocab]
1594
+ next_token = self._sample_token(logits, temperature, top_k) # [B, 1]
1595
+
1596
+ generated = [next_token]
1597
+
1598
+ # --- Step 2: Autoregressive byte-level decoding with KV cache ---
1599
+ for _ in range(max_new_tokens - 1):
1600
+ # Check EOS
1601
+ if (next_token == SENTINEL_TOKENS['EOS']).all():
1602
+ break
1603
+
1604
+ # Embed the last generated token
1605
+ hidden_states = self.embed_tokens(next_token).to(model_dtype) # [B, 1, D]
1606
+ input_embedding = hidden_states.clone()
1607
+
1608
+ if use_cache:
1609
+ # Incremental forward: 1 new token, cached prefix in past_key_values
1610
+ hidden_states, _, past_key_values = self.model(
1611
+ hidden_states,
1612
+ input_embedding=input_embedding,
1613
+ past_key_values=past_key_values,
1614
+ use_cache=True,
1615
+ n_loops=n_loops,
1616
+ hard_boundaries=None,
1617
+ )
1618
+ else:
1619
+ # Naive: re-run full forward from scratch (no KV cache)
1620
+ all_ids = torch.cat([input_ids, torch.cat(generated, dim=1)], dim=1)
1621
+ output = self.forward(
1622
+ all_ids, n_loops=n_loops, use_cache=False,
1623
+ )
1624
+ logits_full = output['logits']
1625
+ next_logits = logits_full[:, -1, :] / max(temperature, 1e-8)
1626
+ if top_k is not None and top_k > 0:
1627
+ v, _ = torch.topk(next_logits, min(top_k, next_logits.size(-1)))
1628
+ next_logits = next_logits.masked_fill(next_logits < v[:, [-1]], float('-inf'))
1629
+ if temperature < 1e-8:
1630
+ next_token = next_logits.argmax(dim=-1, keepdim=True)
1631
+ else:
1632
+ probs = torch.softmax(next_logits, dim=-1)
1633
+ next_token = torch.multinomial(probs, num_samples=1)
1634
+ generated.append(next_token)
1635
+ continue
1636
+
1637
+ # lm_head on last position (coda + norm already applied by self.model)
1638
+ logits = self.lm_head(hidden_states[:, -1:, :]) # [B, 1, vocab]
1639
+ next_token = self._sample_token(logits, temperature, top_k)
1640
+ generated.append(next_token)
1641
+
1642
+ return torch.cat(generated, dim=1) # [B, N]
1643
+
1644
+ @staticmethod
1645
+ def _sample_token(logits: torch.Tensor, temperature: float, top_k: Optional[int]) -> torch.Tensor:
1646
+ """Sample next token from logits with temperature and top-k."""
1647
+ logits = logits.squeeze(1) # [B, vocab]
1648
+ if temperature < 1e-8:
1649
+ return logits.argmax(dim=-1, keepdim=True) # greedy
1650
+ logits = logits / temperature
1651
+ if top_k is not None and top_k > 0:
1652
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
1653
+ logits = logits.masked_fill(logits < v[:, [-1]], float('-inf'))
1654
+ probs = torch.softmax(logits, dim=-1)
1655
+ return torch.multinomial(probs, num_samples=1) # [B, 1]
1656
+
1657
+ def get_num_params(self):
1658
+ total = sum(p.numel() for p in self.parameters())
1659
+ return {"total": total, "trainable": total}