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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
HSE (Hierarchical Sparse Expert) FFN Layer.
|
| 3 |
+
|
| 4 |
+
Two-tier MoE:
|
| 5 |
+
Tier 1: Select 1 semantic domain from K1=4 domains
|
| 6 |
+
Tier 2: Select top-2 specialists from K2=8 experts within that domain
|
| 7 |
+
Total: 32 experts, 2 active per token
|
| 8 |
+
|
| 9 |
+
Load balanced at both tiers independently for stable training.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
import math
|
| 14 |
+
from typing import Optional, Tuple, Dict
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
|
| 20 |
+
from .dgn_norm import build_norm
|
| 21 |
+
from .triton_kernels import fused_swiglu
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class FeedForwardExpert(nn.Module):
|
| 25 |
+
"""Single SwiGLU expert in the HSE layer."""
|
| 26 |
+
|
| 27 |
+
def __init__(self, d_model: int, d_ff: int):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.gate = nn.Linear(d_model, d_ff, bias=False)
|
| 30 |
+
self.up = nn.Linear(d_model, d_ff, bias=False)
|
| 31 |
+
self.down = nn.Linear(d_ff, d_model, bias=False)
|
| 32 |
+
|
| 33 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 34 |
+
return self.down(fused_swiglu(self.gate(x), self.up(x)))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class DenseSwiGLUFFN(nn.Module):
|
| 38 |
+
"""Standard Dense SwiGLU FFN (used in alternating layers)."""
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
d_model: int = 1280,
|
| 43 |
+
d_ff: int = 3200,
|
| 44 |
+
norm_type: str = "dgn",
|
| 45 |
+
dgn_n_groups: int = 16,
|
| 46 |
+
norm_eps: float = 1e-6,
|
| 47 |
+
):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.norm = build_norm(norm_type, d_model, dgn_n_groups, norm_eps)
|
| 50 |
+
self.gate = nn.Linear(d_model, d_ff, bias=False)
|
| 51 |
+
self.up = nn.Linear(d_model, d_ff, bias=False)
|
| 52 |
+
self.down = nn.Linear(d_ff, d_model, bias=False)
|
| 53 |
+
|
| 54 |
+
nn.init.normal_(self.gate.weight, std=0.02)
|
| 55 |
+
nn.init.normal_(self.up.weight, std=0.02)
|
| 56 |
+
nn.init.normal_(self.down.weight, std=0.02 / math.sqrt(2))
|
| 57 |
+
|
| 58 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 59 |
+
residual = x
|
| 60 |
+
h = self.norm(x)
|
| 61 |
+
return residual + self.down(fused_swiglu(self.gate(h), self.up(h)))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class HSELayer(nn.Module):
|
| 65 |
+
"""
|
| 66 |
+
Hierarchical Sparse Expert FFN Layer.
|
| 67 |
+
|
| 68 |
+
Architecture:
|
| 69 |
+
pre-norm β Tier1-router β select domain d*
|
| 70 |
+
β Tier2-router[d*] β select top-2 experts
|
| 71 |
+
β weighted sum of 2 expert outputs
|
| 72 |
+
β residual add
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
d_model: int = 1280,
|
| 78 |
+
n_domains: int = 4,
|
| 79 |
+
n_experts_per_domain: int = 8,
|
| 80 |
+
top_k: int = 2,
|
| 81 |
+
d_ff_expert: int = 288,
|
| 82 |
+
capacity_factor: float = 1.25,
|
| 83 |
+
expert_dropout: float = 0.1,
|
| 84 |
+
aux_loss_alpha: float = 0.01,
|
| 85 |
+
gumbel_tau_init: float = 1.0,
|
| 86 |
+
norm_type: str = "dgn",
|
| 87 |
+
dgn_n_groups: int = 16,
|
| 88 |
+
norm_eps: float = 1e-6,
|
| 89 |
+
layer_idx: int = 0,
|
| 90 |
+
):
|
| 91 |
+
super().__init__()
|
| 92 |
+
assert top_k <= n_experts_per_domain
|
| 93 |
+
|
| 94 |
+
self.d_model = d_model
|
| 95 |
+
self.n_domains = n_domains
|
| 96 |
+
self.n_experts_per_domain = n_experts_per_domain
|
| 97 |
+
self.n_experts_total = n_domains * n_experts_per_domain
|
| 98 |
+
self.top_k = top_k
|
| 99 |
+
self.d_ff_expert = d_ff_expert
|
| 100 |
+
self.capacity_factor = capacity_factor
|
| 101 |
+
self.expert_dropout = expert_dropout
|
| 102 |
+
self.aux_loss_alpha = aux_loss_alpha
|
| 103 |
+
self.layer_idx = layer_idx
|
| 104 |
+
|
| 105 |
+
# Pre-norm
|
| 106 |
+
self.norm = build_norm(norm_type, d_model, dgn_n_groups, norm_eps)
|
| 107 |
+
|
| 108 |
+
# ββ Tier-1 Router ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 109 |
+
# Selects semantic domain: d* = argmax(W_r1 Β· x / Ο)
|
| 110 |
+
self.tier1_router = nn.Linear(d_model, n_domains, bias=False)
|
| 111 |
+
self.gumbel_tau = nn.Parameter(
|
| 112 |
+
torch.tensor(gumbel_tau_init), requires_grad=False # annealed externally
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# ββ Tier-2 Routers (one per domain) ββββββββββββββββββββββββββββββββββ
|
| 116 |
+
self.tier2_routers = nn.ModuleList([
|
| 117 |
+
nn.Linear(d_model, n_experts_per_domain, bias=False)
|
| 118 |
+
for _ in range(n_domains)
|
| 119 |
+
])
|
| 120 |
+
|
| 121 |
+
# ββ Experts βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 122 |
+
self.experts = nn.ModuleList([
|
| 123 |
+
FeedForwardExpert(d_model, d_ff_expert)
|
| 124 |
+
for _ in range(self.n_experts_total)
|
| 125 |
+
])
|
| 126 |
+
|
| 127 |
+
# ββ Dropout for expert regularization ββββββββββββββββββββββββββββββββ
|
| 128 |
+
self.expert_dropout_layer = nn.Dropout(expert_dropout)
|
| 129 |
+
|
| 130 |
+
# ββ Aux loss accumulator (for logging) ββββββββββββββββββββββββββββββββ
|
| 131 |
+
self._last_aux_loss: Optional[torch.Tensor] = None
|
| 132 |
+
|
| 133 |
+
self._init_weights()
|
| 134 |
+
|
| 135 |
+
def _init_weights(self):
|
| 136 |
+
"""Initialize router weights to near-uniform distribution."""
|
| 137 |
+
nn.init.normal_(self.tier1_router.weight, std=0.02)
|
| 138 |
+
for router in self.tier2_routers:
|
| 139 |
+
nn.init.normal_(router.weight, std=0.02)
|
| 140 |
+
for expert in self.experts:
|
| 141 |
+
nn.init.normal_(expert.gate.weight, std=0.02)
|
| 142 |
+
nn.init.normal_(expert.up.weight, std=0.02)
|
| 143 |
+
nn.init.normal_(expert.down.weight, std=0.02 / math.sqrt(2))
|
| 144 |
+
|
| 145 |
+
def update_gumbel_tau(self, progress: float):
|
| 146 |
+
"""
|
| 147 |
+
Anneal Gumbel-softmax temperature from init to final.
|
| 148 |
+
progress: float in [0, 1] representing training progress.
|
| 149 |
+
"""
|
| 150 |
+
tau_init = 1.0
|
| 151 |
+
tau_final = 0.1
|
| 152 |
+
tau = tau_init * (tau_final / tau_init) ** progress
|
| 153 |
+
self.gumbel_tau.data.fill_(tau)
|
| 154 |
+
|
| 155 |
+
def _compute_aux_loss(
|
| 156 |
+
self,
|
| 157 |
+
tier1_probs: torch.Tensor, # (N, n_domains)
|
| 158 |
+
domain_idx: torch.Tensor, # (N,)
|
| 159 |
+
x_flat: torch.Tensor, # (N, d_model)
|
| 160 |
+
) -> torch.Tensor:
|
| 161 |
+
"""
|
| 162 |
+
Hierarchical load-balance auxiliary loss.
|
| 163 |
+
|
| 164 |
+
Loss = Ξ± * [Tier1_balance + Tier2_balance]
|
| 165 |
+
|
| 166 |
+
Tier1_balance = n_domains * Ξ£_d [f_d * P_d]
|
| 167 |
+
Tier2_balance = Ξ£_d {n_exp * Ξ£_e [f_{d,e} * P_{d,e}]} (over assigned tokens)
|
| 168 |
+
"""
|
| 169 |
+
N = x_flat.shape[0]
|
| 170 |
+
|
| 171 |
+
# Tier-1 balance
|
| 172 |
+
# f_d: fraction of tokens routed to domain d
|
| 173 |
+
one_hot_d = F.one_hot(domain_idx, self.n_domains).float() # (N, n_domains)
|
| 174 |
+
f1 = one_hot_d.mean(0) # (n_domains,)
|
| 175 |
+
P1 = tier1_probs.mean(0) # (n_domains,)
|
| 176 |
+
loss_t1 = self.n_domains * (f1 * P1).sum()
|
| 177 |
+
|
| 178 |
+
# Tier-2 balance (over tokens in each domain)
|
| 179 |
+
loss_t2 = torch.zeros(1, device=x_flat.device)
|
| 180 |
+
|
| 181 |
+
for d in range(self.n_domains):
|
| 182 |
+
mask = (domain_idx == d)
|
| 183 |
+
n_d = mask.sum()
|
| 184 |
+
if n_d < 2:
|
| 185 |
+
continue
|
| 186 |
+
|
| 187 |
+
x_d = x_flat[mask] # (n_d, d_model)
|
| 188 |
+
t2_logits = self.tier2_routers[d](x_d) # (n_d, n_exp)
|
| 189 |
+
t2_probs = F.softmax(t2_logits, dim=-1) # (n_d, n_exp)
|
| 190 |
+
|
| 191 |
+
# Top-k indices for f computation
|
| 192 |
+
topk_idx = t2_logits.topk(self.top_k, dim=-1).indices # (n_d, top_k)
|
| 193 |
+
one_hot_e = F.one_hot(topk_idx, self.n_experts_per_domain).float() # (n_d, k, n_exp)
|
| 194 |
+
f2 = one_hot_e.sum(1).mean(0) / self.top_k # (n_exp,)
|
| 195 |
+
P2 = t2_probs.mean(0) # (n_exp,)
|
| 196 |
+
|
| 197 |
+
loss_t2 = loss_t2 + self.n_experts_per_domain * (f2 * P2).sum()
|
| 198 |
+
|
| 199 |
+
return self.aux_loss_alpha * (loss_t1 + loss_t2)
|
| 200 |
+
|
| 201 |
+
def forward(
|
| 202 |
+
self,
|
| 203 |
+
x: torch.Tensor, # (B, T, d_model)
|
| 204 |
+
return_aux_loss: bool = True,
|
| 205 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 206 |
+
"""
|
| 207 |
+
Forward pass with hierarchical routing (vectorized for maximum GPU throughput).
|
| 208 |
+
Returns (output, aux_loss) where aux_loss is for load balancing.
|
| 209 |
+
"""
|
| 210 |
+
B, T, D = x.shape
|
| 211 |
+
N = B * T
|
| 212 |
+
|
| 213 |
+
residual = x
|
| 214 |
+
x_norm = self.norm(x)
|
| 215 |
+
x_flat = x_norm.reshape(N, D) # (N, D)
|
| 216 |
+
|
| 217 |
+
# ββ Tier-1 Routing ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 218 |
+
tier1_logits = self.tier1_router(x_flat) # (N, n_domains)
|
| 219 |
+
tier1_probs = F.softmax(tier1_logits / float(self.gumbel_tau), dim=-1)
|
| 220 |
+
|
| 221 |
+
if self.training:
|
| 222 |
+
domain_idx = F.gumbel_softmax(
|
| 223 |
+
tier1_logits,
|
| 224 |
+
tau=float(self.gumbel_tau),
|
| 225 |
+
hard=True
|
| 226 |
+
).argmax(dim=-1) # (N,)
|
| 227 |
+
else:
|
| 228 |
+
domain_idx = tier1_probs.argmax(dim=-1) # (N,)
|
| 229 |
+
|
| 230 |
+
# ββ Tier-2 Routing (Zero-sync batched projection + gather) βββββββββββ
|
| 231 |
+
t2_weights = torch.cat([r.weight for r in self.tier2_routers], dim=0) # (32, D)
|
| 232 |
+
t2_all = F.linear(x_flat, t2_weights).view(N, self.n_domains, self.n_experts_per_domain)
|
| 233 |
+
|
| 234 |
+
d_expanded = domain_idx.view(N, 1, 1).expand(-1, 1, self.n_experts_per_domain)
|
| 235 |
+
t2_logits = torch.gather(t2_all, 1, d_expanded).squeeze(1) # (N, 8)
|
| 236 |
+
|
| 237 |
+
t2_probs = F.softmax(t2_logits, dim=-1)
|
| 238 |
+
w, topk_idx = t2_probs.topk(self.top_k, dim=-1)
|
| 239 |
+
w = (w / (w.sum(-1, keepdim=True) + 1e-9)).to(x.dtype)
|
| 240 |
+
|
| 241 |
+
global_exp_idx = topk_idx + (domain_idx.unsqueeze(-1) * self.n_experts_per_domain) # (N, 2)
|
| 242 |
+
|
| 243 |
+
# ββ Vectorized Token-Expert Dispatch ββββββββββββββββββββββββββββββββββ
|
| 244 |
+
flat_exp_ids = global_exp_idx.reshape(-1)
|
| 245 |
+
flat_tokens = torch.arange(N, device=x.device).unsqueeze(1).expand(-1, self.top_k).reshape(-1)
|
| 246 |
+
flat_weights = w.reshape(-1, 1)
|
| 247 |
+
|
| 248 |
+
sort_perm = torch.argsort(flat_exp_ids)
|
| 249 |
+
sorted_exp = flat_exp_ids[sort_perm]
|
| 250 |
+
sorted_tokens = flat_tokens[sort_perm]
|
| 251 |
+
sorted_weights = flat_weights[sort_perm]
|
| 252 |
+
|
| 253 |
+
counts = torch.bincount(sorted_exp, minlength=self.n_experts_total).tolist()
|
| 254 |
+
out_flat = torch.zeros(N, D, device=x.device, dtype=x.dtype)
|
| 255 |
+
offset = 0
|
| 256 |
+
|
| 257 |
+
for e in range(self.n_experts_total):
|
| 258 |
+
cnt = counts[e]
|
| 259 |
+
if cnt > 0:
|
| 260 |
+
t_idx = sorted_tokens[offset : offset + cnt]
|
| 261 |
+
w_e = sorted_weights[offset : offset + cnt]
|
| 262 |
+
x_e = x_flat[t_idx]
|
| 263 |
+
if self.training and self.expert_dropout > 0:
|
| 264 |
+
x_e = self.expert_dropout_layer(x_e)
|
| 265 |
+
y_e = self.experts[e](x_e)
|
| 266 |
+
out_flat.index_add_(0, t_idx, w_e * y_e)
|
| 267 |
+
offset += cnt
|
| 268 |
+
|
| 269 |
+
output = out_flat.reshape(B, T, D)
|
| 270 |
+
|
| 271 |
+
# ββ Auxiliary loss ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 272 |
+
aux_loss = None
|
| 273 |
+
if return_aux_loss and self.training:
|
| 274 |
+
aux_loss = self._compute_aux_loss(tier1_probs, domain_idx, x_flat)
|
| 275 |
+
self._last_aux_loss = aux_loss.detach()
|
| 276 |
+
|
| 277 |
+
return residual + output, aux_loss
|