File size: 17,826 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | import torch
import torch.nn as nn
from e3nn import o3
from e3nn.nn import FullyConnectedNet, Gate
# torch_scatter is used for highly optimized message
# aggregation (sum, mean, max, etc.) in message passing
try:
from torch_scatter import scatter
HAS_TORCH_SCATTER = True
except ImportError:
HAS_TORCH_SCATTER = False
def _load_cueq():
try:
import cuequivariance as cue
import cuequivariance_torch as cuet
except ImportError as exc:
raise ImportError(
"equivariance_backend='cueq' requires cuEquivariance. "
"Install it with: pip install cuequivariance-torch "
"cuequivariance-ops-torch-cu12"
) from exc
_patch_torch_fx_for_cueq()
return cue, cuet
def _patch_torch_fx_for_cueq():
try:
import torch.fx._symbolic_trace as symbolic_trace
except ImportError:
return
if (
not hasattr(symbolic_trace, "is_fx_symbolic_tracing")
and hasattr(symbolic_trace, "is_fx_tracing")
):
symbolic_trace.is_fx_symbolic_tracing = symbolic_trace.is_fx_tracing
def _cue_irreps(cue, irreps):
return cue.Irreps("O3", str(o3.Irreps(irreps)))
def _cue_e3nn_layout(cue):
layout = getattr(cue, "mul_ir", None)
if layout is None:
layout = getattr(cue, "ir_mul", None)
if layout is None:
raise RuntimeError("Could not find an e3nn-compatible cuEquivariance layout.")
return layout
class AtomicEmbedding(nn.Module):
"""
Learnable embedding for atomic numbers. Maps integer Z to a vector of
size `embedding_dim`. Returns the initial node embedding for each atom type.
This is superior to traditional one-hot encoding because it allows the model
to learn relationships between different atomic numbers. One-hot-encoding
treats all atom types as orthogonal and thus equally distinct, which is far
from true (e.g., F is more chemically similar to Cl than to Fe).
"""
def __init__(self, max_z=100, embedding_dim=64):
super().__init__()
# Unused entries are never updated and don't hurt learning
self.embedding = nn.Embedding(max_z + 1, embedding_dim)
def forward(self, z):
return self.embedding(z)
class EquivariantLayerNorm(nn.Module):
"""
Custom Equivariant Layer Normalization.
For L=0 features: Standard LayerNorm over channels.
For L>0 features: RMSNorm over channels and spatial components (no centering/beta).
The idea of layer normalization is to normalize the features of each layer to have
mean 0 and variance 1. Then, we scale and shift the features by learnable parameters
gamma and beta to learn the best representation. This helps to prevent the features
from growing too large or too small during trainin (which can lead to instability)
and also allow the network to emphasize important features or suppress irrelevant ones.
In the context of equivariant networks, we need to be careful not to break equivariance.
We cannot center L>0 features because that would break the equivariance (add a constant
vector to a vector changes its direction). Instead, we normalize the features by their
norm (RMSNorm), and then learn the scale of each irreducible representation using gamma.
Note that gamma is a vector (1, mul), so each irrep/channel has its own learnable scale.
By multiplying the RMSE normalized channel/irrep by a constant, we scale it without
altering its direction or geometric meaning.
"""
def __init__(self, irreps, eps=1e-5):
super().__init__()
self.irreps = o3.Irreps(irreps)
self.eps = eps
# We need a separate gamma vector (1,mul) for each L-block
self.gammas = nn.ParameterList()
# For L=0, we also keep the standard beta (1,mul)
self.betas = nn.ParameterList()
for mul, ir in self.irreps:
self.gammas.append(nn.Parameter(torch.ones(1, mul)))
if ir.l == 0:
self.betas.append(nn.Parameter(torch.zeros(1, mul)))
def forward(self, x):
# x shape: [N, sum(dim_i * mul_i)]
out = []
idx = 0
beta_idx = 0
for i, (mul, ir) in enumerate(self.irreps):
length = mul * ir.dim
# Slice the specific L block: shape [N, mul * (2L+1)]
field = x[:, idx : idx + length]
idx += length
# Reshape to [N, mul, 2L+1] to separate channels from spatial components
field = field.view(-1, mul, ir.dim)
if ir.l == 0:
# Standard LayerNorm for scalars (across channels)
mean = field.mean(dim=1, keepdim=True)
var = field.var(dim=1, keepdim=True, unbiased=False)
field_norm = (field - mean) / torch.sqrt(var + self.eps)
# Apply gamma and beta
field_norm = field_norm * self.gammas[i].unsqueeze(-1) + self.betas[beta_idx].unsqueeze(-1)
beta_idx += 1
else:
# RMSNorm for higher-order tensors (without Beta)
# Mean across BOTH channels (dim=1) and spatial components (dim=2)
var = (field ** 2).mean(dim=(1, 2), keepdim=True) # [N, 1, 1]
field_norm = field / torch.sqrt(var + self.eps) # [N, mul, 2L+1]
# Apply gamma (same scaling is broadcasted across the 2L+1 components of each channel/irrep)
field_norm = field_norm * self.gammas[i].unsqueeze(-1) # [N, mul, 2L+1]
# Flatten back to [N, mul * (2L+1)]
out.append(field_norm.view(-1, length))
return torch.cat(out, dim=-1)
class EquivariantGatedAdaptiveResidual(nn.Module):
"""
Equivariant Gated Adaptive Residual Connection.
Computes: gate * Linear(x) + (1 - gate) * message
where `gate` is a per-channel scalar learned from the scalar (l=0) features
of both the input and the message. It avoids breaking equivariance by explicitly
broadcasting the scalar gates across the 2l+1 dimensions of higher-l irreps.
Computes gates inside node $i$ to decide how much to listen to the aggregated
neighborhood versus its own history. Technically, we use invariant scalar
features to control the flow of information without destroying geometric
information contained in the L>0 features and thus preserving equivariance.
The difference to the LayerNorm is that the "gamma" here (gate) is not a
learnable parameter, but rather a function of the scalar input features.
Also, we don't normalize the features here, we just scale them by the
gate constructed by mixing all scalar features.
"""
def __init__(self, irreps_in, irreps_out):
super().__init__()
self.irreps_in = o3.Irreps(irreps_in)
self.irreps_out = o3.Irreps(irreps_out)
self.sc = o3.Linear(self.irreps_in, self.irreps_out)
# Precompute slices to carefully extract scalar features without assuming ordering
self.scalar_slices_in = []
current_idx = 0
for mul, ir in self.irreps_in:
if ir.l == 0:
self.scalar_slices_in.append((current_idx, current_idx + mul))
current_idx += mul * ir.dim
self.scalar_slices_out = []
current_idx = 0
for mul, ir in self.irreps_out:
if ir.l == 0:
self.scalar_slices_out.append((current_idx, current_idx + mul))
current_idx += mul * ir.dim
n_scalars_in = sum(end - start for start, end in self.scalar_slices_in)
n_scalars_out = sum(end - start for start, end in self.scalar_slices_out)
n_gate_values = sum(mul for mul, ir in self.irreps_out)
self.gate_mlp = nn.Sequential(
nn.Linear(n_scalars_in + n_scalars_out, n_gate_values),
nn.Sigmoid()
)
# Precompute the fast interleave pattern to expand scalar gates to full (2l+1) tensor shape
gate_repeats = []
for mul, ir in self.irreps_out:
gate_repeats.extend([ir.dim] * mul)
self.register_buffer('gate_repeats', torch.tensor(gate_repeats, dtype=torch.long))
def _extract_scalars(self, x, slices):
if not slices:
return torch.empty(x.shape[0], 0, device=x.device, dtype=x.dtype)
return torch.cat([x[:, start:end] for start, end in slices], dim=-1)
def forward(self, x, m):
residual = self.sc(x) # self-interaction
x_scalars = self._extract_scalars(x, self.scalar_slices_in)
m_scalars = self._extract_scalars(m, self.scalar_slices_out)
gate_input = torch.cat([x_scalars, m_scalars], dim=-1)
gate_values = self.gate_mlp(gate_input) # [N, mul_0 + mul_1 + mul_2]
# Expand gates from shape [N, mul_0 + mul_1 + mul_2] to [N, 1*mul_0 + 3*mul_1 + 5*mul_2]
gate_expanded = torch.repeat_interleave(gate_values, self.gate_repeats, dim=-1)
# This formulation helps to avoid over-smoothing because the network can choose to
# completely preserve the information from the previous layer by setting the gate to 1.
return gate_expanded * residual + (1 - gate_expanded) * m
class InteractionBlock(nn.Module):
"""
E(3)-equivariant interaction block with gated non-linearity.
Performs message passing: m_ij = TP(h_j, Y_ij) * MLP(d_ij),
aggregates messages, applies layer norm, gates the context
message, and then finds how to best mix the context with
current embedding h_i to produce the output.
"""
def __init__(self,
irreps_in,
irreps_out,
irreps_sh,
number_of_radial_basis_functions,
r_max=5.0,
radial_basis_type='bessel',
equivariance_backend='e3nn'):
super().__init__()
self.irreps_in = o3.Irreps(irreps_in)
self.irreps_out = o3.Irreps(irreps_out)
self.irreps_sh = o3.Irreps(irreps_sh)
self.equivariance_backend = str(equivariance_backend).lower()
if self.equivariance_backend not in {"e3nn", "cueq"}:
raise ValueError(
"equivariance_backend must be either 'e3nn' or 'cueq', "
f"got {equivariance_backend!r}"
)
# --- Build Gate irreps ---
# Gate needs: scalar activations for l=0, and one gate scalar per
# non-scalar channel (l>0).
irreps_scalars = o3.Irreps(
[(mul, ir) for mul, ir in self.irreps_out if ir.l == 0]
)
irreps_nonscalars = o3.Irreps(
[(mul, ir) for mul, ir in self.irreps_out if ir.l > 0]
)
# One gate scalar (0e) per non-scalar multiplicity
irreps_gates = o3.Irreps(
[(mul, "0e") for mul, ir in self.irreps_out if ir.l > 0]
)
# The TP must produce: scalars + gate_scalars + non-scalars
self.irreps_tp_out = irreps_scalars + irreps_gates + irreps_nonscalars
self.layernorm = EquivariantLayerNorm(self.irreps_tp_out)
# Gate module
act_scalars = [torch.nn.functional.silu] * len(irreps_scalars)
act_gates = [torch.sigmoid] * len(irreps_gates)
self.gate = Gate(
irreps_scalars=irreps_scalars,
act_scalars=act_scalars,
irreps_gates=irreps_gates,
act_gates=act_gates,
irreps_gated=irreps_nonscalars,
)
# --- Tensor Product ---
e3nn_tp = o3.FullyConnectedTensorProduct(
irreps_in1=self.irreps_in,
irreps_in2=self.irreps_sh,
irreps_out=self.irreps_tp_out,
irrep_normalization="component",
path_normalization="element",
shared_weights=False,
internal_weights=False,
)
self.tp_weight_numel = e3nn_tp.weight_numel
if self.equivariance_backend == "e3nn":
self.tp = e3nn_tp
else:
cue, cuet = _load_cueq()
self.tp = cuet.FullyConnectedTensorProduct(
_cue_irreps(cue, self.irreps_in),
_cue_irreps(cue, self.irreps_sh),
_cue_irreps(cue, self.irreps_tp_out),
layout=_cue_e3nn_layout(cue),
shared_weights=False,
internal_weights=False,
math_dtype=torch.float32,
method="fused_tp",
)
# --- Radial basis + MLP for TP weights ---
self.num_radial = number_of_radial_basis_functions
self.r_max = r_max
self.radial_basis_type = radial_basis_type
if self.radial_basis_type == 'bessel':
# Frequencies for spherical bessel functions: n*pi / r_max
# where n = 1, 2, ..., num_radial
n_pi = torch.arange(1, self.num_radial + 1, dtype=torch.float32) * torch.pi
self.register_buffer('bessel_freqs', n_pi / self.r_max)
elif self.radial_basis_type == 'gaussian':
# Means for Gaussian basis functions, spaced evenly from 0 to r_max
means = torch.linspace(0, self.r_max, self.num_radial)
self.register_buffer('gaussian_means', means)
# Match std to exact spacing between means for optimal overlap
spacing = self.r_max / max(1, self.num_radial - 1)
self.register_buffer('gaussian_std', torch.tensor(spacing))
else:
raise ValueError(f"Unknown radial basis type: {self.radial_basis_type}")
self.fc = FullyConnectedNet(
[self.num_radial, 64, self.tp_weight_numel],
torch.nn.functional.silu,
)
# --- Gated Residual connection ---
self.has_residual = (self.irreps_in == self.irreps_out) # `True` only from the second layer onwards
self.gated_residual = None
if self.has_residual:
self.gated_residual = EquivariantGatedAdaptiveResidual(self.irreps_in, self.irreps_out)
def radial_basis(self, length):
"""
Spherical Bessel or Gaussian radial basis with cosine smooth cutoff.
"""
# Add small epsilon to avoid division by zero at origin
d = length.unsqueeze(-1) + 1e-8
if self.radial_basis_type == 'bessel':
# Spherical Bessel j_0(k*d) = sin(k*d) / (k*d)
# We can use torch.sinc(x) = sin(pi*x)/(pi*x), so we pass (k*d)/pi
k_d = d * self.bessel_freqs.unsqueeze(0)
r_basis = torch.sinc(k_d / torch.pi)
elif self.radial_basis_type == 'gaussian':
# Gaussian exp(-0.5 * ((d - mu) / std)**2)
r_basis = torch.exp(-0.5 * ((d - self.gaussian_means) / self.gaussian_std) ** 2)
else:
raise ValueError(f"Unknown radial basis type: {self.radial_basis_type}")
# Cosine cutoff polynomial: 0.5 * (cos(pi * d / r_max) + 1.0)
# Monotonically and smoothly decreasing function from [0, r_max].
# We use pi*d/r_max instead of pi/2*d/r_max to ensure that not
# only the function but also its derivative are zero at d=r_max.
cutoff = 0.5 * (torch.cos(torch.pi * d / self.r_max) + 1.0)
# Enforce exact zero outside r_max just in case
cutoff = cutoff * (d < self.r_max).float()
return r_basis * cutoff
def forward(self, x, edge_attr=None, edge_length=None, edge_src=None, edge_dst=None):
# 1. Radial embedding -> TP weights
radial = self.radial_basis(edge_length) # (N_edges, num_radial)
tp_weights_radial = self.fc(radial) # (N_edges, irreps_tp_out)
# 2. Message computation via tensor product
x_j = x[edge_src] # (N_edges, irreps_in)
if self.equivariance_backend == "cueq":
with torch.amp.autocast(x.device.type, enabled=False):
m_ij = self.tp(
x_j.float(),
edge_attr.float(),
tp_weights_radial.float(),
)
else:
m_ij = self.tp(x_j, edge_attr, tp_weights_radial)
# m_ij shape: (N_edges, irreps_tp_out)
# 3. Aggregate messages at destination nodes (Mean is more stable than Add)
if HAS_TORCH_SCATTER:
m_i = scatter(m_ij, edge_dst, dim=0, dim_size=x.shape[0], reduce='mean') # (N, irreps_tp_out)
else:
m_i = torch.zeros(x.shape[0], m_ij.shape[1], device=x.device, dtype=x.dtype)
count = torch.zeros(x.shape[0], 1, device=x.device, dtype=x.dtype)
m_i.index_add_(0, edge_dst, m_ij)
count.index_add_(0, edge_dst, torch.ones_like(m_ij[:,:1]))
m_i = m_i / count.clamp(min=1)
# 4. Layer Normalization
m_i = self.layernorm(m_i) # (N, irreps_tp_out)
# 5. Gated non-linearity
m_i = self.gate(m_i) # (N, irreps_out)
# Note: Gate "consumes" `irreps_gates` scalars from `irreps_tp_out` to gate/activate non-scalar features
# 6. Gated residual connection
if self.gated_residual is not None:
m_i = self.gated_residual(x, m_i)
return m_i
|