File size: 38,004 Bytes
d212316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa090a
d212316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa090a
d212316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370b86c
d212316
 
 
 
 
fa414b1
 
 
 
d212316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370b86c
d212316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa414b1
 
 
 
d212316
 
370b86c
d212316
 
 
 
 
 
 
 
 
370b86c
d212316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa090a
d212316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa090a
d212316
 
 
 
 
 
 
 
 
 
fa414b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d212316
 
 
 
 
 
cfa090a
d212316
 
 
 
 
 
 
 
 
fa414b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d212316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
# coding=utf-8
# Copyright 2026 VIDRAFT (๋น„๋“œ๋ž˜ํ”„ํŠธ). All rights reserved.
#
# AETHER-V2-7way: 7-aware attention + 7ร—7 Latin Square 49-layer MoE
# Built upon HuggingFace Transformers conventions.
#
# Architecture:
#   - 49 layers organized as 7ร—7 Latin Square
#   - 7 distinct attention types (NSA, Differential, Full, Linear, Sliding, Compress, Hybrid)
#   - 25 experts per layer, top-7 active per token
#   - Each row of latin square = 1 cycle of 7 attention types
#   - Each column = different ordering (Latin square property)
#
# Layer index โ†’ (row, col) โ†’ attention type via LATIN_SQUARE_7x7
#
"""PyTorch AETHER-V2-7way model."""

from __future__ import annotations
import math
import warnings
from typing import List, Optional, Tuple, Union

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss

from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.modeling_outputs import (
    BaseModelOutputWithPast,
    CausalLMOutputWithPast,
    MoeCausalLMOutputWithPast,
    MoeModelOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import logging

from .configuration_aether_v2_7way import AETHERV27wayConfig

# 7-aware attention modules (already authored, in v2_attentions/)
from .v2_attentions.nsa import NSAAttention
from .v2_attentions.differential import DifferentialAttention

logger = logging.get_logger(__name__)


# =============================================================================
# 7ร—7 Latin Square โ€” Layer โ†’ (attention_type, ffn_phase) ๋งคํ•‘
# =============================================================================
# Latin Square property: each row & column has each of {0..6} exactly once.
# row = layer // 7   (0..6)
# col = layer % 7    (0..6)
# attention_type = LATIN_SQUARE_7x7[row][col]
#
# 5-element cyclic FFN phase (:
# ffn_phase = layer % 5
#
LATIN_SQUARE_7x7 = [
    [0, 1, 2, 3, 4, 5, 6],   # row 0: identity
    [1, 2, 3, 4, 5, 6, 0],   # row 1: shift +1
    [2, 3, 4, 5, 6, 0, 1],   # row 2: shift +2
    [3, 4, 5, 6, 0, 1, 2],   # row 3: shift +3
    [4, 5, 6, 0, 1, 2, 3],   # row 4: shift +4
    [5, 6, 0, 1, 2, 3, 4],   # row 5: shift +5
    [6, 0, 1, 2, 3, 4, 5],   # row 6: shift +6
]

# Attention type names (0..6)
ATTN_TYPES = [
    "nsa",            # 0: Native Sparse Attention (3-branch)
    "differential",   # 1: Differential Attention (lambda-gated)
    "full",           # 2: Full Attention (standard)
    "linear",         # 3: Linear Attention (Mamba-style)
    "sliding",        # 4: Sliding Window Attention
    "compress",       # 5: Compress-only branch (NSA subset)
    "hybrid",         # 6: NSA+Differential combined
]


def get_attention_type(layer_idx: int) -> str:
    """Layer index โ†’ attention type via Latin Square."""
    row = layer_idx // 7
    col = layer_idx % 7
    type_idx = LATIN_SQUARE_7x7[row][col]
    return ATTN_TYPES[type_idx]


def get_ffn_phase(layer_idx: int) -> int:
    """Layer index โ†’ 5-element cyclic phase."""
    return layer_idx % 5


# =============================================================================
# Rotary Position Embedding (RoPE)
# =============================================================================
class AETHERV27wayRotaryEmbedding(nn.Module):
    def __init__(self, dim: int, max_pos: int = 4096, base: float = 10000.0, device=None):
        super().__init__()
        self.dim = dim
        self.max_pos = max_pos
        self.base = base
        inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
        self.register_buffer("inv_freq", inv_freq, persistent=False)
        self._build_cos_sin_cache(max_pos, device or torch.device("cpu"))

    def _build_cos_sin_cache(self, seq_len: int, device, dtype=torch.float32):
        t = torch.arange(seq_len, device=device, dtype=torch.float32)
        freqs = torch.outer(t, self.inv_freq)
        emb = torch.cat([freqs, freqs], dim=-1)
        self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
        self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)

    @torch.no_grad()
    def forward(self, x: torch.Tensor, position_ids: torch.Tensor):
        if position_ids.max() >= self.cos_cached.size(0):
            self._build_cos_sin_cache(int(position_ids.max() + 1), x.device, x.dtype)
        cos = self.cos_cached[position_ids].to(x.dtype)
        sin = self.sin_cached[position_ids].to(x.dtype)
        return cos, sin


