Ascend-SACT/MPNNModel
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

MPNNModel

MPNN(Message Passing Neural Network,消息传递神经网络)用于分子图的图性质预测。模型通过多轮消息传递更新节点表示,结合边特征计算逐边消息,经 Set2Set 读出层聚合为图级表示,最终通过 MLP 输出预测值。与 LCNN 不同,MPNN 同时包含节点表示和边表示。


1. 模型分析

1.1 模型架构

阶段模块说明
输入特征化MolGraphConvFeaturizer将 SMILES 分子转为 DGLGraph,节点特征 30 维,边特征 11 维
节点投影Linear + ReLU将节点特征投影到 node_out_feats 维
消息传递NNConv (u_mul_e + sum) + GRU多轮消息传递,NNConv 用边特征加权源节点特征,GRU 更新隐状态
图读出Set2Set (LSTM + segment_softmax + sum_nodes)迭代式注意力池化,生成图级表示
输出Linear + ReLU + Linear全连接层输出预测值

1.2 模型规格

项目规格
任务类型分子性质预测(回归/分类)
框架依赖DeepChem + dgl-ascend + dgllife + torch_npu
图结构特点节点表示 + 边表示
默认 batch_size隐式由 TorchModel 控制
默认 learning_rate0.0005
精度参考MAE < 0.5(回归, 400 epoch);roc_auc >= 0.80(分类, 200 epoch)
数据集bace(分类)/ delaney(回归),20 样本 overfit 测试
运行设备Atlas 800T A2(单卡 NPU)

2. 快速开始

本章节为快速部署指引,详细参数见 §3 准备运行环境 与 §4 运行指导。

2.1 模型与代码路径

路径用途
/home/dgl-ascenddgl-ascend 源码与编译目录
/deepchem-ascenddeepchem-ascend 源码目录
deepchem/models/tests/test_mpnn.py端到端 NPU 测试脚本

2.2 部署步骤(概览)

  1. 拉取并启动镜像(见 §3.3 / §3.4)
  2. 容器内编译安装 dgl-ascend(见 §4.1)
  3. 安装 deepchem-ascend 二进制包与 dgllife(见 §4.2)
  4. 运行 test_mpnn.py(见 §4.3 / §4.4)

3. 准备运行环境

3.1 软件环境

组件版本
Python3.11.15
PyTorch2.7.1+cpu
torch_npu2.7.1.post4
CANN9.0.0
dgl-ascend2.5
deepchem-ascend0.0.8
dgllife0.3.2

3.2 硬件环境

设备型号NPU 配置
Atlas 800T A2单卡

3.3 准备镜像

镜像环境镜像地址
公网swr.cn-south-1.myhuaweicloud.com/ascendhub/torch-npu:2.7.1.post4-910b-openeuler24.03-py3.11

3.4 启动镜像

IMAGE_ID=swr.cn-south-1.myhuaweicloud.com/ascendhub/torch-npu:2.7.1.post4-910b-openeuler24.03-py3.11
CONTAINER_NAME=mpnnmodel
docker run -u root --privileged \
 --name ${CONTAINER_NAME} \
 --device /dev/davinci0 \
 --device /dev/davinci_manager \
 --device /dev/devmm_svm \
 --device /dev/hisi_hdc \
 -v /usr/local/dcmi:/usr/local/dcmi \
 -v /usr/local/bin/npu-smi:/usr/local/bin/npu-smi \
 -v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
 -v /etc/ascend_install.info:/etc/ascend_install.info \
 -itd ${IMAGE_ID} /bin/bash

4. 运行指导

4.1 安装 DGL

# 必须使用`--recursive` 参数,以确保拉取所有子模块依赖
cd /home
git clone --recursive https://github.com/BUPT-GAMMA/dgl-ascend.git

