Download src/model/readout.py from vitorgrizzi/xane3_mp: direct link, hf CLI and curl.
- Browser
- Download file 1.49 kB
-
https://huggingface.co/vitorgrizzi/xane3_mp/resolve/main/src/model/readout.py
- Command line
-
hf download hf://vitorgrizzi/xane3_mp/src/model/readout.py
-
curl -L -o readout.py https://huggingface.co/vitorgrizzi/xane3_mp/resolve/main/src/model/readout.py
1.49 kB
| 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) | |