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