# 解决编译问题
yum install gcc-gfortran
ln -s /usr/lib64/libgfortran.so.5 /usr/lib64/libgfortran.so
ln -s /usr/lib64/libgomp.so.1 /usr/lib64/libgomp.so
pip install pydantic transformers -i https://mirrors.aliyun.com/pypi/simple/


# 进入脚本目录
cd dgl-ascend/script/

# 执行编译脚本
bash build_dgl_ascend.sh

# 返回上一级,进入 python 目录
cd ../python/

# 使用开发者模式安装
pip install -e . -i https://mirrors.aliyun.com/pypi/simple/

4.2 迁移适配

#安装 DeepChem
pip install deepchem-ascend==0.0.8 -i https://mirrors.aliyun.com/pypi/simple/

#安装 PyTorch Geometric
pip install torch_geometric==2.7.0 --no-deps -i https://mirrors.aliyun.com/pypi/simple/

#安装 PYG 运行时依赖
pip install xxhash h5py -i https://mirrors.aliyun.com/pypi/simple/

#下载模型源码
git clone --branch develop https://gitcode.com/AI4Science/deepchem-ascend.git

# 安装 dgllife
pip install dgllife==0.3.2 -i https://mirrors.aliyun.com/pypi/simple/

4.3 测试示例

cd /deepchem-ascend
python -m pytest deepchem/models/tests/test_mpnn.py -v

4.4 运行测试代码

python -m pytest deepchem/models/tests/test_mpnn.py -v

5. 实现细节

5.1 关键适配步骤

