class DenseMinCutPooling(torch.nn.Module):
r"""The MinCut pooling operator from the "Spectral Clustering in Graph Neural Networks for Graph Pooling" https://arxiv.org/abs/1907.00481_ paper.
based on dense learned assignments :math:\mathbf{S} \in \mathbb{R}^{B \times N \times C}.
Returns the pooled node feature matrix, the coarsened and symmetrically
normalized adjacency matrix and two auxiliary objectives: (1) The MinCut
loss
Args:
in_channels (int): Size of each input sample.
out_channels (int): Number of output clusters.
temp (float, optional): Temperature parameter for softmax function.
(default: :obj:1.0)
mlp_hidden_channels (int, optional): Number of hidden channels in the MLP.
If not specified, a linear layer is used. (default: :obj:None)
"""
def init(self, in_channels: int, out_channels: int,
temp: float = 1.0, mlp_hidden_channels: int = 32):
super().init()
print("Pooled features:", out.shape)
print("Pooled edge index:", out_edge_index.shape)
print("MinCut loss:", mincut_loss)
print("Orthogonality loss:", ortho_loss)
Make it SO3 equivariant
To make the DenseMinCutPooling SO(3) equivariant, we need to integrate the following modifications to ensure that the operations respect the SO(3) symmetry. This involves working with spherical harmonics and tensors in a way that is invariant under rotations. Here's how we can achieve this:
Steps to Incorporate SO(3) Equivariance
Replace Linear Layers with SO(3)-Equivariant Layers:
Instead of using standard torch.nn.Linear layers within the pooling module, we use SO(3)-equivariant layers like SO3_Linear or SO3_LinearV2 (from the equiformer_v2 repository).
Use Spherical Harmonics for Representations:
Node features and edge features must be represented in terms of spherical harmonics. This is crucial for making the system respect the SO(3) symmetry.
Modify Edge Features and Adjacency Matrix:
Edge features (i.e., edge_index and adjacency matrix) should be encoded using rotation-equivariant embeddings (e.g., relative positions encoded using spherical harmonics).
SO(3)-Equivariant Operations:
Operations such as softmax, dot products, and pooling should be adapted to ensure equivariance. For example, using appropriate normalization methods like EquivariantLayerNormArray.
Use SO(3)-Compatible Distance Functions:
Expand distances (used in adjacency matrices) using equivariant radial basis functions, such as GaussianRadialBasisLayer.
SO(3)-Equivariant Implementation
Here is the modified version of the DenseMinCutPooling class that incorporates SO(3) equivariance:
python
from typing import Optional, Tuple
import torch
from torch import Tensor
from equiformer_v2.nets.equiformer_v2.so3 import SO3_LinearV2, SO3_Embedding
from equiformer_v2.nets.equiformer_v2.gaussian_rbf import GaussianRadialBasisLayer
from equiformer_v2.nets.equiformer_v2.layer_norm import EquivariantLayerNormArray
class SO3DenseMinCutPooling(torch.nn.Module):
r"""
SO(3)-equivariant version of DenseMinCutPooling using SO(3)-equivariant layers.
"""
def __init__(
self,
in_channels: int,
out_channels: int,
temp: float = 1.0,
mlp_hidden_channels: int = 32,
lmax: int = 2, # Maximum degree for spherical harmonics
max_neighbors: int = 20,
cutoff: float = 5.0
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.temp = temp
self.lmax = lmax
self.max_neighbors = max_neighbors
self.cutoff = cutoff
# Distance expansion for equivariant edge features
self.distance_expansion = GaussianRadialBasisLayer(num_basis=mlp_hidden_channels, cutoff=self.cutoff)
# SO(3)-equivariant embedding for input features
self.embedding = SO3_Embedding(
num_nodes=1, # Placeholder, updated dynamically
lmax=self.lmax,
num_channels=in_channels,
device="cpu", # Replace with "cuda" if needed
dtype=torch.float32
)
# SO(3)-equivariant linear layer for assignment matrix
self.lin = torch.nn.Sequential(
SO3_LinearV2(in_channels, mlp_hidden_channels, lmax=self.lmax),
EquivariantLayerNormArray(mlp_hidden_channels, lmax=self.lmax),
torch.nn.ReLU(),
SO3_LinearV2(mlp_hidden_channels, out_channels, lmax=self.lmax)
)
def forward(
self,
x: Tensor,
edge_index: Tensor,
edge_distance_vec: Tensor,
mask: Optional[Tensor] = None
) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
"""
Forward pass for SO(3)-equivariant dense MinCutPooling.
"""
x = x.unsqueeze(0) if x.dim() == 2 else x
(batch_size, num_nodes, _), k = x.size(), self.out_channels
###############################################################
# Initialize edge features and adjacency matrix
###############################################################
# Compute distances and expand with equivariant radial basis
edge_distance = torch.norm(edge_distance_vec, dim=-1, keepdim=True)
edge_distance = self.distance_expansion(edge_distance)
# Create equivariant adjacency matrix
adj = torch.zeros(batch_size, num_nodes, num_nodes, dtype=x.dtype, device=x.device)
row, col = edge_index
adj[torch.arange(batch_size).view(-1, 1, 1), row, col] = edge_distance.view(-1)
###############################################################
# Compute SO(3)-equivariant assignment matrix
###############################################################
s = self.lin(x)
s = torch.softmax(s / self.temp if self.temp != 1.0 else s, dim=-1)
if mask is not None:
mask = mask.view(batch_size, num_nodes, 1).to(x.dtype)
x, s = x * mask, s * mask
###############################################################
# Perform SO(3)-equivariant pooling
###############################################################
out = torch.matmul(s.transpose(1, 2), x)
out_adj = torch.matmul(torch.matmul(s.transpose(1, 2), adj), s)
# MinCut regularization
mincut_num = self._rank3_trace(out_adj)
d_flat = torch.einsum('ijk->ij', adj)
d = self._rank3_diag(d_flat)
mincut_den = self._rank3_trace(torch.matmul(torch.matmul(s.transpose(1, 2), d), s))
mincut_loss = -(mincut_num / mincut_den)
mincut_loss = torch.mean(mincut_loss)
# Orthogonality regularization
ss = torch.matmul(s.transpose(1, 2), s)
i_s = torch.eye(k).type_as(ss)
ortho_loss = torch.norm(
ss / torch.norm(ss, dim=(-1, -2), keepdim=True) -
i_s / torch.norm(i_s), dim=(-1, -2))
ortho_loss = torch.mean(ortho_loss)
EPS = 1e-15
# Fix and normalize coarsened adjacency matrix
ind = torch.arange(k, device=out_adj.device)
out_adj[:, ind, ind] = 0
d = torch.einsum('ijk->ij', out_adj)
d = torch.sqrt(d)[:, None] + EPS
out_adj = (out_adj / d) / d.transpose(1, 2)
# Convert adjacency matrix to edge index
out_edge_index = out_adj.nonzero(as_tuple=False).t()
out_edge_index = out_edge_index[1:] # Remove batch index
return out, out_edge_index, mincut_loss, ortho_loss
###############################################################
# Helper functions for trace and diagonal
###############################################################
def _rank3_trace(self, x: Tensor) -> Tensor:
return torch.einsum('ijj->i', x)
def _rank3_diag(self, x: Tensor) -> Tensor:
eye = torch.eye(x.size(1)).type_as(x)
out = eye * x.unsqueeze(2).expand(x.size(0), x.size(1), x.size(1))
return out
Key Changes
SO(3)-Equivariant Layers:
Replaced torch.nn.Linear with SO3_LinearV2 layers for equivariance.
Used EquivariantLayerNormArray for normalization.
Distance Expansion:
Added GaussianRadialBasisLayer to expand distances equivariantly.
Edge Features and Adjacency:
Incorporated spherical harmonic representations into edge features.
Equivariant Regularizations:
Adapted MinCut and orthogonality loss to the SO(3) setup.