x = torch.randn(batch_size, num_nodes, in_channels)
edge_index = torch.tensor([[0, 3, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9],
[1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 9, 8]],
dtype=torch.long).repeat(batch_size, 1, 1)
mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0]], dtype=torch.bool)
from typing import Optional, Tuple
import torch
from torch import Tensor
from e3nn import o3
from .so3 import (
SO3_Embedding,
SO3_LinearV2,
SO3_Rotation,
CoefficientMappingModule,
SO3_Grid,
)
from .layer_norm import (
EquivariantLayerNormArraySphericalHarmonics
)
from .edge_rot_mat import init_edge_rot_mat
class DenseEquivariantMinCutPooling(torch.nn.Module):
r"""Equivariant MinCut pooling operator.
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`)
lmax_list (List[int]): List of maximum degree of the spherical harmonics.
mmax_list (List[int]): List of maximum order of the spherical harmonics.
grid_resolution (int): Resolution of SO3_Grid.
"""
def __init__(
self,
in_channels: int,
out_channels: int,
temp: float = 1.0,
mlp_hidden_channels: int = 32,
lmax_list = [6],
mmax_list = [2],
grid_resolution = 18,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.temp = temp
self.lmax_list = lmax_list
self.mmax_list = mmax_list
self.num_resolutions = len(self.lmax_list)
self.grid_resolution = grid_resolution
self.mappingReduced = CoefficientMappingModule(self.lmax_list, self.mmax_list)
# Initialize the transformations between spherical and grid representations
self.SO3_grid = torch.nn.ModuleList()
for l in range(max(self.lmax_list) + 1):
SO3_m_grid = torch.nn.ModuleList()
for m in range(max(self.lmax_list) + 1):
SO3_m_grid.append(
SO3_Grid(
l,
m,
resolution=self.grid_resolution,
normalization='component'
)
)
self.SO3_grid.append(SO3_m_grid)
self.SO3_rotation = torch.nn.ModuleList()
for i in range(self.num_resolutions):
self.SO3_rotation.append(SO3_Rotation(self.lmax_list[i]))
self.lin = torch.nn.Sequential(
SO3_LinearV2(in_channels, mlp_hidden_channels, lmax_list, mmax_list),
torch.nn.SiLU(),
SO3_LinearV2(mlp_hidden_channels, out_channels, lmax_list, mmax_list)
)
self.norm = EquivariantLayerNormArraySphericalHarmonics(lmax=max(self.lmax_list), num_channels=out_channels)
def forward(
self,
x: SO3_Embedding,
pos: Tensor,
edge_index: Tensor,
mask: Optional[Tensor] = None,
) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
r"""
Args:
x (SO3_Embedding): Node feature tensor
:math:`\mathbf{X} \in \mathbb{R}^{B \times N \times F}`, with
batch-size :math:`B`, (maximum) number of nodes :math:`N` for
each graph, and feature dimension :math:`F`.
pos (torch.Tensor): Node positions
:math:`\mathbf{pos} \in \mathbb{R}^{B \times N \times 3}`.
edge_index (torch.Tensor): Edge index tensor
:math:`\mathbf{edge\_index} \in \mathbb{R}^{2 \times E}`.
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:`torch.Tensor`, :class:`torch.Tensor`,
:class:`torch.Tensor`, :class:`torch.Tensor`)
"""
# Get the device and dtype of the input
device = x.embedding.device
dtype = x.embedding.dtype
x_emb = x.embedding
(batch_size, num_nodes, _), k = x_emb.size(), self.out_channels
# Initialize adjacency matrix
adj = torch.zeros(batch_size, num_nodes, num_nodes, dtype=dtype, device=device)
row, col = edge_index
adj[torch.arange(batch_size).view(-1, 1, 1), row, col] = 1
# Compute edge directions
edge_distance_vec = pos[row] - pos[col]
# Compute 3x3 rotation matrix per edge
edge_rot_mat = self._init_edge_rot_mat(
pos, edge_index, edge_distance_vec
)
# Initialize the WignerD matrices and other values for spherical harmonic calculations
for i in range(self.num_resolutions):
self.SO3_rotation[i].set_wigner(edge_rot_mat)
# Compute the assignment matrix using equivariant linear layers
s = self.lin(x)
s = torch.softmax(s.embedding / self.temp if self.temp != 1.0 else s.embedding, dim=-1)
s = SO3_Embedding(num_nodes, self.lmax_list, self.out_channels, device=device, dtype=dtype, embedding=s)
if mask is not None:
mask = mask.view(batch_size, num_nodes, 1).to(dtype)
x_emb, s_emb = x_emb * mask, s.embedding * mask
x = SO3_Embedding(num_nodes, self.lmax_list, self.in_channels, device=device, dtype=dtype, embedding=x_emb)
s = SO3_Embedding(num_nodes, self.lmax_list, self.out_channels, device=device, dtype=dtype, embedding=s_emb)
out = torch.matmul(s.embedding.transpose(1, 2), x.embedding)
out = SO3_Embedding(num_nodes, self.lmax_list, self.in_channels, device=device, dtype=dtype, embedding=out)
out_adj = torch.matmul(torch.matmul(s.embedding.transpose(1, 2), adj), s.embedding)
# 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.embedding.transpose(1, 2), d), s.embedding))
mincut_loss = -(mincut_num / mincut_den)
mincut_loss = torch.mean(mincut_loss)
# Orthogonality regularization.
ss = torch.matmul(s.embedding.transpose(1, 2), s.embedding)
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.embedding = self.norm(out.embedding)
return out, out_edge_index, mincut_loss, ortho_loss
# Initialize the edge rotation matrics
def _init_edge_rot_mat(self, pos, edge_index, edge_distance_vec):
return init_edge_rot_mat(edge_distance_vec)
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
if __name__ == '__main__':
batch_size = 2
num_nodes = 10
in_channels = 16
out_channels = 5
mlp_hidden_channels = 32
lmax_list = [6]
mmax_list = [2]
device = 'cpu'
dtype = torch.float32
# Create random node features as SO3_Embedding
x = SO3_Embedding(num_nodes, lmax_list, in_channels, device=device, dtype=dtype)
x.embedding = torch.randn(batch_size, num_nodes, x.embedding.shape[-1], device=device, dtype=dtype)
# Random node positions
pos = torch.randn(batch_size, num_nodes, 3, device=device, dtype=dtype)
# Edge indices (same as in the example)
edge_index = torch.tensor([[0, 3, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9],
[1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 9, 8]],
dtype=torch.long, device=device).repeat(batch_size, 1, 1)
# Mask (same as in the example)
mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0]], dtype=torch.bool, device=device)
pool = DenseEquivariantMinCutPooling(in_channels, out_channels, mlp_hidden_channels=mlp_hidden_channels, lmax_list=lmax_list, mmax_list=mmax_list)
out, out_edge_index, mincut_loss, ortho_loss = pool(x, pos, edge_index[0], mask)
print("Pooled features:", out.embedding.shape)
print("Pooled edge index:", out_edge_index.shape)
print("MinCut loss:", mincut_loss)
print("Orthogonality loss:", ortho_loss)