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

RAscore 昇腾适配与推理

RAscore (Retrosynthetic Accessibility Score) 是由 Reymond Group 发布的机器学习模型,用于预测分子的逆合成可达性——即计算机辅助合成规划工具能否为给定化合物找到合成路线。模型基于 AiZynthfinder 对 200,000 个 ChEMBL 化合物的逆合成分析结果训练而成,输出 [0, 1] 区间的概率得分,得分越高表示越容易合成。本仓库包含将 RAscore DNN 模型从 TensorFlow/NVIDIA GPU 适配至华为昇腾 NPU 的完整交付件。

适配路径

TensorFlow SavedModel (.tf)
    │
    ├── 路径 A: TF → PyTorch (.pt) → 昇腾 NPU 推理 (torch_npu)
    │
    └── 路径 B: TF → ONNX (.onnx) → OM (.om) → 昇腾 NPU 推理 (pyACL)

仓库结构

RAScore/
├── rascore_pytorch/                    # PyTorch 推理交付件
│   ├── inference/
│   │   ├── rascore_inference_pt.py     # 推理+性能基准测试脚本
│   │   └── infer.sh
│   ├── models/
│   │   └── rascore.pt                  # PyTorch 模型权重
│   ├── data/
│   │   └── uspto_chembl_classification_test.csv
│   └── output/
│
├── rascore_om/                         # OM 离线推理交付件
│   ├── inference/
│   │   ├── rascore_inference_om.py     # pyACL 推理脚本
│   │   └── infer.sh
│   ├── models/                         # OM 模型 (需 ATC 编译生成)
│   ├── data/
│   │   └── uspto_chembl_classification_test.csv
│   └── output/
│
├── conversion/                         # 模型转换脚本
│   ├── convert_tf_to_pt.py
│   ├── convert_to_onnx.py
│   └── onnx2om.sh
│
├── rascore_dnn.onnx                    # ONNX 模型 (opset=13)
├── a100_tf_baseline_chembl_classification_smi.csv  # TF 基线精度参考
├── requirements_inference.txt
│
└── patches/                            # 与原始 RAscore 代码的差异补丁
    ├── 0001-RAscore_NN-TF-to-PyTorch-rewrite.patch
    ├── 0002-command_line_interface-ascend-support.patch
    └── PATCHES_README.md

环境要求

项目要求
操作系统openEuler 24.03 LTS-SP2 (aarch64)
NPU华为昇腾 Ascend 910B3
CANN8.5.1
Python3.8 ~ 3.11 (推荐 3.11)
PyTorch2.9.0 + torch_npu 2.9.0
RDKitrdkit-pypi >= 2022.9.1
numpy>= 1.24, < 2.0
pandas>= 1.5
tqdm>= 4.60

完整依赖列表见 requirements_inference.txt。

注:acl 模块由 CANN SDK 提供,无法通过 pip 安装;torch_npu 需从昇腾仓库获取且版本须与 torch 严格一致。

适配其他昇腾 NPU 型号

本仓库以 Ascend 910B3 为目标平台。如需适配其他昇腾 NPU 型号,需修改以下内容:

  1. ATC 编译参数:修改 conversion/onnx2om.sh 中的 soc_version 参数(已支持通过第三个参数传入,如 bash onnx2om.sh rascore_dnn.onnx rascore Ascend310P3)
  2. CANN SDK 版本:不同 NPU 型号对应的 CANN 版本可能不同,需安装对应版本的 CANN SDK,同时更新 onnx2om.sh 中 ATC_BIN 的路径
  3. torch_npu 版本:不同 CANN 版本对应的 torch_npu 版本不同,须确保 torch 与 torch_npu 版本严格一致
  4. 重新编译 OM 模型:OM 模型与 SoC 版本绑定,更换 NPU 型号后必须重新执行 ATC 编译

Python 推理脚本无需修改,torch_npu 和 pyACL 推理代码与 NPU 型号无关。


一、适配部署

1.1 路径 A:TF → PyTorch → 昇腾 NPU (torch_npu)

步骤 1:权重转换 (TF → PyTorch)

脚本:conversion/convert_tf_to_pt.py

