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