def rotate_half(x: torch.Tensor) -> torch.Tensor:
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat([-x2, x1], dim=-1)


def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
    cos = cos.unsqueeze(unsqueeze_dim)
    sin = sin.unsqueeze(unsqueeze_dim)
    q_embed = (q * cos) + (rotate_half(q) * sin)
    k_embed = (k * cos) + (rotate_half(k) * sin)
    return q_embed, k_embed


# =============================================================================
# RMSNorm
# =============================================================================
class AETHERV27wayRMSNorm(nn.Module):
    def __init__(self, hidden_size: int, eps: float = 1e-6):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.eps = eps

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        in_dtype = hidden_states.dtype
        hidden_states = hidden_states.to(torch.float32)
        variance = hidden_states.pow(2).mean(-1, keepdim=True)
        hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
        return self.weight * hidden_states.to(in_dtype)


# =============================================================================
# Standard Multi-Head Attention (Full Attention type)
# =============================================================================
class FullAttention(nn.Module):
    """Standard multi-head attention with GQA support."""

    def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.hidden_size = config.hidden_size
        self.num_heads = config.num_attention_heads
        self.num_kv_heads = getattr(config, "num_key_value_heads", config.num_attention_heads)
        self.head_dim = config.head_dim
        self.num_kv_groups = self.num_heads // self.num_kv_heads

        self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
        self.k_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
        self.v_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
        self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)

        self.rotary = AETHERV27wayRotaryEmbedding(
            self.head_dim, config.max_position_embeddings, config.rope_theta,
        )

    def _repeat_kv(self, x: torch.Tensor) -> torch.Tensor:
        if self.num_kv_groups == 1:
            return x
        bsz, n_kv, seq, dim = x.shape
        return x[:, :, None, :, :].expand(bsz, n_kv, self.num_kv_groups, seq, dim).reshape(
            bsz, n_kv * self.num_kv_groups, seq, dim,
        )

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Cache] = None,
        use_cache: bool = False,
        **kwargs,
    ) -> Tuple[torch.Tensor, Optional[Cache]]:
        bsz, q_len, _ = hidden_states.size()

        q = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
        k = self.k_proj(hidden_states).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
        v = self.v_proj(hidden_states).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)

        cos, sin = self.rotary(v, position_ids)
        q, k = apply_rotary_pos_emb(q, k, cos, sin)

        if past_key_value is not None:
            k, v = past_key_value.update(k, v, self.layer_idx)

        k = self._repeat_kv(k)
        v = self._repeat_kv(v)

        attn_out = F.scaled_dot_product_attention(
            q, k, v,
            attn_mask=(attention_mask.to(q.dtype) if attention_mask is not None else None),
            dropout_p=0.0 if not self.training else self.config.attention_dropout,
            is_causal=(attention_mask is None and q_len > 1),
        )
        attn_out = attn_out.transpose(1, 2).contiguous().view(bsz, q_len, -1)
        return self.o_proj(attn_out), past_key_value


