Aether-6B-11Attn-base / aether_pkg /modeling_aether_v2_11way.py
SeaWolf-AI's picture
remove oheng/오행 references (pass 2)
b13fc27 verified
Raw
History Blame Contribute Delete
36.6 kB
# 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_11attn import AETHERV211AttnConfig
# 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]
#
# cyclic FFN phase (periodic routing bias):
# ffn_phase = layer % 5
#
# Cyclic Latin Square 11x11 (prime number — Prime Series)
LATIN_SQUARE_11x11 = [
[(i + j) % 11 for j in range(11)] for i in range(11)
]
# Backward compat alias
LATIN_SQUARE_7x7 = LATIN_SQUARE_11x11 # for v2_7way imports
# Attention type names (0..6)
ATTN_TYPES = [
"nsa", # 0: Native Sparse Attention (3-branch) [Transformer]
"differential", # 1: Differential Attention (λ-gated) [Transformer]
"full", # 2: Full Attention (standard) [Transformer]
"mla", # 3: Multi-head Latent (DeepSeek-V2/V3) [Transformer]
"sliding", # 4: Sliding Window Attention [Transformer]
"compress", # 5: Compress-only (NSA subset) [Transformer]
"hybrid", # 6: NSA + Differential combined [Transformer]
"linear", # 7: Linear Attention (Mamba-style) [Non-Transformer]
"mamba2", # 8: Mamba2 (SSM) [Non-Transformer]
"gdn", # 9: Gated Delta Network [Non-Transformer]
"hyena", # 10: Hyena (Convolutional) [Non-Transformer]
]
def get_attention_type(layer_idx: int) -> str:
"""Layer index → attention type via 11x11 Latin Square."""
row = layer_idx // 11
col = layer_idx % 11
type_idx = LATIN_SQUARE_11x11[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 AETHERV211AttnRotaryEmbedding(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 AETHERV211AttnRMSNorm(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: AETHERV211AttnConfig, 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 = AETHERV211AttnRotaryEmbedding(
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: AETHERV211AttnConfig, 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 = AETHERV211AttnRMSNorm(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()
q = F.elu(self.q_proj(hidden_states), alpha=1.0).view(bsz, q_len, self.num_heads, self.head_dim) + 1
k = F.elu(self.k_proj(hidden_states), alpha=1.0).view(bsz, q_len, self.num_heads, self.head_dim) + 1
v = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
g = self.gate(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).sigmoid()
# Linear attention: O(n*d^2) instead of O(n^2*d)
kv = torch.einsum("bnhd,bnhe->bhde", k, v) # (bsz, h, d, e)
out = torch.einsum("bnhd,bhde->bnhe", q, kv)
z = torch.einsum("bnhd,bhd->bnh", q, k.sum(dim=1)).unsqueeze(-1).clamp_min(1e-6)
out = (out / z) * 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: AETHERV211AttnConfig, 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: AETHERV211AttnConfig, 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):
bsz, q_len, dim = hidden_states.size()
# Compress along seq dim by averaging blocks
if q_len % self.compress_block == 0 and q_len > self.compress_block:
n_blocks = q_len // self.compress_block
x_comp = hidden_states.view(bsz, n_blocks, self.compress_block, dim).mean(dim=2)
pos_comp = position_ids[:, ::self.compress_block] if position_ids is not None else None
out_comp, kv = self.full_attn(x_comp, None, pos_comp, past_key_value, use_cache)
# Up-sample by repeat
out = out_comp.unsqueeze(2).expand(bsz, n_blocks, self.compress_block, dim).reshape(bsz, q_len, dim)
return out, kv
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: AETHERV211AttnConfig, layer_idx: int):
super().__init__()
self.nsa = NSAAttention(config, layer_idx)
self.diff = DifferentialAttention(config, 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))
# Post-merge GroupNorm to stabilize 49-layer stack
n_groups = 8 if config.hidden_size % 8 == 0 else 1
self.merge_norm = AETHERV211AttnRMSNorm(config.hidden_size, eps=getattr(config,'rms_norm_eps',1e-6))
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
# Stabilize via GroupNorm: (B, S, H) → (B, H, S) → norm → (B, S, H)
out = self.merge_norm(out)
return out, kv1 if kv1 is not None else kv2
# =============================================================================
# 7-aware Attention Dispatcher
# =============================================================================
def build_attention(config: AETHERV211AttnConfig, 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)
elif attn_type == "mla":
from aether_pkg.v2_attentions.mla import MLAAttention
return MLAAttention(config, layer_idx)
elif attn_type == "mamba2":
from aether_pkg.v2_attentions.mamba2 import Mamba2Attention
return Mamba2Attention(config, layer_idx)
elif attn_type == "gdn":
from aether_pkg.v2_attentions.gdn import GDNAttention
return GDNAttention(config, layer_idx)
elif attn_type == "hyena":
from aether_pkg.v2_attentions.hyena import HyenaAttention
return HyenaAttention(config, layer_idx)
raise ValueError(f"Unknown attention type: {attn_type}")
# =============================================================================
# MoE Block: 25 experts, top-7 active per token
# =============================================================================
class AETHERV211AttnMLP(nn.Module):
"""Single expert MLP (SwiGLU)."""
def __init__(self, config: AETHERV211AttnConfig, 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 AETHERV211AttnSparseMoE(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: AETHERV211AttnConfig, 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([
AETHERV211AttnMLP(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 = AETHERV211AttnMLP(
config, intermediate_size=config.expert_intermediate_size,
)
self.shared_expert_gate = nn.Linear(self.hidden_size, 1, bias=False)
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 (loop is OK for prototype; can be optimized with grouped GEMM later)
for e in range(self.num_experts):
mask = (selected_experts == e)
if not mask.any():
continue
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 AETHERV211AttnDecoderLayer(nn.Module):
def __init__(self, config: AETHERV211AttnConfig, 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 = AETHERV211AttnSparseMoE(config, layer_idx)
# Norms
self.input_layernorm = AETHERV211AttnRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = AETHERV211AttnRMSNorm(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 AETHERV211AttnPreTrainedModel(PreTrainedModel):
config_class = AETHERV211AttnConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["AETHERV211AttnDecoderLayer"]
_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, AETHERV211AttnRMSNorm):
module.weight.data.fill_(1.0)
# =============================================================================
# Main Model
# =============================================================================
class AETHERV211AttnModel(AETHERV211AttnPreTrainedModel):
"""49-layer decoder-only model with 7-aware attention + MoE."""
def __init__(self, config: AETHERV211AttnConfig):
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([
AETHERV211AttnDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)
])
self.norm = AETHERV211AttnRMSNorm(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)
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 AETHERV211AttnForCausalLM(AETHERV211AttnPreTrainedModel):
_tied_weights_keys = ["lm_head.weight"]
def __init__(self, config: AETHERV211AttnConfig):
super().__init__(config)
self.model = AETHERV211AttnModel(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,
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__ = [
"AETHERV211AttnConfig",
"AETHERV211AttnModel",
"AETHERV211AttnForCausalLM",
"AETHERV211AttnPreTrainedModel",
"AETHERV211AttnDecoderLayer",
"AETHERV211AttnSparseMoE",
"build_attention",
"get_attention_type",
"get_ffn_phase",
"LATIN_SQUARE_7x7",
"ATTN_TYPES",
"print_layer_map",
]