在 PyTorch Geometric 中,如何自定义 MessagePassing 基类?

解读

国内算法岗面试中,图神经网络(GNN)已成“标配”考点。PyTorch Geometric(简称 PyG)的 MessagePassing 基类是落地 GNN 的核心接口,面试官通过“自定义”考察候选人对“消息-聚合-更新”范式的理解深度、代码严谨度以及性能意识。回答时既要给出可运行骨架,又要体现工程细节(维度对齐、稀疏矩阵、CUDA 友好、内存复用),否则会被追问“这段代码 O(n²) 怎么办”“分布式怎么切图”。

知识点

  1. MessagePassing 三大抽象:message(…) 生成邻居消息、aggregate(…) 归约邻居、update(…) 刷新自身表征。
  2. 关键属性:aggr ∈ {‘add’, ‘mean’, ‘max’} 控制聚合函数;flow ∈ {‘source_to_target’, ‘target_to_source’} 控制消息方向;node_dim=-2 保证批量维度正确。
  3. 稀疏索引:edge_index 为 [2, num_edges] 的 COO 格式,需用 torch_geometric.utils 的 add_remaining_self_loop、softmax 等工具保持数值稳定。
  4. 维度约定:x_j 为源节点特征 [E, F],x_i 为目标节点特征 [E, F],二者通过 edge_index[0]、edge_index[1] 索引;批量训练时增加 batch 向量,需用 torch_scatter.segment_csr 做级联归约。
  5. 性能陷阱:避免显式构造 [N, N] 稠密矩阵;message 阶段尽量用 einsum/bmm 而非 for-loop;aggregate 用 scatter 系列算子而非 Python list。
  6. TorchScript 兼容:禁用动态属性、强制类型注解,确保 forward 可导出为 C++ 推理节点。

答案

下面给出一个工业级可落地的自定义示例:带注意力、残差、归一化的 Graph Attention Layer(GATv2)。代码可直接复制到 PyG ≥2.3 环境运行,并附带中文注释解释面试关注点。

import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_remaining_self_loops, softmax
from torch_scatter import scatter
from typing import Optional, Tuple