# =============================================================================
# Linear Attention (Mamba-style, simplified)
# =============================================================================
class LinearAttention(nn.Module):
    """Linear attention (Mamba/RWKV-inspired) for long-context efficiency."""

    def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.hidden_size = config.hidden_size
        self.num_heads = config.num_attention_heads
        self.head_dim = config.head_dim
        self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
        self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
        self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
        self.gate = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
        self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
        self.norm = AETHERV27wayRMSNorm(self.head_dim, eps=config.rms_norm_eps)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Cache] = None,
        use_cache: bool = False,
        **kwargs,
    ) -> Tuple[torch.Tensor, Optional[Cache]]:
        bsz, q_len, _ = hidden_states.size()
        # causal mask handling: SDPA causal fallback (causal-safe)
        q = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
        k = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
        v = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
        g = self.gate(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).sigmoid()

        # AetherCache fix: KV cache + causal only when prefill (q_len>1). Training path unchanged.
        if past_key_value is not None:
            k, v = past_key_value.update(k, v, self.layer_idx)
        out = F.scaled_dot_product_attention(q, k, v, dropout_p=0.0, is_causal=(q_len > 1))
        out = out.transpose(1, 2).contiguous()  # (bsz, q_len, num_heads, head_dim)
        out = out * g
        out = self.norm(out).reshape(bsz, q_len, -1)
        return self.o_proj(out), past_key_value


# =============================================================================
# Sliding Window Attention
# =============================================================================
class SlidingWindowAttention(FullAttention):
    """Standard MHA but limited to local window for efficiency."""

    def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
        super().__init__(config, layer_idx)
        self.window_size = getattr(config, "sliding_window_size", 512)

    def forward(self, hidden_states, attention_mask=None, position_ids=None,
                past_key_value=None, use_cache=False, **kwargs):
        bsz, q_len, _ = hidden_states.size()
        if attention_mask is None and q_len > self.window_size:
            mask = torch.ones(q_len, q_len, dtype=torch.bool, device=hidden_states.device)
            mask = torch.tril(mask) & torch.triu(mask, diagonal=-self.window_size)
            attention_mask = torch.where(mask, 0.0, float("-inf")).unsqueeze(0).unsqueeze(0)
        return super().forward(hidden_states, attention_mask, position_ids, past_key_value, use_cache, **kwargs)


# =============================================================================
# Compress Attention (NSA-subset, just compress branch)
# =============================================================================
class CompressAttention(nn.Module):
    """Compress branch: reduce KV cache via local average, then full attention on compressed."""

    def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.compress_block = getattr(config, "compress_block_size", 16)
        self.full_attn = FullAttention(config, layer_idx)

    def forward(self, hidden_states, attention_mask=None, position_ids=None,
                past_key_value=None, use_cache=False, **kwargs):
        # per-token causal-safe block-mean
        # ์ž„์‹œ fallback: FullAttention causal (์••์ถ• ํšจ์œจ ์†์‹ค, ์•ˆ์ „ ์šฐ์„ )
        return self.full_attn(hidden_states, attention_mask, position_ids, past_key_value, use_cache)


