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 this pooling SO3 equivariant
Okay, I understand. You're asking to modify the provided DenseMinCutPooling class to make it SO(3) equivariant. This is a challenging task, as the original pooling is not designed to respect rotational symmetries. Here's how we can approach this, along with explanations and code modifications:
Understanding the Challenge
Non-Equivariant Operations: The original DenseMinCutPooling uses a linear layer (self.lin) followed by a softmax to generate the assignment matrix s. These operations are not equivariant to rotations of the input features x. Rotating the input will not result in a corresponding rotation of the output.
Edge Index: The pooling operation also outputs a new edge index. How do we ensure these edges are invariant to the underlying coordinate system?
Core Ideas for SO(3) Equivariance
Replace Linear Layers with SO(3)-Equivariant Layers: Instead of standard torch.nn.Linear layers, we should utilize layers from the equiformer_v2.so3 module, specifically SO3_LinearV2. These layers preserve the transformation properties of the input features.
Use Spherical Harmonics: To represent the node features, we'll use SO3_Embedding. This allows for an expansion into spherical harmonics, which allows for rotationally equivariant representations.
Invariant Assignment Matrix: We must ensure the assignment matrix s is SO(3) invariant. This means it should not change when the input is rotated. We can achieve this by having it operate on invariants computed from the original node features. For example, the radial distances between nodes.
Invariant Edge Index: The new edge index should also be invariant. The mincut implementation computes the adjacency matrix from the assignment matrix, which will be invariant since the assignment matrix is invariant. The adjacency matrix is then converted to an edge index, which will also be invariant.
Modified Code
python
from typing import Optional, Tuple
import torch
from torch import Tensor
from equiformer_v2.so3 import SO3_Embedding, SO3_LinearV2, CoefficientMappingModule, SO3_Rotation
from torch_geometric.utils import dense_to_sparse
import math
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, modified for SO(3) equivariance.
.. math::
\mathbf{X}^{\prime} &= {\mathrm{softmax}(\mathbf{S})}^{\top} \cdot
\mathbf{X}
\mathbf{A}^{\prime} &= {\mathrm{softmax}(\mathbf{S})}^{\top} \cdot
\mathbf{A} \cdot \mathrm{softmax}(\mathbf{S})
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
.. math::
\mathcal{L}_c = - \frac{\mathrm{Tr}(\mathbf{S}^{\top} \mathbf{A}
\mathbf{S})} {\mathrm{Tr}(\mathbf{S}^{\top} \mathbf{D}
\mathbf{S})}
where :math:`\mathbf{D}` is the degree matrix, and (2) the orthogonality
loss
.. math::
\mathcal{L}_o = {\left\| \frac{\mathbf{S}^{\top} \mathbf{S}}
{{\|\mathbf{S}^{\top} \mathbf{S}\|}_F} -\frac{\mathbf{I}_C}{\sqrt{C}}
\right\|}_F.
Args:
in_channels (int): Size of each input sample.
out_channels (int): Number of output clusters.
lmax (int): Maximum degree of the spherical harmonics
temp (float, optional): Temperature parameter for softmax function.
(default: :obj:`1.0`)
mlp_hidden_channels (int, optional): Number of hidden channels in the MLP.
(default: :obj:`32`)
"""
def __init__(self, in_channels: int, out_channels: int, lmax: int,
temp: float = 1.0, mlp_hidden_channels: int = 32):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.lmax = lmax
self.temp = temp
self.lin = torch.nn.Sequential(
SO3_LinearV2(in_channels, mlp_hidden_channels, lmax=lmax),
torch.nn.ReLU(),
SO3_LinearV2(mlp_hidden_channels, out_channels, lmax=lmax)
)
self.mappingReduced = CoefficientMappingModule([lmax], [lmax])
self.SO3_rotation = SO3_Rotation(lmax)
def forward(
self,
x: SO3_Embedding,
edge_index: Tensor,
edge_distance_vec: Tensor,
mask: Optional[Tensor] = None,
) -> Tuple[SO3_Embedding, Tensor, Tensor, Tensor]:
r"""
Args:
x (SO3_Embedding): Node feature tensor
with batch-size :math:`B`, (maximum) number of nodes :math:`N` for
each graph, and feature dimension :math:`F`.
edge_index (torch.Tensor): Edge index tensor
:math:`\mathbf{edge\_index} \in \mathbb{R}^{2 \times E}`.
edge_distance_vec (torch.Tensor): Edge distance vector
:math:`\mathbf{edge\_distance_vec} \in \mathbb{R}^{B \times E \times 3}`.
mask (torch.Tensor, optional): Mask matrix
:math:`\mathbf{M} \in {\{ 0, 1 \}}^{B \times N}` indicating
the valid nodes for each graph. (default: :obj:`None`)
:rtype: (:class:`SO3_Embedding`, :class:`torch.Tensor`,
:class:`torch.Tensor`, :class:`torch.Tensor`)
"""
x_emb = x.embedding
x_emb = x_emb.unsqueeze(0) if x_emb.dim() == 2 else x_emb
(batch_size, num_nodes, _), k = x_emb.size(), self.out_channels
# Initialize the WignerD matrices and other values for spherical harmonic calculations
edge_rot_mat = self._init_edge_rot_mat(edge_distance_vec)
self.SO3_rotation.set_wigner(edge_rot_mat)
adj = torch.zeros(batch_size, num_nodes, num_nodes,
dtype=x_emb.dtype, device=x_emb.device)
row, col = edge_index
adj[torch.arange(batch_size).view(-1, 1, 1), row, col] = 1
s_emb = self.lin(x)
s = s_emb.embedding.narrow(2, 0, 1) # use only the l=0 component
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_emb.dtype)
x_emb, s = x_emb * mask, s * mask
out_emb = torch.matmul(s.transpose(1, 2), x_emb)
out_adj = torch.matmul(torch.matmul(s.transpose(1, 2), adj), s)
# MinCut regularization.
mincut_num = _rank3_trace(out_adj)
d_flat = torch.einsum('ijk->ij', adj)
d = _rank3_diag(d_flat)
mincut_den = _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
out = SO3_Embedding(
0,
x.lmax_list.copy(),
x.num_channels,
device=x.device,
dtype=x.dtype
)
out.set_embedding(out_emb)
out.set_lmax_mmax(x.lmax_list.copy(), x.mmax_list.copy())
return out, out_edge_index, mincut_loss, ortho_loss
# Initialize the edge rotation matrics
def _init_edge_rot_mat(self, edge_distance_vec):
x = edge_distance_vec @ edge_distance_vec.new_tensor([0.0, 1.0, 0.0])
alpha, beta = o3.xyz_to_angles(x)
R = (
o3.angles_to_matrix(
alpha, beta, torch.zeros_like(alpha)
).transpose(-1, -2)
@ edge_distance_vec
)
gamma = torch.atan2(R[..., 0, 2], R[..., 0, 0])
wigner = torch.zeros(len(alpha), (self.lmax + 1)**2, (self.lmax+1)**2, device=edge_distance_vec.device)
for lmax in range(0, self.lmax + 1):
block = wigner_D(lmax, alpha, beta, gamma)
wigner[:, lmax**2:(lmax+1)**2, lmax**2:(lmax+1)**2] = block
return wigner.detach()
def _rank3_trace(x: Tensor) -> Tensor:
return torch.einsum('ijj->i', x)
def _rank3_diag(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 and Explanation:
SO3_Embedding Input: The forward pass now takes an SO3_Embedding as input instead of a simple tensor.
SO3_LinearV2: The torch.nn.Linear layers in self.lin are replaced with SO3_LinearV2 to ensure equivariance.
lmax Parameter: The lmax parameter is now a required input and is used to initialize SO3_LinearV2.
Invariant Assignment Matrix: The assignment matrix s is now computed from an equivariant projection of the input features and only uses the l=0 component, which means it is invariant to rotations.
Output Type: The output is now an SO3_embedding as opposed to a tensor to ensure the output is SO3 equivariant.
Edge Rotation: Edge rotation matrices are computed from the edge distance vectors to be used by the SO3_Rotation class.
Wigner Matrices: The SO3_Rotation class now computes Wigner D matrices to ensure equivariance when pooling.
Integration: This modified DenseMinCutPooling is designed to work within the equiformer_v2 framework. It expects SO3_Embedding objects and SO(3) equivariant layers.
Computational Cost: Using spherical harmonics and SO(3)-equivariant layers can increase computational cost.
Choice of lmax: The lmax parameter determines the complexity of the representation and should be chosen carefully based on the task and data.
Edge Features: The current code doesn't explicitly use edge features. If needed, you would need to incorporate them in an SO(3)-equivariant manner, potentially by using relative distance or direction.
Normalization: You should normalize the output of the SO3_LinearV2 layers using equivariant layer norms to avoid instability in training.
This provides a solid starting point for implementing SO(3) equivariant MinCut pooling. You may need to adapt this further based on your specific application.