|
| 1 | +""" |
| 2 | +Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | +
|
| 4 | +This source code is licensed under the MIT license found in the |
| 5 | +LICENSE file in the root directory of this source tree. |
| 6 | +
|
| 7 | +Unified Radial MLP: Computes all layers' radial functions in a single |
| 8 | +batched operation. |
| 9 | +
|
| 10 | +Instead of running N separate RadialMLP forward passes: |
| 11 | + for layer in layers: |
| 12 | + radial_out = layer.so2_conv_1.rad_func(x_edge) # Sequential |
| 13 | +
|
| 14 | +We run one batched first layer, then each tail: |
| 15 | + all_radial_outs = unified_radial_mlp(x_edge) # list of [E, out] |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +from typing import TYPE_CHECKING |
| 21 | + |
| 22 | +import torch |
| 23 | +import torch.nn as nn |
| 24 | + |
| 25 | +if TYPE_CHECKING: |
| 26 | + from .radial import RadialMLP |
| 27 | + |
| 28 | +__all__ = ["UnifiedRadialMLP", "create_unified_radial_mlp"] |
| 29 | + |
| 30 | +# Expected structure of RadialMLP.net Sequential |
| 31 | +_EXPECTED_NET_STRUCTURE = ( |
| 32 | + nn.Linear, # 0: first linear |
| 33 | + nn.LayerNorm, # 1 |
| 34 | + nn.SiLU, # 2 |
| 35 | + nn.Linear, # 3: second linear |
| 36 | + nn.LayerNorm, # 4 |
| 37 | + nn.SiLU, # 5 |
| 38 | + nn.Linear, # 6: third linear |
| 39 | +) |
| 40 | + |
| 41 | + |
| 42 | +def _validate_radial_mlp(mlp: RadialMLP, idx: int, reference: RadialMLP | None) -> None: |
| 43 | + """ |
| 44 | + Validate a single RadialMLP has expected structure and matches reference. |
| 45 | +
|
| 46 | + Args: |
| 47 | + mlp: The RadialMLP to validate. |
| 48 | + idx: Index in the list (for error messages). |
| 49 | + reference: First RadialMLP to compare dimensions against (None for first). |
| 50 | + """ |
| 51 | + # Check layer count |
| 52 | + if len(mlp.net) != 7: |
| 53 | + raise ValueError(f"RadialMLP[{idx}]: expected 7 layers, got {len(mlp.net)}") |
| 54 | + |
| 55 | + # Check layer types |
| 56 | + for j, expected_type in enumerate(_EXPECTED_NET_STRUCTURE): |
| 57 | + if not isinstance(mlp.net[j], expected_type): |
| 58 | + raise TypeError( |
| 59 | + f"RadialMLP[{idx}].net[{j}]: expected {expected_type.__name__}, " |
| 60 | + f"got {type(mlp.net[j]).__name__}" |
| 61 | + ) |
| 62 | + |
| 63 | + # Check feature dimensions match reference (all MLPs must be identical) |
| 64 | + if reference is not None: |
| 65 | + for j in (0, 3, 6): # Linear layers |
| 66 | + if mlp.net[j].in_features != reference.net[j].in_features: |
| 67 | + raise ValueError( |
| 68 | + f"RadialMLP[{idx}].net[{j}]: in_features mismatch " |
| 69 | + f"({mlp.net[j].in_features} vs {reference.net[j].in_features})" |
| 70 | + ) |
| 71 | + if mlp.net[j].out_features != reference.net[j].out_features: |
| 72 | + raise ValueError( |
| 73 | + f"RadialMLP[{idx}].net[{j}]: out_features mismatch " |
| 74 | + f"({mlp.net[j].out_features} vs {reference.net[j].out_features})" |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +class UnifiedRadialMLP(nn.Module): |
| 79 | + """ |
| 80 | + Unified radial MLP that batches the first linear layer across N RadialMLPs. |
| 81 | +
|
| 82 | + The first layer uses concatenated weights for a single GEMM (all N layers |
| 83 | + share the same input). Layers 2+ use stacked weight buffers for fast |
| 84 | + indexed functional calls. |
| 85 | + """ |
| 86 | + |
| 87 | + def __init__(self, radial_mlps: list[RadialMLP]) -> None: |
| 88 | + """ |
| 89 | + Initialize from a list of RadialMLP modules. |
| 90 | +
|
| 91 | + Args: |
| 92 | + radial_mlps: List of RadialMLP modules with identical architecture. |
| 93 | + """ |
| 94 | + super().__init__() |
| 95 | + |
| 96 | + assert len(radial_mlps) > 0, "Need at least one RadialMLP" |
| 97 | + |
| 98 | + # Validate all MLPs have expected structure and match each other |
| 99 | + for i, mlp in enumerate(radial_mlps): |
| 100 | + _validate_radial_mlp(mlp, i, radial_mlps[0] if i > 0 else None) |
| 101 | + |
| 102 | + self.num_layers = len(radial_mlps) |
| 103 | + self.hidden_features = radial_mlps[0].net[0].out_features |
| 104 | + self.ln_eps = radial_mlps[0].net[1].eps |
| 105 | + |
| 106 | + # First layer: concatenated for single GEMM |
| 107 | + self.register_buffer( |
| 108 | + "W1_cat", |
| 109 | + torch.cat([mlp.net[0].weight.data for mlp in radial_mlps], dim=0), |
| 110 | + ) |
| 111 | + self.register_buffer( |
| 112 | + "b1_cat", |
| 113 | + torch.cat([mlp.net[0].bias.data for mlp in radial_mlps], dim=0), |
| 114 | + ) |
| 115 | + |
| 116 | + # Remaining layers: stacked [N, ...] for indexed access |
| 117 | + self.register_buffer( |
| 118 | + "ln1_weight", |
| 119 | + torch.stack([mlp.net[1].weight.data for mlp in radial_mlps], dim=0), |
| 120 | + ) |
| 121 | + self.register_buffer( |
| 122 | + "ln1_bias", |
| 123 | + torch.stack([mlp.net[1].bias.data for mlp in radial_mlps], dim=0), |
| 124 | + ) |
| 125 | + self.register_buffer( |
| 126 | + "fc2_weight", |
| 127 | + torch.stack([mlp.net[3].weight.data for mlp in radial_mlps], dim=0), |
| 128 | + ) |
| 129 | + self.register_buffer( |
| 130 | + "fc2_bias", |
| 131 | + torch.stack([mlp.net[3].bias.data for mlp in radial_mlps], dim=0), |
| 132 | + ) |
| 133 | + self.register_buffer( |
| 134 | + "ln2_weight", |
| 135 | + torch.stack([mlp.net[4].weight.data for mlp in radial_mlps], dim=0), |
| 136 | + ) |
| 137 | + self.register_buffer( |
| 138 | + "ln2_bias", |
| 139 | + torch.stack([mlp.net[4].bias.data for mlp in radial_mlps], dim=0), |
| 140 | + ) |
| 141 | + self.register_buffer( |
| 142 | + "fc3_weight", |
| 143 | + torch.stack([mlp.net[6].weight.data for mlp in radial_mlps], dim=0), |
| 144 | + ) |
| 145 | + self.register_buffer( |
| 146 | + "fc3_bias", |
| 147 | + torch.stack([mlp.net[6].bias.data for mlp in radial_mlps], dim=0), |
| 148 | + ) |
| 149 | + |
| 150 | + def umas_radial_mlp(self, h: torch.Tensor, i: int) -> torch.Tensor: |
| 151 | + """Apply layers 2+ (LN -> SiLU -> Linear -> LN -> SiLU -> Linear).""" |
| 152 | + H = self.hidden_features |
| 153 | + h = torch.nn.functional.layer_norm( |
| 154 | + h, (H,), self.ln1_weight[i], self.ln1_bias[i], self.ln_eps |
| 155 | + ) |
| 156 | + h = torch.nn.functional.silu(h) |
| 157 | + h = torch.nn.functional.linear(h, self.fc2_weight[i], self.fc2_bias[i]) |
| 158 | + h = torch.nn.functional.layer_norm( |
| 159 | + h, (H,), self.ln2_weight[i], self.ln2_bias[i], self.ln_eps |
| 160 | + ) |
| 161 | + h = torch.nn.functional.silu(h) |
| 162 | + return torch.nn.functional.linear(h, self.fc3_weight[i], self.fc3_bias[i]) |
| 163 | + |
| 164 | + def forward(self, x: torch.Tensor) -> list[torch.Tensor]: |
| 165 | + """ |
| 166 | + Compute all N radial outputs. |
| 167 | +
|
| 168 | + Args: |
| 169 | + x: Input tensor of shape [E, in_features] |
| 170 | +
|
| 171 | + Returns: |
| 172 | + List of N tensors, each of shape [E, out_features] |
| 173 | + """ |
| 174 | + # Single batched GEMM for first layer, then split into per-layer chunks |
| 175 | + h_all = torch.nn.functional.linear(x, self.W1_cat, self.b1_cat) |
| 176 | + h_per_layer = h_all.split(self.hidden_features, dim=1) |
| 177 | + return [self.umas_radial_mlp(h_per_layer[i], i) for i in range(self.num_layers)] |
| 178 | + |
| 179 | + |
| 180 | +def create_unified_radial_mlp(radial_mlps: list) -> UnifiedRadialMLP: |
| 181 | + """ |
| 182 | + Factory function to create a UnifiedRadialMLP from a list of RadialMLPs. |
| 183 | +
|
| 184 | + Args: |
| 185 | + radial_mlps: List of RadialMLP modules |
| 186 | +
|
| 187 | + Returns: |
| 188 | + UnifiedRadialMLP instance with shared first layer weights |
| 189 | + """ |
| 190 | + return UnifiedRadialMLP(radial_mlps) |
0 commit comments