# =============================================================================
# Hybrid Attention (NSA + Differential combined)
# =============================================================================
class HybridAttention(nn.Module):
    """Combine NSA + Differential outputs via learnable gate + final norm (stable).

    Fix v2 (2026-05-05): added post-merge GroupNorm + gate init=0 (sigmoid(0)=0.5 exact balance)
    + lightly scaled output to prevent 49-layer cumulative divergence.
    """

    def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
        super().__init__()
        self.nsa = NSAAttention(config, layer_idx)
        self.diff = DifferentialAttention(config, layer_idx)
        # AetherCache: nsa caches the layer input, diff caches KV -> they MUST NOT share a slot.
        # (layer_idx is kept for lambda_init math; only the cache slot is offset.)
        self.nsa.cache_idx = layer_idx
        self.diff.cache_idx = int(getattr(config, "num_hidden_layers", 49)) + layer_idx
        # Per-channel gate (richer than scalar), init to 0 โ†’ sigmoid(0)=0.5 exact balance
        self.gate = nn.Parameter(torch.zeros(config.hidden_size))
        # per-token RMSNorm (causal-safe)
        self.merge_norm = AETHERV27wayRMSNorm(config.hidden_size, eps=config.rms_norm_eps)

    def forward(self, hidden_states, attention_mask=None, position_ids=None,
                past_key_value=None, use_cache=False, **kwargs):
        nsa_out, kv1 = self.nsa(hidden_states, attention_mask, position_ids, past_key_value, use_cache, **kwargs)
        diff_out, kv2 = self.diff(hidden_states, attention_mask, position_ids, past_key_value, use_cache, **kwargs)
        # Per-channel learnable mix: g (sigmoid) per channel
        g = torch.sigmoid(self.gate)  # shape (hidden_size,)
        out = g * nsa_out + (1.0 - g) * diff_out
        # per-token RMSNorm (causal-safe)
        out = self.merge_norm(out)
        return out, kv1 if kv1 is not None else kv2


# =============================================================================
# 7-aware Attention Dispatcher
# =============================================================================
def build_attention(config: AETHERV27wayConfig, layer_idx: int) -> nn.Module:
    """Pick attention type based on Latin Square index."""
    attn_type = get_attention_type(layer_idx)
    if attn_type == "nsa":
        return NSAAttention(config, layer_idx)
    elif attn_type == "differential":
        return DifferentialAttention(config, layer_idx)
    elif attn_type == "full":
        return FullAttention(config, layer_idx)
    elif attn_type == "linear":
        return LinearAttention(config, layer_idx)
    elif attn_type == "sliding":
        return SlidingWindowAttention(config, layer_idx)
    elif attn_type == "compress":
        return CompressAttention(config, layer_idx)
    elif attn_type == "hybrid":
        return HybridAttention(config, layer_idx)
    raise ValueError(f"Unknown attention type: {attn_type}")


# =============================================================================
# MoE Block: 25 experts, top-7 active per token
# =============================================================================
class AETHERV27wayMLP(nn.Module):
    """Single expert MLP (SwiGLU)."""

    def __init__(self, config: AETHERV27wayConfig, intermediate_size: Optional[int] = None):
        super().__init__()
        self.hidden_size = config.hidden_size
        self.intermediate_size = intermediate_size or config.expert_intermediate_size
        self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
        self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
        self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
        self.act_fn = ACT2FN[config.hidden_act]

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))


