File size: 1,486 Bytes
b368c46 | 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 | import torch
import torch.nn as nn
class ReadoutMoEHead(nn.Module):
"""Absorber-Z-routed mixture head for the spectrum readout."""
def __init__(self, max_z, num_experts, input_dim, output_dim, dropout=0.0):
super().__init__()
if num_experts < 1:
raise ValueError("ReadoutMoEHead requires at least one expert")
self.num_experts = int(num_experts)
self.router_logits = nn.Embedding(max_z + 1, self.num_experts)
nn.init.zeros_(self.router_logits.weight)
self.experts = nn.ModuleList()
for _ in range(self.num_experts):
expert = nn.Sequential(
nn.Linear(input_dim, 256),
nn.SiLU(),
nn.Dropout(p=dropout) if dropout > 0.0 else nn.Identity(),
nn.Linear(256, output_dim),
)
# Dropout after SiLU preserves the activation scale with PyTorch's
# inverted-dropout convention. Dropout scales surviving neurons by 1/(1-p),
# so adding it before could cause problems for z<0 values and since SiLU is
# not bounded the scale of the output is preserved.
self.experts.append(expert)
def forward(self, z_readout, z_abs):
routing_weights = torch.softmax(self.router_logits(z_abs), dim=-1)
expert_outputs = torch.stack([expert(z_readout) for expert in self.experts], dim=1)
return torch.sum(routing_weights.unsqueeze(-1) * expert_outputs, dim=1)
|