File size: 3,316 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 | import torch
import torch.nn as nn
from e3nn import o3
from torch_scatter import scatter_softmax, scatter_add
class AbsorberQueryAttention(nn.Module):
"""
Absorber-Query Attention Pooling.
Uses the absorber's state as a Query to attend to neighbor atoms (Keys/Values).
Aggregates neighbor features into a single context vector.
"""
def __init__(self, irep_in, hidden_dim=64):
super().__init__()
self.irep_in = o3.Irreps(irep_in)
# Count scalar (0e) channels
self.n_scalars = 0
for mul, ir in self.irep_in:
if ir.l == 0 and ir.p == 1:
self.n_scalars += mul
if self.n_scalars == 0:
raise ValueError(
"Input irreps must contain scalar (0e) features for attention pooling."
)
# Attention MLP: (s_absorber, s_neighbor) → score
self.attn_mlp = nn.Sequential(
nn.Linear(2 * self.n_scalars, hidden_dim),
nn.SiLU(),
nn.Linear(hidden_dim, 1),
)
def forward(self, x, absorber_mask, batch):
"""
Average the scalar features of the absorbers to create a global query. Then, we
put this global query with each node's scalar features through a MLP to compute
attention scores. In other words, we use the global query to attend to all atoms
in the graph. Finally, aggregate the features of all atoms in the graph weighted
by the attention scores to produce a context vector.
Args:
x: Feature tensor [N_nodes, feature_dim] matching irep_in.
absorber_mask: Boolean mask [N_nodes], True for absorber atoms.
batch: Batch index [N_nodes].
Returns:
context: Pooled context vectors [N_graphs, n_scalars].
"""
# Extract scalar features (assumed to be first n_scalars channels)
scalars = x[:, :self.n_scalars] # [N_nodes, n_scalars]
# Compute Global Query per graph (Average of all absorbers in the graph)
# batch[absorber_mask] maps each absorber to its graph index
q_global = scatter_add(scalars[absorber_mask], batch[absorber_mask], dim=0, dim_size=int(batch.max()) + 1)
num_absorbers = scatter_add(torch.ones_like(batch[absorber_mask]), batch[absorber_mask], dim=0, dim_size=int(batch.max()) + 1).clamp(min=1).unsqueeze(1)
q_global = q_global / num_absorbers # [N_graphs, n_scalars]
# Expand query to all nodes in the graph
q_expanded = q_global[batch] # [N_nodes, n_scalars]
# Attention scores
cat_features = torch.cat([q_expanded, scalars], dim=1) # [N_nodes, 2*n_scalars]
raw_scores = self.attn_mlp(cat_features) # [N_nodes, 1]
# Mask out the absorbers (score = -inf)
raw_scores = raw_scores.masked_fill(absorber_mask.unsqueeze(1), -1e9) # [N_nodes, 1]
# Softmax per graph to compute attention scores
attention_scores = scatter_softmax(raw_scores, batch, dim=0) # [N_nodes, n_scalars]
# Weighted sum of scalar features using attention scores
context = scatter_add(attention_scores * scalars, batch, dim=0) # [N_graphs, n_scalars]
return context
|