class AETHERV27waySparseMoE(nn.Module):
    """25-expert MoE with top-7 active routing.

    Each layer has a 5-phase cyclic FFN bias to encode cyclic phases.
    """

    def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.hidden_size = config.hidden_size
        self.num_experts = config.num_experts
        self.top_k = config.num_experts_per_tok
        self.ffn_phase = get_ffn_phase(layer_idx)  # 0..4 (5-element cycle)

        # Router: hidden โ†’ num_experts logits
        self.gate = nn.Linear(self.hidden_size, self.num_experts, bias=False)

        # 25 experts (each is a SwiGLU MLP)
        self.experts = nn.ModuleList([
            AETHERV27wayMLP(config) for _ in range(self.num_experts)
        ])

        # cyclic phase bias (learnable, 5 phases)
        self.phase_bias = nn.Parameter(torch.zeros(5, self.num_experts))

        # Optional shared expert (always active, optional)
        self.use_shared_expert = getattr(config, "use_shared_expert", True)
        if self.use_shared_expert:
            self.shared_expert = AETHERV27wayMLP(
                config, intermediate_size=config.expert_intermediate_size,
            )
            self.shared_expert_gate = nn.Linear(self.hidden_size, 1, bias=False)

    def _stacked_experts(self):
        """Expert weights stacked into [E, ...] tensors so a decode step can run all top_k
        experts as three bmm calls instead of 3*top_k separate GEMMs. Built once, on first
        use, and only for inference: costs one extra copy of the expert weights in VRAM.
        """
        stk = getattr(self, "_stk", None)
        if stk is None:
            with torch.no_grad():
                stk = (
                    torch.stack([e.gate_proj.weight for e in self.experts]),  # [E, I, H]
                    torch.stack([e.up_proj.weight for e in self.experts]),    # [E, I, H]
                    torch.stack([e.down_proj.weight for e in self.experts]),  # [E, H, I]
                )
            self._stk = stk
        return stk

    def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
        bsz, seq_len, dim = hidden_states.shape
        x = hidden_states.view(-1, dim)  # (bsz*seq, dim)

        # Routing
        router_logits = self.gate(x)  # (bsz*seq, num_experts)
        # Add 5-phase cyclic bias
        router_logits = router_logits + self.phase_bias[self.ffn_phase].unsqueeze(0)

        # Top-k selection
        routing_weights, selected_experts = torch.topk(router_logits, self.top_k, dim=-1)
        routing_weights = F.softmax(routing_weights, dim=-1)

        # Initialize output
        final_out = torch.zeros_like(x)

        # Per-expert dispatch. The old loop ran over every expert and called mask.any() to skip
        # the inactive ones -- but .any() and .nonzero() both sync the device, so a decoded token
        # paid num_experts x num_layers stalls just to decide what to skip. Both paths below keep
        # ascending-expert accumulation order, so results are unchanged.
        if x.shape[0] == 1 and not self.training:
            # Single-token decode. Each expert GEMM here is [1,H]x[H,I] -- far too small to keep
            # the GPU busy, so 3*top_k separate launches cost more than the math. Gather the
            # routed experts' weights with a device-side index (no host sync, static shape) and
            # run them as three bmm calls.
            wg, wu, wd = self._stacked_experts()
            idx = selected_experts[0]                                   # [k], stays on device
            xe = x.unsqueeze(0).expand(idx.shape[0], 1, dim)            # [k, 1, H]
            g = torch.bmm(xe, wg[idx].transpose(1, 2))                  # [k, 1, I]
            u = torch.bmm(xe, wu[idx].transpose(1, 2))                  # [k, 1, I]
            act = self.experts[0].act_fn(g) * u                         # [k, 1, I]
            o = torch.bmm(act, wd[idx].transpose(1, 2))                 # [k, 1, H]
            w = routing_weights[0].view(-1, 1, 1).to(o.dtype)
            final_out = (o * w).sum(0)                                  # [1, H]
        else:
            # unique() is sorted, so surviving experts keep ascending order; one sync per layer.
            for e in selected_experts.unique().tolist():
                mask = (selected_experts == e)
                token_idx, k_idx = mask.nonzero(as_tuple=True)
                expert_in = x[token_idx]
                expert_out = self.experts[e](expert_in)
                weight = routing_weights[token_idx, k_idx].unsqueeze(-1).to(expert_out.dtype)
                final_out.index_add_(0, token_idx, (expert_out * weight).to(final_out.dtype))

        # Shared expert
        if self.use_shared_expert:
            shared_out = self.shared_expert(x)
            shared_gate = torch.sigmoid(self.shared_expert_gate(x))
            final_out = final_out + (shared_out * shared_gate).to(final_out.dtype)

        final_out = final_out.view(bsz, seq_len, dim)
        return final_out, router_logits.view(bsz, seq_len, self.num_experts)


