LNN(Lagrangian Neural Network,拉格朗日神经网络)是一种物理驱动的深度学习模型,通过学习动力系统的拉格朗日函数 L(q, q̇),利用 Euler-Lagrange 方程直接推导系统的运动方程。与传统直接预测导数的方法不同,LNN 学习标量值拉格朗日函数,并通过一阶/二阶自动微分计算加速度,从而保证动力学守恒性。
LNNModel 基于拉格朗日神经网络,主要计算流程如下:
| 阶段 | 模块 | 说明 |
|---|---|---|
| 输入编码 | MultilayerPerceptron | 将状态空间 [q, q̇](2×n_dof 维)映射为标量拉格朗日值 L(q, q̇) |
| 一阶微分 | jacrev + vmap | 对 L 求 Jacobian,得到 ∂L/∂q 和 ∂L/∂q̇ |
| 二阶微分 | jacrev(jacrev(...)) + vmap | 对 L 求 Hessian,得到 ∂²L/∂q̇²、∂²L/∂q̇∂q |
| Euler-Lagrange 求解 | torch.linalg.solve | 组装右端项,求解线性方程组得到加速度 q̈ |
| 项目 | 规格 |
|---|---|
| 任务类型 | 动力系统加速度预测(回归) |
| 框架依赖 | DeepChem + torch + torch_npu |
| 默认激活函数 | tanh |
| 默认 n_dof | 2(输入维度 4,输出维度 2) |
| 默认 batch_size | 100 |
| 默认 learning_rate | 0.001 |
| 精度参考 | MSE < 0.1(1000 epoch overfit 测试) |
| 运行设备 | Atlas 800T A2(单卡 NPU) |
| 路径 | 用途 |
|---|---|
deepchem/models/torch_models/lnn.py | LNN 模型实现(LNN + LNNModel) |
deepchem/models/torch_models/tests/test_lnn.py | NPU 测试脚本(6 个测试用例) |
deepchem/models/torch_models/tests/conftest.py | pytest 公共夹具(导入顺序修复) |
| 组件 | 版本 |
|---|---|
| Python | 3.11.15 |
| PyTorch | 2.7.1+cpu |
| torch_npu | 2.7.1.post4 |
| CANN | 9.0.0 |
| deepchem-ascend | 0.0.8 |
| rdkit | 2026.03.5 |
| 设备型号 | 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=lnnmodel
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/bashpip install deepchem-ascend==0.0.8 -i https://mirrors.aliyun.com/pypi/simple/
pip install torch_npu -i https://mirrors.aliyun.com/pypi/simple/直接安装 deepchem-ascend 二进制包,模型已含 NPU 适配代码:
pip install deepchem-ascend==0.0.8 -i https://mirrors.aliyun.com/pypi/simple/cd /deepchem-ascend
python -m pytest deepchem/models/torch_models/tests/test_lnn.py -vdeepchem/models/torch_models/tests/test_lnn.py::test_forward_eval PASSED
deepchem/models/torch_models/tests/test_lnn.py::test_calculate_dynamics_shape PASSED
deepchem/models/torch_models/tests/test_lnn.py::test_lagrangian PASSED
deepchem/models/torch_models/tests/test_lnn.py::test_lnnmodel_train_and_predict PASSED
deepchem/models/torch_models/tests/test_lnn.py::test_lnnmodel_restore PASSED
deepchem/models/torch_models/tests/test_lnn.py::test_lnnmodel_overfit PASSED
======================== 6 passed, 2 warnings in 21.84s ========================| 步骤 | 问题 | 修改文件 |
|---|---|---|
| 1. 前向模式 AD 替换 | jacfwd/hessian 在 NPU 上不支持 | lnn.py |
| 2. 非连续张量修复 | 切片产生非连续视图,NPU 算子报错 | lnn.py |
| 3. 线性方程组求解 | torch.linalg.solve 无 NPU 原生算子 | lnn.py |
| 4. 激活函数替换 | NPU softplus_backward 不支持广播 | lnn.py |
| 5. 公开方法设备迁移 | 输入张量未移到 NPU | lnn.py |
| 6. Save/Restore 一致性 | joblib 与 .pt checkpoint 机制不一致 | lnn.py |
| 7. NPU 导入与跳过检查 | 缺少 torch_npu 导入和 NPU 检查 | test_lnn.py |
| 8. 测试设备迁移 | 测试 1-3 模型和张量在 CPU 上 | test_lnn.py |
| 9. 导入顺序修复 | torch 先于 rdkit 加载导致 segfault | test_lnn.py、conftest.py |
问题描述:
LNN 的核心计算依赖 torch.func.jacfwd(前向模式 AD)和 torch.func.hessian(内部实现为 jacfwd(jacrev(...)))来计算 Lagrangian 函数的一阶 Jacobian 和二阶 Hessian。CANN 后端对前向模式 AD 的 JVP(Jacobian-vector product)算子支持不完整,导致运行时失败。
修改方案:
将 jacfwd 替换为 jacrev(反向模式 AD),将 hessian() 替换为 jacrev(jacrev(...))。反向模式 AD 即标准反向传播,NPU 支持完善。参考同仓库 ferminet.py:279-280 的相同做法。
修改代码(lnn.py:5, 145-149):
# 修改前
from torch.func import jacfwd, hessian, vmap
jacobians = vmap(
jacfwd(lambda xi: self.net(xi.unsqueeze(0)).squeeze()))(z)
hessians = vmap(
hessian(lambda xi: self.net(xi.unsqueeze(0)).squeeze()))(z)
# 修改后
from torch.func import jacrev, vmap
jacobians = vmap(
jacrev(lambda xi: self.net(xi.unsqueeze(0)).squeeze()))(z)
hessians = vmap(
jacrev(jacrev(lambda xi: self.net(xi.unsqueeze(0)).squeeze())))(z).contiguous()问题描述:
calculate_dynamics 方法中对 Jacobian 和 Hessian 张量进行切片操作([:, :n]、[:, n:, n:] 等),产生非连续内存视图。NPU 算子(torch.bmm、torch.linalg.solve)对非连续输入支持不完善,可能报错或产生错误结果。
修改方案:
切片后添加 .contiguous(),将非连续视图转为连续张量。.contiguous() 是 NPU 原生内存拷贝操作,不涉及 CPU 回退。同仓库 test_gan_npu.py:48-49 已有相同做法。
修改代码(lnn.py:151-154):
# 修改前
q_dot = z[:, n:]
dL_dq = jacobians[:, :n]
d2L_dqdot2 = hessians[:, n:, n:]
d2L_dqdot_dq = hessians[:, n:, :n]
# 修改后
q_dot = z[:, n:].contiguous()
dL_dq = jacobians[:, :n].contiguous()
d2L_dqdot2 = hessians[:, n:, n:].contiguous()
d2L_dqdot_dq = hessians[:, n:, :n].contiguous()torch.linalg.solve(CPU 自动回退)问题描述:
Euler-Lagrange 方程求解需要 torch.linalg.solve 解线性方程组 d2L_dqdot2 · q_ddot = rhs。该算子在 NPU 上无原生实现。
探索过程:
torch.linalg.cholesky + torch.linalg.solve_triangular,NPU 原生):当矩阵非正定时(未训练网络的 Hessian),NPU Cholesky 不是抛出 Python 异常,而是触发硬件级 vector core exception(error code 507035),导致整个 NPU 设备崩溃,后续所有测试失败。添加 1e-6 正则化不足以解决此问题。torch.linalg.qr + torch.linalg.solve_triangular,NPU 原生):前向正确且无 CPU 回退,但 NPU float32 的 QR 分解精度比 CPU LAPACK 差约 26 倍(2.48e-5 vs 9.54e-7)。尝试迭代求精提升前向精度到 5.96e-8,但额外反向传播路径导致梯度数值不稳定(梯度范数在 17 到 5,936,775,495 之间剧烈波动),训练无法收敛(1000 epochs 后 MSE=26.1,要求 < 0.1)。修改方案:
保持 torch.linalg.solve,接受 CPU 自动回退。NPU 的 VariableFallbackKernel 自动将张量拷贝到 CPU 执行计算,结果再拷贝回 NPU,前向和反向梯度都能正确传播。LNN 中求解的矩阵很小(2×2),性能影响可忽略。
修改代码(lnn.py:158-164):
# 修改前
# accelerations values
q_ddot = torch.linalg.solve(d2L_dqdot2, rhs.unsqueeze(-1)).squeeze(-1)
# 修改后
# accelerations values
# torch.linalg.solve falls back to CPU on NPU (no native NPU op), but is
# safe and reliable. Cholesky decomposition is NPU native but crashes the
# device when the matrix is not positive definite (untrained network Hessian).
# QR decomposition is NPU native but float32 precision is insufficient for
# training convergence (iterative refinement causes gradient instability).
q_ddot = torch.linalg.solve(d2L_dqdot2, rhs.unsqueeze(-1)).squeeze(-1)softplus → tanh问题描述:
LNN 默认使用 softplus 激活函数。NPU 的 aclnnSoftplusBackward 算子在 jacrev(jacrev(...)) 计算 Hessian 时,要求 self(softplus 输入)和 gradOutput(梯度)形状完全一致,不支持广播。vmap 内部产生形状 [1,1,1,1,32] vs [1,4,1,1,32] 的不匹配,导致 RuntimeError: call aclnnSoftplusBackward failed, error code is 161002。
修改方案:
将默认激活函数从 softplus 替换为 tanh。tanh 是平滑的(有定义良好的二阶导数,适合 Hessian 计算),且同仓库 HNN 模型(hnn.py:58)已使用 tanh。relu 的二阶导数几乎处处为零,不适合 LNN。涉及 LNN.__init__、LNNModel.__init__ 默认参数及所有 docstring。
修改代码(lnn.py:58, 246 等):
# LNN.__init__ 默认参数 (lnn.py:58)
# 修改前: activation_fn: str = 'softplus'
# 修改后: activation_fn: str = 'tanh'
# LNNModel.__init__ 默认参数 (lnn.py:246)
# 修改前: activation_fn: str = 'softplus',
# 修改后: activation_fn: str = 'tanh',
# 所有 docstring 中的示例和说明同步更新LNNModel 公开方法添加设备迁移问题描述:
LNNModel.predict_lagrangian() 和 LNNModel.calculate_dynamics() 直接将输入 z 传给模型,未将 z 移到 self.device。模型在 NPU 但 z 在 CPU 时报设备不匹配错误(RuntimeError: Expected all tensors to be on the same device)。
修改方案:
方法内添加 z.to(self.device),确保输入张量与模型在同一设备上。z.to(self.device) 是设备间数据传输,NPU 原生支持,无 CPU 回退。同仓库 hnn.py:260 已有类似做法。
修改代码(lnn.py:270, 286):
# predict_lagrangian (lnn.py:270)
# 修改前: return self.model.lagrangian(z)
# 修改后: return self.model.lagrangian(z.to(self.device))
# calculate_dynamics (lnn.py:286)
# 修改前: return self.model.calculate_dynamics(z)
# 修改后: return self.model.calculate_dynamics(z.to(self.device))问题描述:
LNNModel.save() 使用 joblib 保存到 model.joblib,但 LNNModel 未覆写 restore(),测试中调用的 restore() 走父类 TorchModel.restore(),从 .pt checkpoint 文件加载。两种机制不一致,且 joblib 序列化 NPU 张量可能失败或丢失设备信息。
修改方案:
覆写 restore() 调用 self.reload(),使 save/restore 配对使用 joblib 机制。reload() 中添加 .to(self.device),将反序列化后(CPU 上)的模型移回 NPU。
修改代码(lnn.py:288-299):
# 修改前
def save(self):
save_to_disk(self.model, self.get_model_filename(self.model_dir))
def reload(self):
self.model = load_from_disk(self.get_model_filename(self.model_dir))
# 修改后
def save(self):
"""Saves model to disk using joblib."""
save_to_disk(self.model, self.get_model_filename(self.model_dir))
def reload(self):
"""Loads model from joblib file on disk."""
self.model = load_from_disk(self.get_model_filename(self.model_dir))
self.model = self.model.to(self.device)
def restore(self, **kwargs):
"""Restores model from disk using joblib."""
self.reload()torch_npu 导入和 NPU 可用性检查问题描述:
测试文件未导入 torch_npu(NPU 后端注册所必需),未检查 is_npu_available(),无法在没有 NPU 的环境中优雅跳过。
修改方案:
在文件头部添加独立的 try/except 块导入 torch_npu 和 is_npu_available,设置 has_npu 标志。与 has_torch 分离,避免 torch_npu 未安装时影响 torch 基础测试的跳过逻辑。每个测试函数添加 @pytest.mark.skipif(not has_npu, ...) 装饰器。
修改代码(test_lnn.py:13-18):
# 新增
try:
import torch_npu
from deepchem.models.torch_models.torch_model import is_npu_available
has_npu = is_npu_available()
except (ModuleNotFoundError, ImportError):
has_npu = False
# 每个测试函数新增装饰器
@pytest.mark.skipif(not has_npu, reason="NPU is not available")问题描述:
测试 1-3(test_forward_eval、test_calculate_dynamics_shape、test_lagrangian)直接使用 LNN(普通 nn.Module,无设备自动检测逻辑),模型和张量都在 CPU 上创建,完全没有测试 NPU 功能。
修改方案:
添加设备检测,模型用 .to(device),张量用 device=device。has_npu 已在文件头部定义,直接复用。测试 4/5/6 使用 LNNModel(继承 TorchModel),已自动处理设备迁移,无需修改。
修改代码(test_lnn.py:27-29, 41-43, 54-56,3 个测试函数均修改):
# 修改前
model = LNN(n_dof=2)
input_tensor = torch.tensor([[1.0, 5.0, 2.0, 3.0]], dtype=torch.float32)
# 修改后
device = torch.device('npu' if has_npu else 'cpu')
model = LNN(n_dof=2).to(device)
input_tensor = torch.tensor([[1.0, 5.0, 2.0, 3.0]], dtype=torch.float32, device=device)问题描述:
deepchem 导入链中 graph_utils.py:4 先导入 torch,poly_wd_graph_utils.py:1 后导入 rdkit.Chem。torch 先于 rdkit 加载导致 C++ 符号冲突 segfault,使 import deepchem 崩溃,所有测试无法运行。
修改方案:
在 test_lnn.py 和 conftest.py 顶部添加 from rdkit import Chem,确保 rdkit 先于 torch 加载。conftest.py 是 pytest 测试收集的入口,必须一并修改。
修改代码:
# test_lnn.py:1(新增)
from rdkit import Chem # noqa: F401 must be imported before torch to avoid segfault
# conftest.py:1(新增)
from rdkit import Chem # noqa: F401 must be imported before torch to avoid segfaulttorch-npu:2.7.1.post4-910b-openeuler24.03-py3.11| 测试项 | 验收标准 | 结果 |
|--------|---------|------|
| test_forward_eval | 输出 shape [1, 2] | PASS |
| test_calculate_dynamics_shape | 输出 shape [1, 2] | PASS |
| test_lagrangian | 输出 shape [1] | PASS |
| test_lnnmodel_train_and_predict | pred.shape == labels.shape | PASS |
| test_lnnmodel_restore | np.allclose(atol=1e-4) | PASS |
| test_lnnmodel_overfit | MSE < 0.1 (1000 epoch) | PASS |
======================== 6 passed, 2 warnings in 21.84s ========================Q1:运行测试报 Segmentation fault?
A:torch 先于 rdkit 加载导致 C++ 符号冲突。需在文件顶部添加 from rdkit import Chem 确保 rdkit 先加载。test_lnn.py 和 conftest.py 均需修改。
Q2:报 RuntimeError: call aclnnSoftplusBackward failed, error code is 161002?
A:NPU 的 softplus_backward 算子不支持广播。LNN 默认激活函数已从 softplus 改为 tanh,如自定义模型仍用 softplus 会触发此问题。
Q3:报 RuntimeError: ... is not positive definite 或 NPU 设备崩溃(error 507035)?
A:Cholesky 分解方案在矩阵非正定时触发硬件级异常。LNN 已回退为 torch.linalg.solve(CPU 自动回退),不要改回 Cholesky。
Q4:torch_npu.is_available() 返回 False?
A:检查容器是否挂载了 NPU 设备(--device /dev/davinci0 等)及 driver 目录;宿主机执行 npu-smi info 确认设备在线。
Q5:torch.linalg.solve 出现 CPU 回退 warning 是否正常?
A:正常。aten::_linalg_solve_ex.result 在 NPU 上无原生实现,通过 VariableFallbackKernel 自动回退到 CPU 执行,前向和反向梯度均正确。LNN 求解矩阵为 2×2,性能影响可忽略。