class GATv2Conv(MessagePassing):
    """
    面试亮点:
    1. 继承 MessagePassing,重写 message/aggregate/update
    2. 支持多头、残差、batch norm、edge feature 预留接口
    3. 全部使用稀疏 scatter,无 O(N²) 操作
    """
    def __init__(self,
                 in_channels: int,
                 out_channels: int,
                 heads: int = 1,
                 concat: bool = True,
                 negative_slope: float = 0.2,
                 dropout: float = 0.0,
                 add_self_loops: bool = True,
                 residual: bool = True,
                 bias: bool = True):
        # 选择聚合方式:add 保证与官方 GAT 一致
        super().__init__(aggr='add', node_dim=-2, flow='source_to_target')
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.heads = heads
        self.concat = concat
        self.negative_slope = negative_slope
        self.dropout = dropout
        self.add_self_loops = add_self_loops
        self.residual = residual

        # 线性变换:W·x,输出维度 heads * out_channels
        self.lin = nn.Linear(in_channels, heads * out_channels, bias=False)

        # 注意力向量 a 分成 [a_l, a_r],用于计算 e_ij = a^T [W x_i || W x_j]
        self.att_l = nn.Parameter(torch.empty(1, heads, out_channels))
        self.att_r = nn.Parameter(torch.empty(1, heads, out_channels))

        # 残差映射:当输入输出维度不一致时做投影
        if residual and in_channels != heads * out_channels:
            self.res_lin = nn.Linear(in_channels, heads * out_channels, bias=False)
        else:
            self.register_parameter('res_lin', None)

        if bias and concat:
            self.bias = nn.Parameter(torch.empty(heads * out_channels))
        elif bias and not concat:
            self.bias = nn.Parameter(torch.empty(out_channels))
        else:
            self.register_parameter('bias', None)

        self.reset_parameters()

    def reset_parameters(self):
        nn.init.xavier_uniform_(self.lin.weight)
        nn.init.xavier_uniform_(self.att_l)
        nn.init.xavier_uniform_(self.att_r)
        if self.bias is not None:
            nn.init.zeros_(self.bias)
        if self.res_lin is not None:
            nn.init.xavier_uniform_(self.res_lin.weight)

    def forward(self,
                x: Tensor,
                edge_index: Tensor,
                edge_attr: Optional[Tensor] = None,
                size: Optional[Tuple[int, int]] = None) -> Tensor:
        """
        x: [N, F_in]
        edge_index: [2, E]
        size: 当图为二分图时传入 (num_source_nodes, num_target_nodes)
        """
        N = x.size(0)
        # 1) 线性变换 + 多头拆分: [N, heads*F'] -> [N, heads, F']
        x_l = x_r = self.lin(x).view(N, self.heads, self.out_channels)

        # 2) 添加自环,保证节点能接收自身信息
        if self.add_self_loops:
            edge_index, _ = add_remaining_self_loops(edge_index, num_nodes=N)

        # 3) 计算注意力系数,先算 e_ij = LeakyReLU( a_l^T W x_i + a_r^T W x_j )
        # alpha_l/r: [N, heads, 1]
        alpha_l = (x_l * self.att_l).sum(dim=-1, keepdim=True)
        alpha_r = (x_r * self.att_r).sum(dim=-1, keepdim=True)

        # 4) 消息传递
        out = self.propagate(edge_index, x=x_l, alpha=(alpha_l, alpha_r),
                             size=size)

        # 5) 残差连接
        if self.residual:
            res = x if self.res_lin is None else self.res_lin(x)
            res = res.view(N, -1, self.out_channels)
            out = out + res

        # 6) 偏置 & 拼接/平均
        if self.concat:
            out = out.view(N, self.heads * self.out_channels)
        else:
            out = out.mean(dim=1)

        if self.bias is not None:
            out = out + self.bias

        return out

    def message(self, x_j: Tensor, alpha_i: Tensor, alpha_j: Tensor,
                index: Tensor, ptr: Optional[Tensor],
                size_i: Optional[int]) -> Tensor:
        """
        x_j: [E, heads, F']  源节点特征
        alpha_i/j: [E, heads, 1]  目标/源注意力分数
        index: [E]  目标节点索引,用于 softmax
        """
        # 计算未归一化注意力
        alpha = alpha_i + alpha_j  # [E, heads, 1]
        alpha = F.leaky_relu(alpha, self.negative_slope)
        # 按目标节点做 softmax,保证 ∑_{j∈N(i)} α_{ij}=1
        alpha = softmax(alpha, index, ptr, size_i)
        alpha = F.dropout(alpha, p=self.dropout, training=self.training)
        # 消息 = α * x_j
        return x_j * alpha  # [E, heads, F']

    def update(self, aggr_out: Tensor) -> Tensor:
        """
        aggr_out: [N, heads, F']  已完成 ∑αx 聚合
        这里可再接入 LayerNorm、BN、激活函数
        """
        return aggr_out

使用示例(供面试官现场验证):

from torch_geometric.data import Data

x = torch.randn(4, 8)
edge_index = torch.tensor([[0,1,2,3],[1,2,3,0]], dtype=torch.long)
data = Data(x=x, edge_index=edge_index)

conv = GATv2Conv(8, 16, heads=2, concat=True)
out = conv(data.x, data.edge_index)
print(out.shape)  # torch.Size([4, 32])

面试加分话术:

  1. “我显式传了 size 参数,支持二分图场景,例如推荐系统 user→item 二部图。”
  2. “scatter 阶段用的是 PyG 内置 softmax,底层调用 CUDA kernel,比手写 CPU 循环快两个数量级。”
  3. “训练 2000 万节点、5 亿边的大规模图时,我通过 torch.cuda.amp 自动混合精度 + 梯度检查点,把显存从 32 G 压到 12 G,单卡 A100 即可跑通。”

拓展思考

  1. 分布式训练:当图大到单机存不下,可用 PyG 2.4 的 torch_geometric.distributed 接口,把 edge_index 按 METIS 切分,重写 message 时通过 dist_neighbor_loader 拉取远程邻居特征,注意缓存一致性。
  2. 异构图:继承 HeteroConv,为每种边类型注册一个 GATv2Conv 子模块,在 message 里用 edge_type 查表映射参数,保证不同类型语义隔离。
  3. 动态图:时序场景下 edge_index 每步变化,可在 forward 里先 coalesce 去重,再用 time_encoding 把绝对时间戳拼到 x_j,实现 T-GNN。
  4. 生产部署:用 torch.jit.script 导出时,必须把 aggr='add' 写死,禁用 Python dict 动态属性;若端侧跑在 LibTorch,可把 scatter 替换为 torch.sparse 算子,避免链接 torch_scatter 动态库。