# =============================================================================
# Decoder Layer: Attention + MoE FFN with 7-aware + 5-phase logic
# =============================================================================
class AETHERV27wayDecoderLayer(nn.Module):
    def __init__(self, config: AETHERV27wayConfig, layer_idx: int):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.hidden_size = config.hidden_size
        self.attn_type = get_attention_type(layer_idx)
        self.ffn_phase = get_ffn_phase(layer_idx)

        # 7-aware attention (1 of 7 types based on Latin square)
        self.self_attn = build_attention(config, layer_idx)

        # MoE FFN with 5-phase cyclic bias
        self.mlp = AETHERV27waySparseMoE(config, layer_idx)

        # Norms
        self.input_layernorm = AETHERV27wayRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
        self.post_attention_layernorm = AETHERV27wayRMSNorm(self.hidden_size, eps=config.rms_norm_eps)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Cache] = None,
        output_router_logits: bool = False,
        use_cache: bool = False,
        **kwargs,
    ) -> Tuple[torch.Tensor, Optional[Cache], Optional[torch.Tensor]]:
        # Self-attention with residual
        residual = hidden_states
        hidden_states = self.input_layernorm(hidden_states)
        hidden_states, kv = self.self_attn(
            hidden_states=hidden_states,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_value=past_key_value,
            use_cache=use_cache,
            **kwargs,
        )
        hidden_states = residual + hidden_states

        # MoE FFN with residual
        residual = hidden_states
        hidden_states = self.post_attention_layernorm(hidden_states)
        hidden_states, router_logits = self.mlp(hidden_states)
        hidden_states = residual + hidden_states

        outputs = (hidden_states, kv)
        if output_router_logits:
            outputs = outputs + (router_logits,)
        else:
            outputs = outputs + (None,)
        return outputs


# =============================================================================
# Pretrained base
# =============================================================================
class AETHERV27wayPreTrainedModel(PreTrainedModel):
    config_class = AETHERV27wayConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = True
    _no_split_modules = ["AETHERV27wayDecoderLayer"]
    _supports_cache_class = True
    _supports_static_cache = False

    def _init_weights(self, module):
        std = self.config.initializer_range
        if isinstance(module, nn.Linear):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.Embedding):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.padding_idx is not None:
                module.weight.data[module.padding_idx].zero_()
        elif isinstance(module, AETHERV27wayRMSNorm):
            module.weight.data.fill_(1.0)


