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

FerminetModel模型NPU推理迁移指南

FerminetModel(Fermionic Neural Network,费米子神经网络)是一种基于深度学习的变分蒙特卡洛(VMC)方法,用于求解多电子体系的 ab-initio 基态能量。模型以 Hartree-Fock(HF)解为基线,通过 MCMC 随机游走采样电子坐标,用神经网络(含 Jastrow 型包络函数与多行列式展开)拟合波函数 ψ 的模方,仅需输入原子核坐标即可运行。本指南覆盖 FerminetModel 在 Atlas 800T A2 NPU 上的推理(前向计算)迁移验证。


1.快速开始

1.1 软件环境

组件版本
Python3.12.13
PyTorch2.10.0+cpu
torch_npu2.10.0.post2
CANN9.0.1
DeepChemdeepchem-ascend 0.0.8(源码安装,PyTorch 后端)
pyscf2.14.0
rdkit随 deepchem 依赖安装

1.2 硬件环境

设备型号NPU 配置
Atlas 800T A2(910B3)单卡即可(验证环境为 8 卡,测试仅使用单卡)

1.3 准备镜像

quay.m.daocloud.io/ascend/vllm-ascend:nightly-releases-v0.25.1rc

1.4 启动镜像

IMAGE_ID=<镜像地址>
CONTAINER_NAME=ferminet
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

1.5 部署步骤(概览)

  1. 拉取并启动镜像
  2. 在容器内获取 deepchem-ascend 源码并安装依赖(参见 §3.1)
  3. 运行 test_ferminet_npu_infer.py(参见 §3.2)

注:devlop 分支的 Ferminet 源码已完成 NPU 推理适配,测试文件无需再做任何源码修改即可运行。若使用已发布的 deepchem-ascend==0.0.8 二进制包,需按 §3.2 应用 1 处源码补丁。

2. 模型分析

2.1 模型架构(推理路径)

阶段模块说明
输入采样ElectronSamplerMCMC 随机游走采样电子坐标(gauss_initialize_position 高斯初始化),输出 (batch_no, 电子数×3) 的 numpy 坐标
HF 基线pyscf.scf.UHF(sto-6g)prepare_hf_solution 求解 Hartree-Fock;evaluate_hf 在采样点评估上/下自旋分子轨道值(numpy/CPU 域)
特征构建Ferminet.forwardone-electron 特征(电子-核向量 + 距离)与 two-electron 特征(电子-电子向量 + 距离),eps 防零距离
特征交互FerminetElectronFeaturen_one/n_two 线性层堆叠,tanh 激活,自旋均值作为全局特征拼接,残差 + 投影连接
波函数输出FerminetEnvelopeenvelope_w/g/sigma/pi 参数,determinant 个行列式,ψ = Σ wdet_k·det(ψ↑)·det(ψ↓)

2.2 模型规格

项目规格
任务类型分子波函数前向推理(VMC 模型)
框架依赖DeepChem(PyTorch 后端)+ torch_npu + pyscf + rdkit
默认 n_one[256, 256, 256, 256]
默认 n_two[32, 32, 32, 32]
默认 determinant16
默认 batch_no8
精度参考前向输出 shape (batch_no,);初始化电子数/自旋校验正确
运行设备Atlas 800T A2(910B3,单卡 NPU)

2.3 模型与代码路径

路径用途
deepchem-ascend(本仓库,dev_ferminet 分支)deepchem-ascend 源码目录,已包含 Ferminet NPU 适配
deepchem/models/torch_models/ferminet.py模型实现
deepchem/models/torch_models/layers.pyFerminetElectronFeature/FerminetEnvelope 层
deepchem/models/tests/test_ferminet_npu_infer.py端到端 NPU 推理测试(pytest)
conftest.py(仓库根目录)NPU 环境下 rdkit 预加载,规避 import 段错误(详见 §7 Q1)

3. 运行指导

3.1 获取源码与安装依赖

# 获取源码(含 Ferminet NPU 适配,当前模型已合入devlop分支)
git clone https://gitcode.com/AI4Science/deepchem-ascend.git
cd deepchem-ascend
git checkout devlop

# 安装源码及其依赖(PyTorch 后端,不装 TensorFlow)
pip install -e . -i https://mirrors.aliyun.com/pypi/simple/