从 TF SavedModel 的 checkpoint 中逐层提取 kernel/bias 权重,转置后保存为 PyTorch state_dict 格式。DNN 层结构 [2048, 512, 512, 128, 512, 256, 128, 128, 128, 512, 512, 1] 硬编码在脚本中。

python conversion/convert_tf_to_pt.py \
    --tf_model <path/to/model.tf/variables/variables> \
    --pt_output rascore_pytorch/models/rascore.pt

关键差异:TF kernel shape (in, out) 需转置为 PyTorch Linear weight (out, in)。

步骤 2:推理脚本适配

脚本:rascore_pytorch/inference/rascore_inference_pt.py

将原始 RAscore_NN.py 中 TF/Keras 推理重写为 PyTorch + torch_npu,核心变更:

  • 推理引擎:keras.models.load_model() → torch.jit.load() + torch_npu
  • 设备:NVIDIA GPU → npu:0
  • 指纹 dtype:np.int32 → np.float32(整数转 FP32 无损)
  • 激活函数映射:linear→Identity, relu→ReLU, elu→ELU, selu→SELU

步骤 3:运行推理

cd rascore_pytorch/inference
bash infer.sh

或手动指定参数:

python rascore_inference_pt.py \
    --model ../models/rascore.pt \
    --dataset ../data/uspto_chembl_classification_test.csv \
    --output ../output/result.csv \
    --device 0

精度验证

以 TF 官方模型在 A100 上的推理结果为基线,对比昇腾 NPU 推理得分误差:

推理配置MAERMSEMax_AEPearson_R
A100 PyTorch FP329.49e-053.03e-045.03e-031.0
Ascend 910B PyTorch FP329.49e-053.03e-045.04e-031.0

TF→PyTorch 转换引入的 MAE ~1e-4,Max_AE ~5e-3,Pearson 相关系数为 1.0。跨硬件(A100 vs Ascend 910B)PyTorch 推理得分差异仅在 1e-8 量级,可忽略。


1.2 路径 B:TF → ONNX → OM → 昇腾 NPU (pyACL)

步骤 1:ONNX 转换 (TF → ONNX)

脚本:conversion/convert_to_onnx.py

使用 tf2onnx 将 TF SavedModel 转换为 ONNX 格式,opset=13(兼容 Ascend CANN ATC 编译器)。转换后自动清理多余 opset_import 条目(ATC 要求仅保留默认域)并验证模型规格。

python conversion/convert_to_onnx.py \
    --saved_model_dir <path/to/model.tf> \
    --output rascore_dnn.onnx

ONNX 模型规格:输入 input_1: [batch, 2048] FP32,输出 target: [batch, 1] FP32。

步骤 2:ATC 编译 (ONNX → OM)

脚本:conversion/onnx2om.sh

使用 Ascend ATC 编译器将 ONNX 模型编译为昇腾离线推理模型 (.om)。关键参数:--precision_mode=must_keep_origin_dtype 保持原始精度,--soc_version 指定目标芯片。

bash conversion/onnx2om.sh rascore_dnn.onnx rascore Ascend910B3
# 输出: rascore.om,放入 rascore_om/models/

步骤 3:运行推理

脚本:rascore_om/inference/rascore_inference_om.py

采用预分配内存与指纹加速优化的 pyACL 推理脚本(详见性能优化章节)。

cd rascore_om/inference
bash infer.sh

或手动指定参数:

python rascore_inference_om.py \
    --model ../models/rascore.om \
    --dataset ../data/uspto_chembl_classification_test.csv \
    --output ../output/result.csv \
    --device 0

脚本支持 --baseline 参数加载 A100 TF 基线结果自动进行精度对比,使用 --no_compare 跳过。

精度验证

推理配置MAERMSEMax_AEPearson_R
Ascend 910B OM FP167.15e-051.20e-041.52e-031.0
Ascend 910B OM FP329.49e-053.03e-045.04e-031.0

OM FP16 的 MAE 甚至低于 FP32(FP16 舍入方向统计抵消了转换系统偏差)。ONNX→OM 转换在 FP32 精度下无额外损失。

1.3 精度验证说明

