SeaWolf-AI commited on
Commit
6aff8df
·
verified ·
1 Parent(s): 286680a

Delete aether_pkg/modeling_aether_v2_7way.py.pre_moe with huggingface_hub

Browse files
aether_pkg/modeling_aether_v2_7way.py.pre_moe DELETED
@@ -1,826 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2026 VIDRAFT (비드래프트). All rights reserved.
3
- #
4
- # AETHER-V2-7way: 7-aware attention + 7×7 Latin Square 49-layer MoE
5
- # Built upon HuggingFace Transformers conventions.
6
- #
7
- # Architecture:
8
- # - 49 layers organized as 7×7 Latin Square
9
- # - 7 distinct attention types (NSA, Differential, Full, Linear, Sliding, Compress, Hybrid)
10
- # - 25 experts per layer, top-7 active per token
11
- # - Each row of latin square = 1 cycle of 7 attention types
12
- # - Each column = different ordering (Latin square property)
13
- #
14
- # Layer index → (row, col) → attention type via LATIN_SQUARE_7x7
15
- #
16
- """PyTorch AETHER-V2-7way model."""
17
-
18
- from __future__ import annotations
19
- import math
20
- import warnings
21
- from typing import List, Optional, Tuple, Union
22
-
23
- import torch
24
- import torch.nn as nn
25
- import torch.nn.functional as F
26
- from torch.nn import CrossEntropyLoss
27
-
28
- from transformers.activations import ACT2FN
29
- from transformers.cache_utils import Cache, DynamicCache
30
- from transformers.modeling_outputs import (
31
- BaseModelOutputWithPast,
32
- CausalLMOutputWithPast,
33
- MoeCausalLMOutputWithPast,
34
- MoeModelOutputWithPast,
35
- )
36
- from transformers.modeling_utils import PreTrainedModel
37
- from transformers.utils import logging
38
-
39
- from .configuration_aether_v2_7way import AETHERV27wayConfig
40
-
41
- # 7-aware attention modules (already authored, in v2_attentions/)
42
- from .v2_attentions.nsa import NSAAttention
43
- from .v2_attentions.differential import DifferentialAttention
44
-
45
- logger = logging.get_logger(__name__)
46
-
47
-
48
- # =============================================================================
49
- # 7×7 Latin Square — Layer → (attention_type, ffn_phase) 매핑
50
- # =============================================================================
51
- # Latin Square property: each row & column has each of {0..6} exactly once.
52
- # row = layer // 7 (0..6)
53
- # col = layer % 7 (0..6)
54
- # attention_type = LATIN_SQUARE_7x7[row][col]
55
- #
56
- # 5-element cyclic FFN phase (오행 상생 — Q2B OhengGate inspired):
57
- # ffn_phase = layer % 5
58
- #
59
- LATIN_SQUARE_7x7 = [
60
- [0, 1, 2, 3, 4, 5, 6], # row 0: identity
61
- [1, 2, 3, 4, 5, 6, 0], # row 1: shift +1
62
- [2, 3, 4, 5, 6, 0, 1], # row 2: shift +2
63
- [3, 4, 5, 6, 0, 1, 2], # row 3: shift +3
64
- [4, 5, 6, 0, 1, 2, 3], # row 4: shift +4
65
- [5, 6, 0, 1, 2, 3, 4], # row 5: shift +5
66
- [6, 0, 1, 2, 3, 4, 5], # row 6: shift +6
67
- ]
68
-
69
- # Attention type names (0..6)
70
- ATTN_TYPES = [
71
- "nsa", # 0: Native Sparse Attention (3-branch)
72
- "differential", # 1: Differential Attention (lambda-gated)
73
- "full", # 2: Full Attention (standard)
74
- "linear", # 3: Linear Attention (Mamba-style)
75
- "sliding", # 4: Sliding Window Attention
76
- "compress", # 5: Compress-only branch (NSA subset)
77
- "hybrid", # 6: NSA+Differential combined
78
- ]
79
-
80
-
81
- def get_attention_type(layer_idx: int) -> str:
82
- """Layer index → attention type via Latin Square."""
83
- row = layer_idx // 7
84
- col = layer_idx % 7
85
- type_idx = LATIN_SQUARE_7x7[row][col]
86
- return ATTN_TYPES[type_idx]
87
-
88
-
89
- def get_ffn_phase(layer_idx: int) -> int:
90
- """Layer index → 5-element cyclic phase (오행)."""
91
- return layer_idx % 5
92
-
93
-
94
- # =============================================================================
95
- # Rotary Position Embedding (RoPE)
96
- # =============================================================================
97
- class AETHERV27wayRotaryEmbedding(nn.Module):
98
- def __init__(self, dim: int, max_pos: int = 4096, base: float = 10000.0, device=None):
99
- super().__init__()
100
- self.dim = dim
101
- self.max_pos = max_pos
102
- self.base = base
103
- inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
104
- self.register_buffer("inv_freq", inv_freq, persistent=False)
105
- self._build_cos_sin_cache(max_pos, device or torch.device("cpu"))
106
-
107
- def _build_cos_sin_cache(self, seq_len: int, device, dtype=torch.float32):
108
- t = torch.arange(seq_len, device=device, dtype=torch.float32)
109
- freqs = torch.outer(t, self.inv_freq)
110
- emb = torch.cat([freqs, freqs], dim=-1)
111
- self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
112
- self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
113
-
114
- @torch.no_grad()
115
- def forward(self, x: torch.Tensor, position_ids: torch.Tensor):
116
- if position_ids.max() >= self.cos_cached.size(0):
117
- self._build_cos_sin_cache(int(position_ids.max() + 1), x.device, x.dtype)
118
- cos = self.cos_cached[position_ids].to(x.dtype)
119
- sin = self.sin_cached[position_ids].to(x.dtype)
120
- return cos, sin
121
-
122
-
123
- def rotate_half(x: torch.Tensor) -> torch.Tensor:
124
- x1, x2 = x.chunk(2, dim=-1)
125
- return torch.cat([-x2, x1], dim=-1)
126
-
127
-
128
- def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
129
- cos = cos.unsqueeze(unsqueeze_dim)
130
- sin = sin.unsqueeze(unsqueeze_dim)
131
- q_embed = (q * cos) + (rotate_half(q) * sin)
132
- k_embed = (k * cos) + (rotate_half(k) * sin)
133
- return q_embed, k_embed
134
-
135
-
136
- # =============================================================================
137
- # RMSNorm
138
- # =============================================================================
139
- class AETHERV27wayRMSNorm(nn.Module):
140
- def __init__(self, hidden_size: int, eps: float = 1e-6):
141
- super().__init__()
142
- self.weight = nn.Parameter(torch.ones(hidden_size))
143
- self.eps = eps
144
-
145
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
146
- in_dtype = hidden_states.dtype
147
- hidden_states = hidden_states.to(torch.float32)
148
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
149
- hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
150
- return self.weight * hidden_states.to(in_dtype)
151
-
152
-
153
- # =============================================================================
154
- # Standard Multi-Head Attention (Full Attention type)
155
- # =============================================================================
156
- class FullAttention(nn.Module):
157
- """Standard multi-head attention with GQA support."""
158
-
159
- def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
160
- super().__init__()
161
- self.config = config
162
- self.layer_idx = layer_idx
163
- self.hidden_size = config.hidden_size
164
- self.num_heads = config.num_attention_heads
165
- self.num_kv_heads = getattr(config, "num_key_value_heads", config.num_attention_heads)
166
- self.head_dim = config.head_dim
167
- self.num_kv_groups = self.num_heads // self.num_kv_heads
168
-
169
- self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
170
- self.k_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
171
- self.v_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
172
- self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
173
-
174
- self.rotary = AETHERV27wayRotaryEmbedding(
175
- self.head_dim, config.max_position_embeddings, config.rope_theta,
176
- )
177
-
178
- def _repeat_kv(self, x: torch.Tensor) -> torch.Tensor:
179
- if self.num_kv_groups == 1:
180
- return x
181
- bsz, n_kv, seq, dim = x.shape
182
- return x[:, :, None, :, :].expand(bsz, n_kv, self.num_kv_groups, seq, dim).reshape(
183
- bsz, n_kv * self.num_kv_groups, seq, dim,
184
- )
185
-
186
- def forward(
187
- self,
188
- hidden_states: torch.Tensor,
189
- attention_mask: Optional[torch.Tensor] = None,
190
- position_ids: Optional[torch.LongTensor] = None,
191
- past_key_value: Optional[Cache] = None,
192
- use_cache: bool = False,
193
- **kwargs,
194
- ) -> Tuple[torch.Tensor, Optional[Cache]]:
195
- bsz, q_len, _ = hidden_states.size()
196
-
197
- q = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
198
- k = self.k_proj(hidden_states).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
199
- v = self.v_proj(hidden_states).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
200
-
201
- cos, sin = self.rotary(v, position_ids)
202
- q, k = apply_rotary_pos_emb(q, k, cos, sin)
203
-
204
- if past_key_value is not None:
205
- k, v = past_key_value.update(k, v, self.layer_idx)
206
-
207
- k = self._repeat_kv(k)
208
- v = self._repeat_kv(v)
209
-
210
- attn_out = F.scaled_dot_product_attention(
211
- q, k, v,
212
- attn_mask=(attention_mask.to(q.dtype) if attention_mask is not None else None),
213
- dropout_p=0.0 if not self.training else self.config.attention_dropout,
214
- is_causal=(attention_mask is None and q_len > 1),
215
- )
216
- attn_out = attn_out.transpose(1, 2).contiguous().view(bsz, q_len, -1)
217
- return self.o_proj(attn_out), past_key_value
218
-
219
-
220
- # =============================================================================
221
- # Linear Attention (Mamba-style, simplified)
222
- # =============================================================================
223
- class LinearAttention(nn.Module):
224
- """Linear attention (Mamba/RWKV-inspired) for long-context efficiency."""
225
-
226
- def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
227
- super().__init__()
228
- self.config = config
229
- self.layer_idx = layer_idx
230
- self.hidden_size = config.hidden_size
231
- self.num_heads = config.num_attention_heads
232
- self.head_dim = config.head_dim
233
- self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
234
- self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
235
- self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
236
- self.gate = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
237
- self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
238
- self.norm = AETHERV27wayRMSNorm(self.head_dim, eps=config.rms_norm_eps)
239
-
240
- def forward(
241
- self,
242
- hidden_states: torch.Tensor,
243
- attention_mask: Optional[torch.Tensor] = None,
244
- position_ids: Optional[torch.LongTensor] = None,
245
- past_key_value: Optional[Cache] = None,
246
- use_cache: bool = False,
247
- **kwargs,
248
- ) -> Tuple[torch.Tensor, Optional[Cache]]:
249
- bsz, q_len, _ = hidden_states.size()
250
- # FIX 5/8: causal mask 누락 fix — SDPA causal fallback (Linear의 효율 손실, but 안전)
251
- q = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
252
- k = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
253
- v = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
254
- g = self.gate(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).sigmoid()
255
-
256
- out = F.scaled_dot_product_attention(q, k, v, dropout_p=0.0, is_causal=True)
257
- out = out.transpose(1, 2).contiguous() # (bsz, q_len, num_heads, head_dim)
258
- out = out * g
259
- out = self.norm(out).reshape(bsz, q_len, -1)
260
- return self.o_proj(out), past_key_value
261
-
262
-
263
- # =============================================================================
264
- # Sliding Window Attention
265
- # =============================================================================
266
- class SlidingWindowAttention(FullAttention):
267
- """Standard MHA but limited to local window for efficiency."""
268
-
269
- def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
270
- super().__init__(config, layer_idx)
271
- self.window_size = getattr(config, "sliding_window_size", 512)
272
-
273
- def forward(self, hidden_states, attention_mask=None, position_ids=None,
274
- past_key_value=None, use_cache=False, **kwargs):
275
- bsz, q_len, _ = hidden_states.size()
276
- if attention_mask is None and q_len > self.window_size:
277
- mask = torch.ones(q_len, q_len, dtype=torch.bool, device=hidden_states.device)
278
- mask = torch.tril(mask) & torch.triu(mask, diagonal=-self.window_size)
279
- attention_mask = torch.where(mask, 0.0, float("-inf")).unsqueeze(0).unsqueeze(0)
280
- return super().forward(hidden_states, attention_mask, position_ids, past_key_value, use_cache, **kwargs)
281
-
282
-
283
- # =============================================================================
284
- # Compress Attention (NSA-subset, just compress branch)
285
- # =============================================================================
286
- class CompressAttention(nn.Module):
287
- """Compress branch: reduce KV cache via local average, then full attention on compressed."""
288
-
289
- def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
290
- super().__init__()
291
- self.config = config
292
- self.layer_idx = layer_idx
293
- self.compress_block = getattr(config, "compress_block_size", 16)
294
- self.full_attn = FullAttention(config, layer_idx)
295
-
296
- def forward(self, hidden_states, attention_mask=None, position_ids=None,
297
- past_key_value=None, use_cache=False, **kwargs):
298
- # FIX 5/8: Block-mean broadcast가 미래 leak (token 0이 token 7 평균 받음)
299
- # 임시 fallback: FullAttention causal (압축 효율 손실, 안전 우선)
300
- return self.full_attn(hidden_states, attention_mask, position_ids, past_key_value, use_cache)
301
-
302
-
303
- # =============================================================================
304
- # Hybrid Attention (NSA + Differential combined)
305
- # =============================================================================
306
- class HybridAttention(nn.Module):
307
- """Combine NSA + Differential outputs via learnable gate + final norm (stable).
308
-
309
- Fix v2 (2026-05-05): added post-merge GroupNorm + gate init=0 (sigmoid(0)=0.5 exact balance)
310
- + lightly scaled output to prevent 49-layer cumulative divergence.
311
- """
312
-
313
- def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
314
- super().__init__()
315
- self.nsa = NSAAttention(config, layer_idx)
316
- self.diff = DifferentialAttention(config, layer_idx)
317
- # Per-channel gate (richer than scalar), init to 0 → sigmoid(0)=0.5 exact balance
318
- self.gate = nn.Parameter(torch.zeros(config.hidden_size))
319
- # FIX 5/8: GroupNorm sequence-spanning leak → RMSNorm (per-token, causal-safe)
320
- self.merge_norm = AETHERV27wayRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
321
-
322
- def forward(self, hidden_states, attention_mask=None, position_ids=None,
323
- past_key_value=None, use_cache=False, **kwargs):
324
- nsa_out, kv1 = self.nsa(hidden_states, attention_mask, position_ids, past_key_value, use_cache, **kwargs)
325
- diff_out, kv2 = self.diff(hidden_states, attention_mask, position_ids, past_key_value, use_cache, **kwargs)
326
- # Per-channel learnable mix: g (sigmoid) per channel
327
- g = torch.sigmoid(self.gate) # shape (hidden_size,)
328
- out = g * nsa_out + (1.0 - g) * diff_out
329
- # FIX 5/8: per-token RMSNorm (was sequence-spanning GroupNorm = leak)
330
- out = self.merge_norm(out)
331
- return out, kv1 if kv1 is not None else kv2
332
-
333
-
334
- # =============================================================================
335
- # 7-aware Attention Dispatcher
336
- # =============================================================================
337
- def build_attention(config: AETHERV27wayConfig, layer_idx: int) -> nn.Module:
338
- """Pick attention type based on Latin Square index."""
339
- attn_type = get_attention_type(layer_idx)
340
- if attn_type == "nsa":
341
- return NSAAttention(config, layer_idx)
342
- elif attn_type == "differential":
343
- return DifferentialAttention(config, layer_idx)
344
- elif attn_type == "full":
345
- return FullAttention(config, layer_idx)
346
- elif attn_type == "linear":
347
- return LinearAttention(config, layer_idx)
348
- elif attn_type == "sliding":
349
- return SlidingWindowAttention(config, layer_idx)
350
- elif attn_type == "compress":
351
- return CompressAttention(config, layer_idx)
352
- elif attn_type == "hybrid":
353
- return HybridAttention(config, layer_idx)
354
- raise ValueError(f"Unknown attention type: {attn_type}")
355
-
356
-
357
- # =============================================================================
358
- # MoE Block: 25 experts, top-7 active per token
359
- # =============================================================================
360
- class AETHERV27wayMLP(nn.Module):
361
- """Single expert MLP (SwiGLU)."""
362
-
363
- def __init__(self, config: AETHERV27wayConfig, intermediate_size: Optional[int] = None):
364
- super().__init__()
365
- self.hidden_size = config.hidden_size
366
- self.intermediate_size = intermediate_size or config.expert_intermediate_size
367
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
368
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
369
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
370
- self.act_fn = ACT2FN[config.hidden_act]
371
-
372
- def forward(self, x: torch.Tensor) -> torch.Tensor:
373
- return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
374
-
375
-
376
- class AETHERV27waySparseMoE(nn.Module):
377
- """25-expert MoE with top-7 active routing.
378
-
379
- Each layer has a 5-phase cyclic FFN bias to encode 오행 (Five Elements) cycle.
380
- """
381
-
382
- def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
383
- super().__init__()
384
- self.config = config
385
- self.layer_idx = layer_idx
386
- self.hidden_size = config.hidden_size
387
- self.num_experts = config.num_experts
388
- self.top_k = config.num_experts_per_tok
389
- self.ffn_phase = get_ffn_phase(layer_idx) # 0..4 (5-element cycle)
390
-
391
- # Router: hidden → num_experts logits
392
- self.gate = nn.Linear(self.hidden_size, self.num_experts, bias=False)
393
-
394
- # 25 experts (each is a SwiGLU MLP)
395
- self.experts = nn.ModuleList([
396
- AETHERV27wayMLP(config) for _ in range(self.num_experts)
397
- ])
398
-
399
- # 오행 cyclic phase bias (learnable, 5 phases)
400
- self.phase_bias = nn.Parameter(torch.zeros(5, self.num_experts))
401
-
402
- # Optional shared expert (always active, optional)
403
- self.use_shared_expert = getattr(config, "use_shared_expert", True)
404
- if self.use_shared_expert:
405
- self.shared_expert = AETHERV27wayMLP(
406
- config, intermediate_size=config.expert_intermediate_size,
407
- )
408
- self.shared_expert_gate = nn.Linear(self.hidden_size, 1, bias=False)
409
-
410
- def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
411
- bsz, seq_len, dim = hidden_states.shape
412
- x = hidden_states.view(-1, dim) # (bsz*seq, dim)
413
-
414
- # Routing
415
- router_logits = self.gate(x) # (bsz*seq, num_experts)
416
- # Add 5-phase cyclic bias (오행)
417
- router_logits = router_logits + self.phase_bias[self.ffn_phase].unsqueeze(0)
418
-
419
- # Top-k selection
420
- routing_weights, selected_experts = torch.topk(router_logits, self.top_k, dim=-1)
421
- routing_weights = F.softmax(routing_weights, dim=-1)
422
-
423
- # Initialize output
424
- final_out = torch.zeros_like(x)
425
-
426
- # Per-expert dispatch (loop is OK for prototype; can be optimized with grouped GEMM later)
427
- for e in range(self.num_experts):
428
- mask = (selected_experts == e)
429
- if not mask.any():
430
- continue
431
- token_idx, k_idx = mask.nonzero(as_tuple=True)
432
- expert_in = x[token_idx]
433
- expert_out = self.experts[e](expert_in)
434
- weight = routing_weights[token_idx, k_idx].unsqueeze(-1).to(expert_out.dtype)
435
- final_out.index_add_(0, token_idx, (expert_out * weight).to(final_out.dtype))
436
-
437
- # Shared expert
438
- if self.use_shared_expert:
439
- shared_out = self.shared_expert(x)
440
- shared_gate = torch.sigmoid(self.shared_expert_gate(x))
441
- final_out = final_out + (shared_out * shared_gate).to(final_out.dtype)
442
-
443
- final_out = final_out.view(bsz, seq_len, dim)
444
- return final_out, router_logits.view(bsz, seq_len, self.num_experts)
445
-
446
-
447
- # =============================================================================
448
- # Decoder Layer: Attention + MoE FFN with 7-aware + 5-phase logic
449
- # =============================================================================
450
- class AETHERV27wayDecoderLayer(nn.Module):
451
- def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
452
- super().__init__()
453
- self.config = config
454
- self.layer_idx = layer_idx
455
- self.hidden_size = config.hidden_size
456
- self.attn_type = get_attention_type(layer_idx)
457
- self.ffn_phase = get_ffn_phase(layer_idx)
458
-
459
- # 7-aware attention (1 of 7 types based on Latin square)
460
- self.self_attn = build_attention(config, layer_idx)
461
-
462
- # MoE FFN with 5-phase cyclic bias
463
- self.mlp = AETHERV27waySparseMoE(config, layer_idx)
464
-
465
- # Norms
466
- self.input_layernorm = AETHERV27wayRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
467
- self.post_attention_layernorm = AETHERV27wayRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
468
-
469
- def forward(
470
- self,
471
- hidden_states: torch.Tensor,
472
- attention_mask: Optional[torch.Tensor] = None,
473
- position_ids: Optional[torch.LongTensor] = None,
474
- past_key_value: Optional[Cache] = None,
475
- output_router_logits: bool = False,
476
- use_cache: bool = False,
477
- **kwargs,
478
- ) -> Tuple[torch.Tensor, Optional[Cache], Optional[torch.Tensor]]:
479
- # Self-attention with residual
480
- residual = hidden_states
481
- hidden_states = self.input_layernorm(hidden_states)
482
- hidden_states, kv = self.self_attn(
483
- hidden_states=hidden_states,
484
- attention_mask=attention_mask,
485
- position_ids=position_ids,
486
- past_key_value=past_key_value,
487
- use_cache=use_cache,
488
- **kwargs,
489
- )
490
- hidden_states = residual + hidden_states
491
-
492
- # MoE FFN with residual
493
- residual = hidden_states
494
- hidden_states = self.post_attention_layernorm(hidden_states)
495
- hidden_states, router_logits = self.mlp(hidden_states)
496
- hidden_states = residual + hidden_states
497
-
498
- outputs = (hidden_states, kv)
499
- if output_router_logits:
500
- outputs = outputs + (router_logits,)
501
- else:
502
- outputs = outputs + (None,)
503
- return outputs
504
-
505
-
506
- # =============================================================================
507
- # Pretrained base
508
- # =============================================================================
509
- class AETHERV27wayPreTrainedModel(PreTrainedModel):
510
- config_class = AETHERV27wayConfig
511
- base_model_prefix = "model"
512
- supports_gradient_checkpointing = True
513
- _no_split_modules = ["AETHERV27wayDecoderLayer"]
514
- _supports_cache_class = True
515
- _supports_static_cache = False
516
-
517
- def _init_weights(self, module):
518
- std = self.config.initializer_range
519
- if isinstance(module, nn.Linear):
520
- module.weight.data.normal_(mean=0.0, std=std)
521
- if module.bias is not None:
522
- module.bias.data.zero_()
523
- elif isinstance(module, nn.Embedding):
524
- module.weight.data.normal_(mean=0.0, std=std)
525
- if module.padding_idx is not None:
526
- module.weight.data[module.padding_idx].zero_()
527
- elif isinstance(module, AETHERV27wayRMSNorm):
528
- module.weight.data.fill_(1.0)
529
-
530
-
531
- # =============================================================================
532
- # Main Model
533
- # =============================================================================
534
- class AETHERV27wayModel(AETHERV27wayPreTrainedModel):
535
- """49-layer decoder-only model with 7-aware attention + MoE."""
536
-
537
- def __init__(self, config: AETHERV27wayConfig):
538
- super().__init__(config)
539
- self.padding_idx = config.pad_token_id
540
- self.vocab_size = config.vocab_size
541
-
542
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
543
- self.layers = nn.ModuleList([
544
- AETHERV27wayDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)
545
- ])
546
- self.norm = AETHERV27wayRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
547
- self.gradient_checkpointing = False
548
- self.post_init()
549
-
550
- def get_input_embeddings(self):
551
- return self.embed_tokens
552
-
553
- def set_input_embeddings(self, value):
554
- self.embed_tokens = value
555
-
556
- def forward(
557
- self,
558
- input_ids: Optional[torch.LongTensor] = None,
559
- attention_mask: Optional[torch.Tensor] = None,
560
- position_ids: Optional[torch.LongTensor] = None,
561
- past_key_values: Optional[Cache] = None,
562
- inputs_embeds: Optional[torch.FloatTensor] = None,
563
- use_cache: Optional[bool] = None,
564
- output_attentions: Optional[bool] = None,
565
- output_hidden_states: Optional[bool] = None,
566
- output_router_logits: Optional[bool] = None,
567
- return_dict: Optional[bool] = None,
568
- **kwargs,
569
- ) -> Union[Tuple, MoeModelOutputWithPast]:
570
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
571
- output_hidden_states = output_hidden_states if output_hidden_states is not None else False
572
- output_router_logits = output_router_logits if output_router_logits is not None else self.config.output_router_logits
573
- use_cache = use_cache if use_cache is not None else self.config.use_cache
574
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
575
-
576
- if input_ids is not None and inputs_embeds is not None:
577
- raise ValueError("Cannot specify both input_ids and inputs_embeds")
578
- if input_ids is not None:
579
- bsz, seq_len = input_ids.shape
580
- elif inputs_embeds is not None:
581
- bsz, seq_len, _ = inputs_embeds.shape
582
- else:
583
- raise ValueError("Either input_ids or inputs_embeds must be provided")
584
-
585
- if inputs_embeds is None:
586
- inputs_embeds = self.embed_tokens(input_ids)
587
-
588
- # TST superposition: bag s consecutive token-embeddings (FSDP-safe)
589
- _tst_bag = kwargs.get("tst_bag_size", 0)
590
- if _tst_bag and _tst_bag > 1:
591
- _b, _l, _d = inputs_embeds.shape
592
- inputs_embeds = inputs_embeds.view(_b, _l // _tst_bag, _tst_bag, _d).mean(dim=2)
593
- seq_len = inputs_embeds.shape[1]
594
-
595
- if use_cache and past_key_values is None:
596
- past_key_values = DynamicCache()
597
-
598
- past_seen = past_key_values.get_seq_length() if past_key_values is not None else 0
599
-
600
- if position_ids is None:
601
- position_ids = torch.arange(
602
- past_seen, past_seen + seq_len, device=inputs_embeds.device,
603
- ).unsqueeze(0)
604
-
605
- hidden_states = inputs_embeds
606
-
607
- all_hidden_states = () if output_hidden_states else None
608
- all_router_logits = () if output_router_logits else None
609
-
610
- for layer_idx, decoder_layer in enumerate(self.layers):
611
- if output_hidden_states:
612
- all_hidden_states += (hidden_states,)
613
-
614
- if self.gradient_checkpointing and self.training:
615
- layer_out = self._gradient_checkpointing_func(
616
- decoder_layer.__call__,
617
- hidden_states, attention_mask, position_ids,
618
- past_key_values, output_router_logits, use_cache,
619
- )
620
- else:
621
- layer_out = decoder_layer(
622
- hidden_states=hidden_states,
623
- attention_mask=attention_mask,
624
- position_ids=position_ids,
625
- past_key_value=past_key_values,
626
- output_router_logits=output_router_logits,
627
- use_cache=use_cache,
628
- )
629
-
630
- hidden_states = layer_out[0]
631
- if output_router_logits:
632
- all_router_logits += (layer_out[2],)
633
-
634
- hidden_states = self.norm(hidden_states)
635
- if output_hidden_states:
636
- all_hidden_states += (hidden_states,)
637
-
638
- if not return_dict:
639
- return tuple(v for v in [
640
- hidden_states, past_key_values, all_hidden_states, None, all_router_logits,
641
- ] if v is not None)
642
-
643
- return MoeModelOutputWithPast(
644
- last_hidden_state=hidden_states,
645
- past_key_values=past_key_values,
646
- hidden_states=all_hidden_states,
647
- attentions=None,
648
- router_logits=all_router_logits,
649
- )
650
-
651
-
652
- # =============================================================================
653
- # Causal LM Wrapper
654
- # =============================================================================
655
- class AETHERV27wayForCausalLM(AETHERV27wayPreTrainedModel):
656
- _tied_weights_keys = ["lm_head.weight"]
657
-
658
- def __init__(self, config: AETHERV27wayConfig):
659
- super().__init__(config)
660
- self.model = AETHERV27wayModel(config)
661
- self.vocab_size = config.vocab_size
662
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
663
- self.router_aux_loss_coef = getattr(config, "router_aux_loss_coef", 0.001)
664
- self.num_experts = config.num_experts
665
- self.num_experts_per_tok = config.num_experts_per_tok
666
- self.post_init()
667
-
668
- def get_input_embeddings(self):
669
- return self.model.embed_tokens
670
-
671
- def set_input_embeddings(self, value):
672
- self.model.embed_tokens = value
673
-
674
- def get_output_embeddings(self):
675
- return self.lm_head
676
-
677
- def set_output_embeddings(self, new_embeddings):
678
- self.lm_head = new_embeddings
679
-
680
- def get_decoder(self):
681
- return self.model
682
-
683
- def forward(
684
- self,
685
- input_ids: Optional[torch.LongTensor] = None,
686
- attention_mask: Optional[torch.Tensor] = None,
687
- position_ids: Optional[torch.LongTensor] = None,
688
- past_key_values: Optional[Cache] = None,
689
- inputs_embeds: Optional[torch.FloatTensor] = None,
690
- labels: Optional[torch.LongTensor] = None,
691
- use_cache: Optional[bool] = None,
692
- output_attentions: Optional[bool] = None,
693
- output_hidden_states: Optional[bool] = None,
694
- output_router_logits: Optional[bool] = None,
695
- return_dict: Optional[bool] = None,
696
- **kwargs,
697
- ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
698
- output_router_logits = output_router_logits if output_router_logits is not None else self.config.output_router_logits
699
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
700
-
701
- outputs = self.model(
702
- input_ids=input_ids,
703
- attention_mask=attention_mask,
704
- position_ids=position_ids,
705
- past_key_values=past_key_values,
706
- inputs_embeds=inputs_embeds,
707
- use_cache=use_cache,
708
- output_hidden_states=output_hidden_states,
709
- output_router_logits=output_router_logits,
710
- tst_bag_size=kwargs.get("tst_bag_size", 0),
711
- return_dict=True,
712
- )
713
- hidden_states = outputs.last_hidden_state
714
- logits = self.lm_head(hidden_states).float()
715
-
716
- loss = None
717
- aux_loss = None
718
- if labels is not None:
719
- shift_logits = logits[..., :-1, :].contiguous()
720
- shift_labels = labels[..., 1:].contiguous()
721
- loss = F.cross_entropy(
722
- shift_logits.view(-1, self.vocab_size),
723
- shift_labels.view(-1),
724
- ignore_index=-100,
725
- )
726
-
727
- if output_router_logits and outputs.router_logits is not None:
728
- aux_loss = self._compute_router_aux_loss(outputs.router_logits, attention_mask)
729
- if loss is not None:
730
- loss = loss + self.router_aux_loss_coef * aux_loss
731
-
732
- if not return_dict:
733
- output = (logits,) + tuple(v for v in [
734
- outputs.past_key_values, outputs.hidden_states, None, outputs.router_logits, aux_loss,
735
- ] if v is not None)
736
- return (loss,) + output if loss is not None else output
737
-
738
- return MoeCausalLMOutputWithPast(
739
- loss=loss,
740
- aux_loss=aux_loss,
741
- logits=logits,
742
- past_key_values=outputs.past_key_values,
743
- hidden_states=outputs.hidden_states,
744
- attentions=None,
745
- router_logits=outputs.router_logits,
746
- )
747
-
748
- def _compute_router_aux_loss(self, router_logits: Tuple[torch.Tensor, ...], attention_mask=None):
749
- """Standard switch-transformer auxiliary loss for load balancing."""
750
- if router_logits is None or len(router_logits) == 0:
751
- return None
752
- # Each router_logits[i] shape: (bsz, seq, num_experts) → flatten to (n_tokens, num_experts)
753
- flat = []
754
- for r in router_logits:
755
- if r is None:
756
- continue
757
- flat.append(r.reshape(-1, self.num_experts))
758
- if not flat:
759
- return None
760
- all_router_logits = torch.cat(flat, dim=0) # (total_tokens, num_experts)
761
-
762
- routing_weights = F.softmax(all_router_logits.float(), dim=-1)
763
- _, selected_experts = torch.topk(routing_weights, self.num_experts_per_tok, dim=-1)
764
-
765
- # Expert mask: (n_tokens, top_k, num_experts)
766
- expert_mask = F.one_hot(selected_experts, num_classes=self.num_experts).float()
767
- # Tokens-per-expert frequency: average over (n_tokens, top_k) dims → (num_experts,)
768
- tokens_per_expert = expert_mask.mean(dim=(0, 1))
769
- # Router prob per expert: (num_experts,)
770
- router_prob_per_expert = routing_weights.mean(dim=0)
771
- # aux_loss = num_experts * sum(token_freq * prob)
772
- return self.num_experts * torch.sum(tokens_per_expert * router_prob_per_expert)
773
-
774
- def prepare_inputs_for_generation(
775
- self,
776
- input_ids,
777
- past_key_values=None,
778
- attention_mask=None,
779
- inputs_embeds=None,
780
- **kwargs,
781
- ):
782
- if past_key_values is not None:
783
- input_ids = input_ids[:, -1:]
784
- position_ids = kwargs.get("position_ids", None)
785
- if attention_mask is not None and position_ids is None:
786
- position_ids = attention_mask.long().cumsum(-1) - 1
787
- position_ids.masked_fill_(attention_mask == 0, 1)
788
- if past_key_values is not None:
789
- position_ids = position_ids[:, -input_ids.shape[1]:]
790
- return {
791
- "input_ids": input_ids,
792
- "position_ids": position_ids,
793
- "past_key_values": past_key_values,
794
- "use_cache": kwargs.get("use_cache"),
795
- "attention_mask": attention_mask,
796
- }
797
-
798
-
799
- # =============================================================================
800
- # Helper: Latin Square Layer Map (for analysis / debugging)
801
- # =============================================================================
802
- def print_layer_map(num_layers: int = 49):
803
- """Print the Latin Square attention type map."""
804
- print(f"=== AETHER-V2-7way Layer Map ({num_layers} layers) ===")
805
- for L in range(num_layers):
806
- attn = get_attention_type(L)
807
- phase = get_ffn_phase(L)
808
- row = L // 7
809
- col = L % 7
810
- print(f" L{L:02d} (row={row} col={col}): attn={attn:12s} ffn_phase={phase}")
811
-
812
-
813
- __all__ = [
814
- "AETHERV27wayConfig",
815
- "AETHERV27wayModel",
816
- "AETHERV27wayForCausalLM",
817
- "AETHERV27wayPreTrainedModel",
818
- "AETHERV27wayDecoderLayer",
819
- "AETHERV27waySparseMoE",
820
- "build_attention",
821
- "get_attention_type",
822
- "get_ffn_phase",
823
- "LATIN_SQUARE_7x7",
824
- "ATTN_TYPES",
825
- "print_layer_map",
826
- ]