# 安装 pyscf(Ferminet 初始化的 HF 基线硬依赖)
pip install pyscf -i https://mirrors.aliyun.com/pypi/simple/

注意:deepchem-ascend 源码自带根目录 conftest.py,pytest 运行时会先于 torch_npu 预加载 rdkit.Chem,规避 C 扩展 ABI 冲突导致的段错误(详见 §7 Q1)。请勿脱离仓库根目录单独运行测试脚本,或自行保证 from rdkit import Chem 先于 import torch_npu 执行。

3.2 迁移适配

devlop 分支已完成 NPU 适配。FerminetModel 支持 device 参数(缺省时 _get_device() 自动选择 NPU/CUDA/MPS/CPU),测试脚本无需显式传参。若使用 deepchem-ascend==0.0.8 二进制包,推理路径需应用以下 1 处源码补丁:

补丁:FerminetEnvelope 波函数累加张量的设备放置(layers.py,FerminetEnvelope.forward)

ψ 以零张量初始化,原实现固定在 CPU,与 NPU 上的行列式计算结果相加时报设备不匹配:

# 修改前
psi = torch.zeros(self.batch_size)
# 修改后
psi = torch.zeros(self.batch_size, device=one_electron.device)

注:devlop 分支源码中另包含训练路径相关适配(损失函数设备放置、linalg.norm 等价替换、采样坐标 float32 转换、防零 eps 调整),与推理无关,本指南不展开。

测试文件侧的修改(2 处,最小修改):

  1. 文件头部增加 import torch_npu 与 NPU 可用性跳过保护(pytestmark);
  2. test_forward 中输入张量增加 .to(mol.device) 上设备。

3.3 测试示例

测试文件 deepchem/models/tests/test_ferminet_npu_infer.py 基于同目录下的 test_ferminet.py 适配,完整内容如下:

"""
Test for Ferminet Model on NPU.
"""

import pytest
import numpy as np
try:
    from deepchem.models.torch_models.ferminet import FerminetModel
    import torch
    import torch_npu
    # When pytest runs without pytorch in the environment (ex: as in tensorflow workflow),
    # the above import raises a ModuleNotFoundError. It is safe to ignore it
    # since the below tests only run in an environment with pytorch installed.
except ModuleNotFoundError:
    pass
from deepchem.models.torch_models.torch_model import is_npu_available

pytestmark = pytest.mark.skipif(not is_npu_available(), reason="NPU not available")


@pytest.mark.torch
def test_FerminetModel():
    # Test for the init function of FerminetModel class
    FH_molecule = [['F', [0, 0, 0]], ['H', [0, 0.5, 0.5]]]
    # Testing ionic initialization
    mol = FerminetModel(FH_molecule, spin=1, ion_charge=-1)
    assert (mol.electron_no == np.array([[10], [1]])).all()
    # Testing whether error throws up when spin is wrong
    with pytest.raises(ValueError):
        FerminetModel(FH_molecule, spin=0, ion_charge=-1)
    # Testing the spin values
    Li_atom = [['Li', [0, 0, 0]]]
    mol = FerminetModel(Li_atom, spin=1, ion_charge=0)
    assert mol.up_spin == 2 and mol.down_spin == 1


@pytest.mark.torch
def test_forward():
    FH_molecule = [['F', [0.424, 0.424, 0.23]], ['H', [0.4, 0.5, 0.5]]]
    # Testing ionic initialization
    mol = FerminetModel(FH_molecule, spin=1, ion_charge=-1)
    result = mol.model.forward(torch.from_numpy(mol.molecule.x).to(mol.device))
    assert result.size() == torch.Size([8])


@pytest.mark.torch
def test_evaluate_hf_solution():
    # Test for the evaluate_hf_solution function of FerminetModel class
    H2_molecule = [['F', [0, 0, 0]], ['He', [0, 0, 0.748]]]
    mol = FerminetModel(H2_molecule, spin=1, ion_charge=0)
    electron_coordinates = np.random.rand(10, 11, 3)
    spin_up_orbitals, spin_down_orbitals = mol.evaluate_hf(electron_coordinates)
    # The solution should be of the shape (number of electrons, number of electrons)
    assert np.shape(spin_up_orbitals) == (10, 6, 6)
    assert np.shape(spin_down_orbitals) == (10, 5, 5)