以上精度验证以 NVIDIA A100 TensorFlow FP32 推理结果为基线,衡量的是推理得分与基线的数值偏差。RAscore 输出 [0, 1] 区间的概率得分,所有适配路径的 MAE < 1e-4、Pearson_R = 1.0,得分与基线高度一致。

RAscore 的原始设计中,得分用于指示 AiZynthfinder 能否找到合成路线。是否将得分二分为"可合成/不可合成",以及二分阈值的选取,需根据实际项目需求确定(原始论文未指定统一阈值)。

1.4 测试数据集

数据集样本数来源
uspto_chembl_classification_test19935RAscore 官方仓库 data.zip 中 ChEMBL 分类测试集
test.smi99RAscore 官方仓库附带的测试分子集

数据集来源于 reymond-group/RAscore。其中 uspto_chembl_classification_test 是论文中 200,000 个 ChEMBL 化合物经 AiZynthfinder 逆合成分析后的分类测试子集,用于训练和评估 RAscore 模型。


二、性能优化

OM 推理脚本 rascore_om/inference/rascore_inference_om.py 采用了以下优化措施:

2.1 预分配设备内存与元数据结构

问题:未优化时每帧推理都执行完整的 acl.rt.malloc() → memcpy → execute → memcpy → acl.rt.free() 流程,同时每帧创建/销毁 Dataset、DataBuffer 结构和 Host 端输出数组。在批量推理场景下,累积的设备内存分配/释放、元数据创建/销毁开销显著拉低吞吐量。

优化措施:初始化阶段一次性分配所有资源,推理循环内仅做数据拷贝和模型执行,结束时统一释放:

  • 预分配 input_buffer / output_buffer(acl.rt.malloc),推理时仅 memcpy
  • 预创建 input_dataset / output_dataset + DataBuffer,推理时直接复用
  • 预分配 Host 端 host_output_array(np.zeros),避免每帧 numpy 数组分配

收益:消除每帧 8 次设备内存操作(2×malloc + 2×free + 2×create_dataset + 2×create_data_buffer)和 Host 端数组重分配,推理循环仅保留 H2D memcpy → execute → D2H memcpy 三个核心操作。

2.2 指纹计算加速

问题:原始指纹计算使用 AllChem.GetMorganFingerprint 返回稀疏指纹,需 Python 逐元素 idx % size 取模 + 逐元素赋值填充数组,在 Python 层存在循环开销。

优化措施:

  • 替换为 rdMolDescriptors.GetHashedMorganFingerprint(mol, 3, nBits=2048, useFeatures=True):C++ 层直接完成 hash 折叠,输出长度固定的密集指纹,消除 Python 侧取模循环
  • 替换逐元素 Python 赋值为 np.put(arr, keys, values):vectorized numpy 操作,单次调用完成全部赋值

精度保证:输出与原始方法完全一致(np.allclose=True,0 差异),因 nBits=2048 与原始 idx % 2048 等价。

2.3 优化效果

以 19935 个分子的 uspto_chembl_classification_test 数据集在昇腾 910B3 上测试:

指纹计算方式内存策略avg/ms/molthroughput/mol/s
AllChem.GetMorganFingerprint + Python 逐元素赋值每帧 malloc/create/destroy~1.1~904
GetHashedMorganFingerprint + np.put预分配+复用~0.85~1176

优化后每分子平均推理时间从 ~1.1ms 降至 ~0.85ms,吞吐提升约 30%。其中指纹计算加速贡献了主要的单帧耗时下降,预分配优化消除了帧间的内存管理累积开销。


补丁说明

patches/ 目录包含与原始 RAscore 开源代码的差异补丁,用于追溯适配修改:

Patch修改内容
0001-RAscore_NN-TF-to-PyTorch-rewrite.patchRAscore_NN.py: TF/Keras → PyTorch/torch_npu 重写,新增 predict_batch(),指纹 dtype 改为 np.float32,设备改为 npu:0
0002-command_line_interface-ascend-support.patchcommand_line_interface.py: 新增 --device 参数,模型识别从 .h5 改为 .pt,默认设备 npu:0

应用方式见 patches/PATCHES_README.md。

原始项目

  • 官方仓库: https://github.com/reymond-group/RAscore