MPNN(Message Passing Neural Network,消息传递神经网络)用于分子图的图性质预测。模型通过多轮消息传递更新节点表示,结合边特征计算逐边消息,经 Set2Set 读出层聚合为图级表示,最终通过 MLP 输出预测值。与 LCNN 不同,MPNN 同时包含节点表示和边表示。
| 阶段 | 模块 | 说明 |
|---|---|---|
| 输入特征化 | 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 | 全连接层输出预测值 |
| 项目 | 规格 |
|---|---|
| 任务类型 | 分子性质预测(回归/分类) |
| 框架依赖 | DeepChem + dgl-ascend + dgllife + torch_npu |
| 图结构特点 | 节点表示 + 边表示 |
| 默认 batch_size | 隐式由 TorchModel 控制 |
| 默认 learning_rate | 0.0005 |
| 精度参考 | MAE < 0.5(回归, 400 epoch);roc_auc >= 0.80(分类, 200 epoch) |
| 数据集 | bace(分类)/ delaney(回归),20 样本 overfit 测试 |
| 运行设备 | Atlas 800T A2(单卡 NPU) |
本章节为快速部署指引,详细参数见 §3 准备运行环境 与 §4 运行指导。
| 路径 | 用途 |
|---|---|
/home/dgl-ascend | dgl-ascend 源码与编译目录 |
/deepchem-ascend | deepchem-ascend 源码目录 |
deepchem/models/tests/test_mpnn.py | 端到端 NPU 测试脚本 |
test_mpnn.py(见 §4.3 / §4.4)| 组件 | 版本 |
|---|---|
| Python | 3.11.15 |
| PyTorch | 2.7.1+cpu |
| torch_npu | 2.7.1.post4 |
| CANN | 9.0.0 |
| dgl-ascend | 2.5 |
| deepchem-ascend | 0.0.8 |
| dgllife | 0.3.2 |
| 设备型号 | NPU 配置 |
|---|---|
| Atlas 800T A2 | 单卡 |
| 镜像环境 | 镜像地址 |
|---|---|
| 公网 | swr.cn-south-1.myhuaweicloud.com/ascendhub/torch-npu:2.7.1.post4-910b-openeuler24.03-py3.11 |
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# 必须使用`--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/#安装 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/cd /deepchem-ascend
python -m pytest deepchem/models/tests/test_mpnn.py -vpython -m pytest deepchem/models/tests/test_mpnn.py -v| 步骤 | 问题描述 | 修改代码路径 |
|---|---|---|
| 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 触发 KeyError | tests/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 fallback | python/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 exception | python/dgl/_sparse_ops.py + python/dgl/heterograph.py + python/dgl/_ffi/streams.py(PR #13) |
问题描述
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]问题描述
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:
passu_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)问题描述
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", {
...
});
}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)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));问题描述
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)torch-npu:2.7.1.post4-910b-openeuler24.03-py3.11| 测试项 | 任务 | 验收标准 | 实际精度 | 训练轮次 | 结果 |
|---|---|---|---|---|---|
| test_mpnn_regression | 回归 | MAE < 0.5 | MAE = 0.008621 | 400 epoch | PASS |
| test_mpnn_classification | 分类 | ROC-AUC >= 0.80 | ROC-AUC = 1.000000 | 200 epoch | PASS |
| test_mpnn_reload | 模型重载 | 原始预测 == 重载预测 | 完全一致 | 200 epoch | PASS |
| 测试项 | 训练轮次 | 总耗时 | 每 epoch 耗时 |
|---|---|---|---|
| Regression | 400 epoch | 106.6s | 0.266s/epoch |
| Classification | 200 epoch | 104.1s | 0.521s/epoch |
| Reload | 200 epoch | 62.0s | 0.310s/epoch |
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.soQ2: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 间的数据竞争。