3.4 运行测试代码

在仓库根目录执行:

pytest deepchem/models/tests/test_ferminet_npu_infer.py -v

预期输出:

deepchem/models/tests/test_ferminet_npu.py::test_FerminetModel PASSED    [ 33%]
deepchem/models/tests/test_ferminet_npu.py::test_forward PASSED          [ 66%]
deepchem/models/tests/test_ferminet_npu.py::test_evaluate_hf_solution PASSED [100%]
======================= 3 passed, 19 warnings in ~20s ========================

4. 实现细节

4.1 关键适配步骤

步骤说明
1. 获取源码使用 devlop 分支(或对 0.0.8 二进制包应用 §3.2 补丁)
2. 安装 pyscfpip install pyscf,模型初始化的硬依赖,缺失时抛 ImportError
3. 设备自动选择FerminetModel(device=None) 时 _get_device() 自动选择 NPU,无需显式传参
4. 输入上设备采样坐标为 numpy 数组,torch.from_numpy(x).to(model.device) 后即可前向
5. 测试级最小修改测试文件增加 torch_npu 导入与 NPU 可用性跳过保护

4.2 适配要点

  • 设备自动选择已内置:deepchem-ascend 源码的 FerminetModel/Ferminet 已支持 device 参数与 _get_device() 自动选择(CUDA 优先、其次 NPU),模型参数与原子核坐标张量自动放置到 NPU。
  • numpy 域计算不上 NPU:电子采样(MCMC)与 HF 求解(pyscf)在 numpy/CPU 域完成,仅神经网络前向运行在 NPU,NPU-CPU 数据交互为一次小张量拷贝(batch_no × 电子数 × 3)。
  • 前向算子均为 NPU 原生支持:前向路径使用的 cdist、det、exp/abs、matmul、sqrt/sum/pow、cat/reshape/permute、tanh/Linear 等算子在 NPU 上原生执行,无 CPU 回退。
  • rdkit 必须先于 torch_npu 导入:仓库根目录 conftest.py 已处理(§7 Q1)。

5. 测试结果

5.1 测试环境

  • 设备:Atlas 800T A2(910B3,单卡)
  • 软件:Python 3.12.13 / PyTorch 2.10.0+cpu / torch_npu 2.10.0.post2 / CANN 9.0.1 / pyscf 2.14.0
  • 数据集:测试内置的 FH⁻、Li、FH/He⁺ 小分子体系(pyscf UHF/sto-6g 基线)

5.2 测试结果

测试项内容验收标准结果
test_FerminetModel模型初始化(离子化电子数、自旋校验)电子数/自旋正确,非法自旋抛 ValueError通过
test_forwardNPU 前向推理输出 shape == (8,)通过
test_evaluate_hf_solutionHF 基线轨道评估上/下自旋轨道 shape (10, 6, 6)/(10, 5, 5)通过

6. 常见问题解答

Q1:python -c "import deepchem" 或独立脚本运行时段错误(Segmentation fault)?

A:torch_npu 先于 rdkit.Chem 导入时存在 C 扩展 ABI 冲突,导致进程崩溃。仓库根目录的 conftest.py 已在 pytest 会话开始时预加载 rdkit.Chem 规避此问题,因此请在仓库根目录下用 pytest 运行测试。独立脚本需自行保证 from rdkit import Chem 位于 import torch_npu 之前。

Q2:初始化即抛 ImportError: This module requires pySCF?

A:Ferminet 依赖 pyscf 求解 HF 基线。执行:

pip install pyscf -i https://mirrors.aliyun.com/pypi/simple/

Q3:报 RuntimeError: Expected all tensors to be on the same device. Expected NPU tensor?

A:源码中 CPU 张量与 NPU 张量混合运算。确认已应用 §4.2 补丁(FerminetEnvelope 的 psi 设备放置),或直接使用 devlop 分支;同时检查输入张量是否已 .to(model.device) 上设备。

Q4:torch.npu.is_available() 返回 False?

A:检查容器是否挂载 NPU 设备(--device /dev/davinci0 等)及驱动目录;在宿主机执行 npu-smi info 确认设备在线。另注意 import torch_npu 必须在 torch.npu.* 调用之前执行。