步骤问题描述修改代码路径
1. dgl-ascend 源码编译旧版 libdgl.so 不含 SDDMM/SPMM Ascend 内核,NNConv 反向报 Operator SDDMM does not support ascend device打 PR #13/#16/#17/#18 patch 后执行 build_dgl_ascend.sh
2. 测试后端 NPU 支持tests/backend 的 _context_dict 只支持 cpu/gpu,DGLTESTDEV=npu 触发 KeyErrortests/backend/__init__.py + tests/backend/pytorch/__init__.py
3. rdkit 导入顺序修复torch_npu._C 与 rdkit.Chem C 扩展 ABI 冲突,import dgllife 时 segfault/deepchem-ascend/conftest.py(新建)
4. NNConv 前向算子替换Ascend SpMM 内核不支持 op="mul",走 CPU fallbackpython/dgl/_sparse_ops.py(新增 _npu_gspmm_binary + _gspmm NPU 拦截分支)
5. GRU 反向算子替换nn.GRU 反向触发 DynamicGRUV2,NPU 不支持deepchem/models/torch_models/mpnn.py(新增 GRUCellAdapter + monkey-patch)
6. segment_reduce stream 修复segment_reduce("max") NPU 内核崩溃src/array/ascend/segment_reduce.cc(PR #18)
7. PyTorch/DGL stream 同步DGL ACL stream 与 PyTorch NPU stream 解耦,多 epoch 训练后 vector core exceptionpython/dgl/_sparse_ops.py + python/dgl/heterograph.py + python/dgl/_ffi/streams.py(PR #13)

5.2 适配要点


修改点 1:测试后端无 NPU 设备选项

问题描述

tests/backend/__init__.py 的 _context_dict 只支持 {"cpu", "gpu"},设置 DGLTESTDEV=npu 会触发 KeyError。F.ctx() 和 F.randn() 无法返回 NPU 设备,导致所有 import backend as F 的 DGL 测试无法在 NPU 上运行。

修改方案

在 tests/backend/pytorch/__init__.py 新增 npu() 函数返回 th.device("npu:0") 和 is_npu_available() 检查函数;在 tests/backend/__init__.py 中用 hasattr(mod, "npu") 条件添加 "npu" 到 _context_dict,仅当 per-framework backend 定义了 npu() 时生效,不影响 mxnet/tensorflow backend。

修改代码

文件:/home/dgl-ascend/tests/backend/pytorch/__init__.py

def npu():
    return th.device("npu:0")


def is_npu_available():
    return hasattr(th, "npu") and th.npu.is_available()

文件:/home/dgl-ascend/tests/backend/__init__.py

_context_dict = {
    "cpu": cpu(),
    "gpu": cuda(),
}
if hasattr(mod, "npu"):
    _context_dict["npu"] = mod.npu()
_default_context = _context_dict[_default_context_str]

修改点 2:rdkit + torch_npu 导入顺序冲突

问题描述

torch_npu._C 与 rdkit.Chem 的 C 扩展存在 ABI 冲突。若 torch_npu 先于 rdkit.Chem 加载,import dgllife(内部触发 from rdkit import Chem)时会 segfault。test_mpnn.py 的导入链为 import deepchem → import torch(自动加载 torch_npu)→ import dgllife → import rdkit.Chem,正好命中此冲突顺序。

修改方案

在 /deepchem-ascend/conftest.py 中预加载 from rdkit import Chem,使其在 pytest 收集阶段(早于 torch_npu 加载)完成 C 扩展初始化。导入顺序变为 rdkit → torch_npu(安全方向,无 ABI 冲突)。

修改代码

文件:/deepchem-ascend/conftest.py(新建)

"""Pytest conftest for NPU environment.

Preloads rdkit.Chem before torch_npu to avoid a C extension ABI conflict
that causes a segfault when torch_npu is imported before rdkit.Chem.
The order rdkit -> torch_npu is safe; the reverse crashes.
"""
try:
    from rdkit import Chem  # noqa: F401
except ImportError:
    pass

修改点 3:NNConv 前向 u_mul_e+sum 走 CPU fallback

问题描述

NNConv 的核心计算 graph.update_all(fn.u_mul_e("h","w","m"), fn.sum("m","neigh")) 调度到 SpMMCsr<kDGLAscend>(op="mul", reduce="sum")。Ascend SpMM 内核仅支持 op="copy_lhs",op="mul" 会走 CPU fallback 路径(D2H 拷贝 → CPU 计算 → H2D 拷贝),非 NPU 原生计算,严重影响性能。

修改方案

在 _gspmm(_sparse_ops.py)算子层,当设备为 NPU 且 op in ("mul","add") 且 reduce_op=="sum" 时,调用新增的 _npu_gspmm_binary 函数替代 _CAPI_DGLKernelSpMM。将融合 SpMM 分解为三个 NPU 原生算子组合:CPU 图副本 find_edges + get_csr_shuffle_order 获取 CSC 排序边索引;PyTorch index_select + elementwise mul/add 计算逐边消息;torch.npu.synchronize() + F.segment_reduce("sum") 按 dst 归约。CPU/GPU 路径完全不受影响。

修改代码

文件:/home/dgl-ascend/python/dgl/_sparse_ops.py

def _npu_gspmm_binary(gidx, op, reduce_op, u, e, v_shp, ctx, dtype):
    import torch as th
    num_edges = gidx.num_edges(0)
    _, dsttype = gidx.metagraph.find_edge(0)
    num_dst = gidx.num_nodes(dsttype)

    from ._ffi.runtime_ctypes import DGLContext
    cpu_gidx = gidx.copy_to(DGLContext(1, 0))
    eid_cpu = th.arange(num_edges, dtype=th.int64)
    src_eid, dst_eid, _ = cpu_gidx.find_edges(0, eid_cpu)
    _, csc_order_idx = cpu_gidx.get_csr_shuffle_order(0)
    csc_order = csc_order_idx.tousertensor().to(ctx)
    src_eid = src_eid.to(ctx)
    dst_eid = dst_eid.to(ctx)

    u_gathered = u[src_eid[csc_order]]
    e_sorted = e[csc_order]

    if op == "mul":
        msg = u_gathered * e_sorted
    else:
        msg = u_gathered + e_sorted

    msg_flat = msg.reshape(num_edges, -1)

    seglen = th.zeros(num_dst, device=ctx, dtype=th.int64)
    seglen.scatter_add_(
        0, dst_eid[csc_order].long(),
        th.ones(num_edges, device=ctx, dtype=th.int64)
    )
    offsets = th.cumsum(
        th.cat([th.zeros(1, device=ctx, dtype=seglen.dtype), seglen]), 0
    )

    try:
        th.npu.synchronize()
    except Exception:
        pass

    rst = F.segment_reduce(reduce_op, msg_flat, offsets)
    rst = rst.reshape(v_shp)
    return rst, (None, None)

在 _gspmm 中添加 NPU 拦截分支:

    _is_npu = hasattr(F, "device_type") and F.device_type(ctx) == "npu"
    if (
        _is_npu
        and op in ("mul", "add")
        and reduce_op == "sum"
        and use_u
        and use_e
        and gidx.num_edges(0) > 0
    ):
        v, (arg_u, arg_e) = _npu_gspmm_binary(
            gidx, op, reduce_op, u, e, v_shp, ctx, dtype
        )
        if (expand_u or not use_u) and (expand_e or not use_e):
            v = F.squeeze(v, -1)
        return v, (arg_u, arg_e)

修改点 4:NNConv 反向 SDDMM 不支持 Ascend 设备

问题描述

NNConv 的 backward() 调用 gsddmm(g_rev, "mul"/"dot", ...) → _CAPI_DGLKernelSDDMM → SDDMM() → ATEN_XPU_SWITCH_CUDA_ASCEND。build/libdgl.so 旧版(PR #16 合入前编译)的宏走 fallback 分段(不含 kDGLAscend case),报 Operator SDDMM does not support ascend device。

修改方案

执行 bash script/build_dgl_ascend.sh -c 重新编译 dgl,使 build/libdgl.so 包含 PR #16 合入的 SDDMM Ascend 内核(SDDMMCoo<kDGLAscend,12,...> + SDDMMCsr<kDGLAscend,12,...>,共 26 个符号)。PR #18 额外将 array.cc 中 CSRSDDMM/COOSDDMM 的 ATEN_XPU_SWITCH_CUDA 改为 ATEN_XPU_SWITCH_CUDA_ASCEND,使 SDDMM dispatch 支持 Ascend。

修改代码

文件:/home/dgl-ascend/src/array/array.cc(PR #18)

void CSRSDDMM(...) {
  // was: ATEN_XPU_SWITCH_CUDA
  ATEN_XPU_SWITCH_CUDA_ASCEND(csr.indptr->ctx.device_type, XPU, "SDDMM", {
    ...
  });
}

void COOSDDMM(...) {
  // was: ATEN_XPU_SWITCH_CUDA
  ATEN_XPU_SWITCH_CUDA_ASCEND(coo.row->ctx.device_type, XPU, "SDDMM", {
    ...
  });
}

修改点 5:nn.GRU 反向 DynamicGRUV2 算子不支持

问题描述

MPNNGNN 内部使用 nn.GRU(dgllife/model/gnn/mpnn.py:58)在消息传递步骤间更新节点隐状态。nn.GRU 前向在 NPU 上正常,但反向传播触发 torch_npu 的 DynamicGRUV2 算子,报 Optype [DynamicGRUV2] of Ops kernel [AIcoreEngine] is unsupported。这是 torch_npu 的算子缺失。

修改方案

用 nn.GRUCell(通过 GRUCellAdapter 包装)替换 nn.GRU。nn.GRUCell 与 nn.GRU 单层单步数学完全等价(CPU 验证 diff=0.0),且不触发 DynamicGRUV2(使用不同 C++ 后端)。GRUCellAdapter 包装 nn.GRUCell 使其接口与 nn.GRU 兼容(接受 (1,N,H) 输入,返回 (out, hidden) 二元组)。在 MPNNModel.__init__ 中 super().__init__ 之后 monkey-patch self.model.model.gnn.gru,不改 dgllife 源码。

修改代码

文件:/deepchem-ascend/deepchem/models/torch_models/mpnn.py

class GRUCellAdapter(nn.Module):
    """Adapter wrapping nn.GRUCell to match nn.GRU's call interface.

    nn.GRU backward triggers DynamicGRUV2 which is unsupported on Ascend NPU.
    nn.GRUCell uses a different C++ backend and does not trigger it.
    This adapter makes GRUCell accept (1, N, H) input and return (out, hidden),
    matching how MPNNGNN.forward calls self.gru(input.unsqueeze(0), hidden).
    """

    def __init__(self, input_size, hidden_size):
        super(GRUCellAdapter, self).__init__()
        self.cell = nn.GRUCell(input_size, hidden_size)

    def reset_parameters(self):
        self.cell.reset_parameters()

    def forward(self, input, hidden):
        out = self.cell(input.squeeze(0), hidden.squeeze(0))
        return out.unsqueeze(0), out.unsqueeze(0)

在 MPNNModel.__init__ 中(super().__init__ 之后)monkey-patch:

        self.model.model.gnn.gru = GRUCellAdapter(
            node_out_feats, node_out_feats).to(self.device)

修改点 6:segment_reduce("max") NPU 内核崩溃

问题描述

Set2Set 的 segment_softmax 调用 segment_reduce(seglen, value, reducer="max"),Ascend 的 segment_reduce_max_kernel 触发 vector core exception。根因是 DGL-Ascend 的 segment_reduce 使用自定义 stream(segment_reduce_stream),与 PyTorch NPU default stream 解耦,导致 offsets/tiling 数据竞争。

修改方案

合入 PR #18 的 C++ 层修复:segment_reduce.cc 删除自定义 segment_reduce_stream,改用 default stream(nullptr);aclrtMemcpyAsync + aclrtSynchronizeStream 改为同步 aclrtMemcpy;入口加 aclrtSynchronizeDevice()。

修改代码

文件:/home/dgl-ascend/src/array/ascend/segment_reduce.cc

void SegmentReduceAscend(...) {
#ifdef DGL_USE_ASCEND
  DGLContext ctx = feat->ctx;
  ASCEND_CALL(aclrtSynchronizeDevice());  // Ensure PyTorch NPU ops complete
  ASCEND_CALL(aclrtSetDevice(ctx.device_id));
  ...
  // was: static aclrtStream segment_reduce_stream = nullptr; (singleton)
  aclrtStream stream = nullptr;
  ...

BuildSegmentSplit 和 LaunchSegmentReduceKernel 中:

  // was: ASCEND_CALL(aclrtMemcpyAsync(..., stream));
  //       ASCEND_CALL(aclrtSynchronizeStream(stream));
  ASCEND_CALL(aclrtMemcpy(..., ACL_MEMCPY_DEVICE_TO_HOST));

修改点 7:PyTorch/DGL stream 数据竞争

问题描述

DGL-Ascend 运行 C++ 内核在 default ACL stream(nullptr),与 PyTorch NPU stream 解耦。_segment_reduce 调用 _CAPI_DGLKernelSegmentReduce(DGL stream)时,输入 feat/offsets 由前序 PyTorch NPU 操作产生(PyTorch stream),两 stream 间无同步,连续多 epoch 训练后触发 vector core exception。图结构查询(in_degrees、edges 等)也有同样问题。

修改方案

合入 PR #13 的 Python 层 stream 同步修复:_sparse_ops.py 的 _segment_reduce 前加 torch.npu.synchronize();heterograph.py 新增 _sync_npu() helper 用于图结构查询前后同步 + to() 中 record_stream;streams.py 支持 torch.npu.Stream;core.py 修复 int64 比较。

修改代码

文件:/home/dgl-ascend/python/dgl/_sparse_ops.py

    arg_nd = to_dgl_nd_for_write(arg)
    try:
        import torch
        torch.npu.synchronize()
    except Exception:
        pass
    _CAPI_DGLKernelSegmentReduce(
        op,
        to_dgl_nd(feat),
        to_dgl_nd(offsets),
        to_dgl_nd_for_write(out),
        arg_nd,
    )

文件:/home/dgl-ascend/python/dgl/heterograph.py

    def _sync_npu(self):
        if F.device_type(self.device) == "npu":
            try:
                import torch
                torch.npu.synchronize()
            except Exception:
                pass

    def to(self, device, **kwargs):
        ...
        if F.device_type(ret.device) == "npu":
            try:
                import torch
                cur_stream = torch.npu.current_stream()
                ret.record_stream(cur_stream)
            except Exception:
                pass
        return ret

文件:/home/dgl-ascend/python/dgl/_ffi/streams.py

def to_dgl_stream_handle(cuda_stream):
    raw = getattr(cuda_stream, "npu_stream", None)
    if raw is None:
        raw = cuda_stream.cuda_stream
    return ctypes.c_void_p(raw)

6. 测试结果

6.1 测试环境

  • 设备:Atlas 800T A2(单卡)
  • 镜像:torch-npu:2.7.1.post4-910b-openeuler24.03-py3.11
  • 数据集:bace(分类)/ delaney(回归),20 样本 overfit 测试

6.2 精度结果

测试项任务验收标准实际精度训练轮次结果
test_mpnn_regression回归MAE < 0.5MAE = 0.008621400 epochPASS
test_mpnn_classification分类ROC-AUC >= 0.80ROC-AUC = 1.000000200 epochPASS
test_mpnn_reload模型重载原始预测 == 重载预测完全一致200 epochPASS

6.3 性能结果

测试项训练轮次总耗时每 epoch 耗时
Regression400 epoch106.6s0.266s/epoch
Classification200 epoch104.1s0.521s/epoch
Reload200 epoch62.0s0.310s/epoch

7. FAQ

Q1:编译 dgl-ascend 报 libgfortran.so / libgomp.so 找不到? A:镜像内仅提供 .so.5 / .so.1 版本,需手动建立软链:

yum install gcc-gfortran
ln -s /usr/lib64/libgfortran.so.5 /usr/lib64/libgfortran.so
ln -s /usr/lib64/libgomp.so.1 /usr/lib64/libgomp.so

Q2:import dgllife 时 segfault? A:torch_npu._C 与 rdkit.Chem 的 C 扩展 ABI 冲突。需在 conftest.py 中预加载 from rdkit import Chem,确保 rdkit 先于 torch_npu 加载。

Q3:NNConv 前向报 SpMMCsrAscend only supports copy_lhs? A:Ascend SpMM 内核不支持 op="mul"。修改点 3 的 _npu_gspmm_binary 算子替换方案已解决此问题,确保 NPU 原生计算。

Q4:NNConv 反向报 Operator SDDMM does not support ascend device? A:build/libdgl.so 旧版不含 SDDMM Ascend 内核。需打上 PR #16 patch 后重新编译 bash script/build_dgl_ascend.sh -c。

Q5:nn.GRU 反向报 DynamicGRUV2 ... unsupported? A:torch_npu 的 DynamicGRUV2 反向算子未注册。修改点 5 用 GRUCellAdapter(包装 nn.GRUCell)替换 nn.GRU,全部 NPU 原生支持。

Q6:segment_reduce("max") 崩溃或 BackwardSegmentCmp does not support ascend device? A:PR #18 修复了 segment_reduce 的 stream 管理(default stream + 同步拷贝),修改点 6 补充了 BackwardSegmentCmp 的 CPU fallback。两者均需重新编译。

Q7:多 epoch 训练时 vector core exception? A:PR #13 的 _sync_npu() 和 _segment_reduce 前的 torch.npu.synchronize() 解决了 PyTorch/DGL stream 间的数据竞争。