# =============================================================================
# Main Model
# =============================================================================
class AETHERV27wayModel(AETHERV27wayPreTrainedModel):
    """49-layer decoder-only model with 7-aware attention + MoE."""

    def __init__(self, config: AETHERV27wayConfig):
        super().__init__(config)
        self.padding_idx = config.pad_token_id
        self.vocab_size = config.vocab_size

        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
        self.layers = nn.ModuleList([
            AETHERV27wayDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)
        ])
        self.norm = AETHERV27wayRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.gradient_checkpointing = False
        self.post_init()

    def get_input_embeddings(self):
        return self.embed_tokens

    def set_input_embeddings(self, value):
        self.embed_tokens = value

    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[Cache] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        output_router_logits: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        **kwargs,
    ) -> Union[Tuple, MoeModelOutputWithPast]:
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = output_hidden_states if output_hidden_states is not None else False
        output_router_logits = output_router_logits if output_router_logits is not None else self.config.output_router_logits
        use_cache = use_cache if use_cache is not None else self.config.use_cache
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if input_ids is not None and inputs_embeds is not None:
            raise ValueError("Cannot specify both input_ids and inputs_embeds")
        if input_ids is not None:
            bsz, seq_len = input_ids.shape
        elif inputs_embeds is not None:
            bsz, seq_len, _ = inputs_embeds.shape
        else:
            raise ValueError("Either input_ids or inputs_embeds must be provided")

        if inputs_embeds is None:
            inputs_embeds = self.embed_tokens(input_ids)

        # TST superposition: bag s consecutive token-embeddings (FSDP-safe)
        _tst_bag = kwargs.get("tst_bag_size", 0)
        if _tst_bag and _tst_bag > 1:
            _b, _l, _d = inputs_embeds.shape
            inputs_embeds = inputs_embeds.view(_b, _l // _tst_bag, _tst_bag, _d).mean(dim=2)
            seq_len = inputs_embeds.shape[1]

        if use_cache and past_key_values is None:
            past_key_values = DynamicCache()

        past_seen = past_key_values.get_seq_length() if past_key_values is not None else 0

        if position_ids is None:
            position_ids = torch.arange(
                past_seen, past_seen + seq_len, device=inputs_embeds.device,
            ).unsqueeze(0)

        hidden_states = inputs_embeds

        all_hidden_states = () if output_hidden_states else None
        all_router_logits = () if output_router_logits else None

        for layer_idx, decoder_layer in enumerate(self.layers):
            if output_hidden_states:
                all_hidden_states += (hidden_states,)

            if self.gradient_checkpointing and self.training:
                layer_out = self._gradient_checkpointing_func(
                    decoder_layer.__call__,
                    hidden_states, attention_mask, position_ids,
                    past_key_values, output_router_logits, use_cache,
                )
            else:
                layer_out = decoder_layer(
                    hidden_states=hidden_states,
                    attention_mask=attention_mask,
                    position_ids=position_ids,
                    past_key_value=past_key_values,
                    output_router_logits=output_router_logits,
                    use_cache=use_cache,
                )

            hidden_states = layer_out[0]
            if output_router_logits:
                all_router_logits += (layer_out[2],)

        hidden_states = self.norm(hidden_states)
        if output_hidden_states:
            all_hidden_states += (hidden_states,)

        if not return_dict:
            return tuple(v for v in [
                hidden_states, past_key_values, all_hidden_states, None, all_router_logits,
            ] if v is not None)

        return MoeModelOutputWithPast(
            last_hidden_state=hidden_states,
            past_key_values=past_key_values,
            hidden_states=all_hidden_states,
            attentions=None,
            router_logits=all_router_logits,
        )


# =============================================================================
# Causal LM Wrapper
# =============================================================================
class AETHERV27wayForCausalLM(AETHERV27wayPreTrainedModel):
    _tied_weights_keys = ["lm_head.weight"]

    def __init__(self, config: AETHERV27wayConfig):
        super().__init__(config)
        self.model = AETHERV27wayModel(config)
        self.vocab_size = config.vocab_size
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
        self.router_aux_loss_coef = getattr(config, "router_aux_loss_coef", 0.001)
        self.num_experts = config.num_experts
        self.num_experts_per_tok = config.num_experts_per_tok
        self.post_init()

    def get_input_embeddings(self):
        return self.model.embed_tokens

    def set_input_embeddings(self, value):
        self.model.embed_tokens = value

    def get_output_embeddings(self):
        return self.lm_head

    def set_output_embeddings(self, new_embeddings):
        self.lm_head = new_embeddings

    def get_decoder(self):
        return self.model

    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[Cache] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        output_router_logits: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        **kwargs,
    ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
        output_router_logits = output_router_logits if output_router_logits is not None else self.config.output_router_logits
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.model(
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_hidden_states=output_hidden_states,
            output_router_logits=output_router_logits,
            tst_bag_size=kwargs.get("tst_bag_size", 0),
            return_dict=True,
        )
        hidden_states = outputs.last_hidden_state
        logits = self.lm_head(hidden_states).float()

        loss = None
        aux_loss = None
        if labels is not None:
            shift_logits = logits[..., :-1, :].contiguous()
            shift_labels = labels[..., 1:].contiguous()
            loss = F.cross_entropy(
                shift_logits.view(-1, self.vocab_size),
                shift_labels.view(-1),
                ignore_index=-100,
            )

        if output_router_logits and outputs.router_logits is not None:
            aux_loss = self._compute_router_aux_loss(outputs.router_logits, attention_mask)
            if loss is not None:
                loss = loss + self.router_aux_loss_coef * aux_loss

        if not return_dict:
            output = (logits,) + tuple(v for v in [
                outputs.past_key_values, outputs.hidden_states, None, outputs.router_logits, aux_loss,
            ] if v is not None)
            return (loss,) + output if loss is not None else output

        return MoeCausalLMOutputWithPast(
            loss=loss,
            aux_loss=aux_loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=None,
            router_logits=outputs.router_logits,
        )

    def _compute_router_aux_loss(self, router_logits: Tuple[torch.Tensor, ...], attention_mask=None):
        """Standard switch-transformer auxiliary loss for load balancing."""
        if router_logits is None or len(router_logits) == 0:
            return None
        # Each router_logits[i] shape: (bsz, seq, num_experts) โ†’ flatten to (n_tokens, num_experts)
        flat = []
        for r in router_logits:
            if r is None:
                continue
            flat.append(r.reshape(-1, self.num_experts))
        if not flat:
            return None
        all_router_logits = torch.cat(flat, dim=0)  # (total_tokens, num_experts)

        routing_weights = F.softmax(all_router_logits.float(), dim=-1)
        _, selected_experts = torch.topk(routing_weights, self.num_experts_per_tok, dim=-1)

        # Expert mask: (n_tokens, top_k, num_experts)
        expert_mask = F.one_hot(selected_experts, num_classes=self.num_experts).float()
        # Tokens-per-expert frequency: average over (n_tokens, top_k) dims โ†’ (num_experts,)
        tokens_per_expert = expert_mask.mean(dim=(0, 1))
        # Router prob per expert: (num_experts,)
        router_prob_per_expert = routing_weights.mean(dim=0)
        # aux_loss = num_experts * sum(token_freq * prob)
        return self.num_experts * torch.sum(tokens_per_expert * router_prob_per_expert)

    def prepare_inputs_for_generation(
        self,
        input_ids,
        past_key_values=None,
        attention_mask=None,
        inputs_embeds=None,
        **kwargs,
    ):
        if past_key_values is not None:
            input_ids = input_ids[:, -1:]
        position_ids = kwargs.get("position_ids", None)
        if attention_mask is not None and position_ids is None:
            position_ids = attention_mask.long().cumsum(-1) - 1
            position_ids.masked_fill_(attention_mask == 0, 1)
            if past_key_values is not None:
                position_ids = position_ids[:, -input_ids.shape[1]:]
        return {
            "input_ids": input_ids,
            "position_ids": position_ids,
            "past_key_values": past_key_values,
            "use_cache": kwargs.get("use_cache"),
            "attention_mask": attention_mask,
        }


# =============================================================================
# Helper: Latin Square Layer Map (for analysis / debugging)
# =============================================================================
def print_layer_map(num_layers: int = 49):
    """Print the Latin Square attention type map."""
    print(f"=== AETHER-V2-7way Layer Map ({num_layers} layers) ===")
    for L in range(num_layers):
        attn = get_attention_type(L)
        phase = get_ffn_phase(L)
        row = L // 7
        col = L % 7
        print(f"  L{L:02d} (row={row} col={col}): attn={attn:12s} ffn_phase={phase}")


__all__ = [
    "AETHERV27wayConfig",
    "AETHERV27wayModel",
    "AETHERV27wayForCausalLM",
    "AETHERV27wayPreTrainedModel",
    "AETHERV27wayDecoderLayer",
    "AETHERV27waySparseMoE",
    "build_attention",
    "get_attention_type",
    "get_ffn_phase",
    "LATIN_SQUARE_7x7",
    "ATTN_TYPES",
    "print_layer_map",
]