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

PINNModel

PINN(Physics-Informed Neural Network,物理信息神经网络)是一种将物理定律(偏微分方程)嵌入神经网络训练过程的深度学习方法。通过在损失函数中加入 PDE 残差项,使网络在拟合数据的同时满足物理约束,从而在少量数据下也能获得物理一致的解。本模型基于 DeepChem 的 TorchModel 实现,支持 Dirichlet、Neumann、Robin 三类边界条件,利用 torch.autograd.grad 配合 create_graph=True 计算高阶导数构建 PDE 残差。


1. 模型分析

1.1 模型架构

PINNModel 基于 PyTorch 的 TorchModel 扩展,主要计算流程如下:

阶段模块说明
前向推理自定义 MLP / 用户提供模型对输入坐标 x 进行前向计算得到预测值 u
PDE 残差torch.autograd.grad(高阶自动微分)通过 create_graph=True 构建二阶反向传播图,计算 du/dx、d²u/dx²
损失计算data_loss + physics_loss + boundary_loss数据损失 + PDE 残差损失 + 边界条件损失
反向传播loss.backward()通过二阶计算图反向传播梯度
推理预测predict() → eval_fn()调用评估函数进行推理

1.2 模型规格

项目规格
任务类型偏微分方程求解(回归)
框架依赖DeepChem + torch_npu
核心机制create_graph=True 二阶自动微分
默认 batch_size32(热方程测试)
默认 learning_rate0.001
精度参考MSE < 1e-2,PDE 残差 < 1e-2(100 epoch)
运行设备Atlas 800T A2(单卡 NPU)

2. 快速开始

2.1 模型与代码路径

路径用途
deepchem/models/torch_models/pinns_model.pyPINN 模型实现
deepchem/models/torch_models/tests/test_pinns.py端到端 NPU 测试脚本
conftest.py(根目录)pytest 入口,修复 rdkit/torch 导入顺序段错误

2.2 部署步骤(概览)

  1. 拉取并启动镜像(见 §3.3 / §3.4)
  2. 容器内安装 deepchem-ascend 代码及依赖(见 §4.1)
  3. 运行 test_pinns.py 测试脚本(见 §4.3 / §4.4)

3. 准备运行环境

3.1 软件环境

组件版本
Python3.11.15
PyTorch2.7.1+cpu
torch_npu2.7.1.post4
CANN9.0.0
DeepChemdevelop 分支(本地源码安装)

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=pinnmodel
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 安装依赖

# 安装 Python 依赖
pip install packaging tqdm transformers -i https://pypi.org/simple/
pip install pytest -i https://pypi.org/simple/

# 本地源码安装 deepchem-ascend(develop 分支)
cd /home/deepchem-ascend_gxl
pip install -e . --no-deps

4.2 迁移适配

PINN 模型的 NPU 适配代码已直接修改在 deepchem-ascend 源码中,无需额外安装二进制包。涉及修改 2 个文件共 8 处代码,详见 §5.2 适配要点。

4.3 测试示例

"""
PINN Model NPU Test Script
Tests all 4 test cases on NPU device
"""
from rdkit import Chem  # noqa: F401  must be imported before torch to avoid segfault
import time
import torch
import torch_npu
torch.npu.set_device(0)
import deepchem as dc
import numpy as np
from deepchem.models.torch_models import PINNModel

device = torch.device('npu:0')


def test_pinns_overfit():
    """Test 1: Overfit test"""
    model = torch.nn.Sequential(torch.nn.Linear(1, 64), torch.nn.Tanh(),
                                torch.nn.Linear(64, 64), torch.nn.Tanh(),
                                torch.nn.Linear(64, 1))
    pinn = PINNModel(
        model=model,
        pde_fn=lambda u, x: torch.zeros_like(u),
        boundary_data={
            'dirichlet': {
                'points': torch.tensor([[0.0], [1.0]], dtype=torch.float32),
                'values': torch.tensor([[0.0], [1.0]], dtype=torch.float32)
            }
        })
    dataset = dc.data.NumpyDataset(X=torch.tensor([[0.0], [1.0]]),
                                   y=torch.tensor([[0.0], [1.0]]))
    loss = pinn.fit(dataset, nb_epoch=300)
    assert loss < 1e-3, "Model can't overfit"
    print(f"[test_pinns_overfit] PASS, loss={loss:.2e}")


def test_pinn_default_model():
    """Test 2: Default model test"""
    x = torch.tensor([[1.0, 0.0], [0.0, 1.0]])
    pinn = PINNModel(in_features=x.shape[1])
    assert pinn.model is not None
    output = pinn.predict(x)
    assert output is not None
    assert output.shape[0] == x.shape[0]
    print(f"[test_pinn_default_model] PASS, output shape={output.shape}")


def test_pinn_custom_eval():
    """Test 3: Custom eval function test"""
    model = torch.nn.Linear(1, 1)
    def custom_eval(x):
        return 2 * model(x)
    pinn = PINNModel(model=model, eval_fn=custom_eval)
    test_dataset = torch.tensor([[1.0]], dtype=torch.float32)
    with torch.no_grad():
        y_standard = model(test_dataset.to(pinn.device))
        y_custom = pinn.predict(test_dataset)
    assert torch.allclose(y_custom, 2 * y_standard, atol=1e-6)
    print(f"[test_pinn_custom_eval] PASS")


def test_pinn_heat_equation():
    """Test 4: Heat equation PDE solving test"""
    class HeatNet(torch.nn.Module):
        def __init__(self):
            super(HeatNet, self).__init__()
            self.net = torch.nn.Sequential(
                torch.nn.Linear(1, 64), torch.nn.Tanh(),
                torch.nn.Linear(64, 64), torch.nn.Tanh(),
                torch.nn.Linear(64, 1))
        def forward(self, x):
            if not isinstance(x, torch.Tensor):
                x = torch.tensor(x, dtype=torch.float32)
            return self.net(x)

    def heat_equation_residual(model, x):
        x.requires_grad_(True)
        u = model(x)
        du_dx = torch.autograd.grad(u.sum(), x, create_graph=True,
                                    retain_graph=True)[0]
        d2u_dx2 = torch.autograd.grad(du_dx.sum(), x, create_graph=True,
                                      retain_graph=True)[0]
        return du_dx - d2u_dx2

    def custom_loss(outputs, labels, weights=None):
        outputs = outputs[0]
        labels = labels[0]
        data_loss = torch.mean(torch.square(outputs - labels))
        pde_residuals = heat_equation_residual(model, labels)
        pde_loss = torch.mean(torch.abs(pde_residuals))
        boundary_loss = 0.0
        for _, value in boundary_data.items():
            if isinstance(value, dict):
                points = value.get('points')
                values = value.get('values')
                if points is not None and values is not None:
                    pred = model(points)
                    boundary_loss += torch.mean(torch.square(pred - values))
        return 0.5 * data_loss + 0.5 * pde_loss + boundary_loss

    x_train = torch.linspace(0, 1, 2000)[1:-1].reshape(-1, 1)
    x_boundary = torch.tensor([[0.0], [1.0]])
    x_train = torch.cat([x_train, x_boundary], dim=0)
    y_train = x_train.clone()
    dataset = dc.data.NumpyDataset(X=x_train.numpy(), y=y_train.numpy())

    boundary_data = {
        'dirichlet': {
            'points': torch.tensor([[0.0], [1.0]], dtype=torch.float32),
            'values': torch.tensor([[0.0], [1.0]], dtype=torch.float32)
        }
    }

    model = HeatNet()
    pinn = PINNModel(model=model,
                     pde_fn=lambda u, x: heat_equation_residual(model, x),
                     loss_fn=custom_loss,
                     boundary_data=boundary_data,
                     learning_rate=0.001, batch_size=32,
                     data_weight=1.0, physics_weight=1.0)
    pinn.fit(dataset, nb_epoch=100)

    x_test = torch.linspace(0, 1, 100).reshape(-1, 1)
    with torch.no_grad():
        y_pred = pinn.predict(x_test)
    y_true = x_test.to(pinn.device)
    mse = torch.mean((y_pred - y_true)**2)
    assert mse < 1e-2, f"MSE {mse} is too high"
    assert torch.abs(y_pred[0]) < 1e-1
    assert torch.abs(y_pred[-1] - 1.0) < 1e-1

    x_interior = x_test[1:-1].clone().to(pinn.device).requires_grad_(True)
    residuals = heat_equation_residual(model, x_interior)
    pde_error = torch.mean(torch.abs(residuals))
    assert pde_error < 1e-2, f"PDE residuals are too high"
    print(f"[test_pinn_heat_equation] PASS, MSE={mse:.2e}, PDE error={pde_error:.2e}")


if __name__ == "__main__":
    print("=" * 60)
    print("PINN Model NPU Test")
    print(f"Device: {device}")
    print("=" * 60)

    test_pinns_overfit()
    test_pinn_default_model()
    test_pinn_custom_eval()
    test_pinn_heat_equation()

    print("\n" + "=" * 60)
    print("ALL TESTS PASSED!")
    print("=" * 60)

4.4 运行测试代码

方式一:直接运行测试脚本

将上述测试代码保存为 test_pinn_npu.py:

python test_pinn_npu.py

方式二:通过 pytest 运行

cd /home/deepchem-ascend_gxl
python -m pytest deepchem/models/torch_models/tests/test_pinns.py -v -s

方式三:运行带性能/精度采集的综合脚本

python /tmp/run_pinn_tests.py

5. 实现细节

5.1 关键适配步骤

步骤修改文件修改位置说明
1. 修复 CPU 累加器张量deepchem/models/torch_models/pinns_model.pyline 230_compute_pde_loss 中 torch.tensor(0.0) 默认创建在 CPU,与 NPU 张量做 += 跨设备报错,需添加 device=self.device
2. 修复 CPU 累加器张量deepchem/models/torch_models/pinns_model.pyline 256, 258_compute_boundary_loss 中两处 torch.tensor(0.0) 默认创建在 CPU,与 NPU 张量做 += 跨设备报错,需添加 device=self.device
3. 迁移 boundary_data 到 NPUdeepchem/models/torch_models/pinns_model.pyline 203-207(新增)__init__ 中 boundary_data 的 points/values 张量在 CPU 上,需在 super().__init__() 后原地修改 dict 迁移到 NPU
4. 修复 predict 设备迁移deepchem/models/torch_models/pinns_model.pyline 369-370(新增)predict() 方法直接调用 eval_fn 未做设备迁移,需在调用前将输入张量迁移到 self.device
5. 修复测试中 CPU 张量调用 NPU 模型deepchem/models/torch_models/tests/test_pinns.pyline 61测试中直接用 CPU 张量调用已被迁移到 NPU 的模型,需添加 .to(pinn.device)
6. 修复 .numpy() 用于 NPU 张量deepchem/models/torch_models/tests/test_pinns.pyline 64NPU 张量不能直接 .numpy(),改用 torch.allclose 在 NPU 上直接比较
7. 修复 NPU/CPU 张量算术运算deepchem/models/torch_models/tests/test_pinns.pyline 165y_pred(NPU)与 y_true(CPU)做减法跨设备报错,需将 y_true 迁移到 NPU
8. 修复残差计算设备迁移deepchem/models/torch_models/tests/test_pinns.pyline 174x_interior 从 CPU 切片而来,需 .to(pinn.device).requires_grad_(True) 先迁移再启用梯度
9. 验证二阶自动微分 NPU 兼容性—(无代码修改,仅验证)—分步验证 create_graph=True 二阶反向传播在 NPU 上正常工作

5.2 适配要点

适配要点 1:_compute_pde_loss CPU 累加器

问题描述:

_compute_pde_loss 方法中 residual_loss 初始化为 torch.tensor(0.0),默认创建在 CPU 上。当 NPU 上的 residuals 张量与 CPU 累加器做 += 操作时,触发跨设备报错。影响 test_pinns_overfit 和 test_pinn_default_model。

修改方案:

添加 device=self.device 参数,使累加器张量创建在 NPU 上。

修改文件: deepchem/models/torch_models/pinns_model.py

# 修改前(line 230)
residual_loss = torch.tensor(0.0)

# 修改后(line 230)
residual_loss = torch.tensor(0.0, device=self.device)

适配要点 2:_compute_boundary_loss CPU 累加器(2 处)

问题描述:

_compute_boundary_loss 方法中两处 torch.tensor(0.0) 默认创建在 CPU:

  • 空返回值(return torch.tensor(0.0))
  • 累加器初始化(boundary_loss = torch.tensor(0.0))

NPU 上的边界损失张量与 CPU 累加器做 += 时跨设备报错。影响 test_pinns_overfit 和 test_pinn_default_model。

修改方案:

两处均添加 device=self.device 参数。

修改文件: deepchem/models/torch_models/pinns_model.py

# 修改前(line 255-258)
if not self.boundary_data:
    return torch.tensor(0.0)

boundary_loss = torch.tensor(0.0)

# 修改后(line 255-258)
if not self.boundary_data:
    return torch.tensor(0.0, device=self.device)

boundary_loss = torch.tensor(0.0, device=self.device)

适配要点 3:boundary_data 张量未迁移到 NPU

问题描述:

boundary_data 中的 points 和 values 张量由用户在测试中创建于 CPU。PINNModel.__init__ 未将它们迁移到 NPU。_compute_boundary_loss 中 self.model(points) 和 pred - values 跨设备报错。

同时,test_pinn_heat_equation 的 custom_loss 闭包通过引用访问同一 dict 对象,也受影响。

关键约束:

  • self.device 在 super().__init__() 内部才赋值,迁移代码必须放在其后
  • 原地修改 dict(而非创建新 dict)确保闭包引用同一对象能访问到迁移后的张量

修改方案:

在 super().__init__() 之后,遍历 self.boundary_data,将 points 和 values 张量替换为 .to(self.device) 版本。

修改文件: deepchem/models/torch_models/pinns_model.py

# 修改前(line 199-201)
super(PINNModel, self).__init__(model=model,
                                loss=self.loss_fn,
                                **kwargs)
# (无后续迁移代码)

# 修改后(line 199-207)
super(PINNModel, self).__init__(model=model,
                                loss=self.loss_fn,
                                **kwargs)

for key, value in self.boundary_data.items():
    if isinstance(value, dict):
        for field in ('points', 'values'):
            if field in value and isinstance(value[field], torch.Tensor):
                value[field] = value[field].to(self.device)

适配要点 4:predict 无设备迁移

问题描述:

PINNModel.predict() 完全重写了父类的 predict,直接调用 self.eval_fn(dataset),绕过了父类 TorchModel._predict 的设备处理机制(通过 _prepare_batch 做 torch.as_tensor(x, device=self.device))。

_default_eval_fn 执行 self.model(x),模型在 NPU 但输入在 CPU,跨设备报错。影响 test_pinn_default_model、test_pinn_custom_eval、test_pinn_heat_equation。

修改方案:

在调用 eval_fn 前,将输入张量迁移到 self.device。

修改文件: deepchem/models/torch_models/pinns_model.py

# 修改前(line 356-371)
def predict(self, dataset):
    """
    Makes predictions on dataset using the evaluation function.
    ...
    """
    return self.eval_fn(dataset)

# 修改后(line 356-371)
def predict(self, dataset):
    """
    Makes predictions on dataset using the evaluation function.
    ...
    """
    if isinstance(dataset, torch.Tensor):
        dataset = dataset.to(self.device)
    return self.eval_fn(dataset)

适配要点 5:测试中 CPU 张量调用 NPU 模型

问题描述:

test_pinn_custom_eval 中 model(test_dataset) 直接用 CPU 张量调用 NPU 模型。PINNModel.__init__ 调用 super().__init__() 时执行了 self.model = model.to(device),模型权重已迁移到 NPU,但 test_dataset 仍在 CPU。

修改方案:

调用时添加 .to(pinn.device)。

修改文件: deepchem/models/torch_models/tests/test_pinns.py

# 修改前(line 61)
y_standard = model(test_dataset)

# 修改后(line 61)
y_standard = model(test_dataset.to(pinn.device))

适配要点 6:.numpy() 用于 NPU 张量

问题描述:

test_pinn_custom_eval 中 y_standard.numpy() 的 y_standard 在 NPU 上,NPU 张量不能直接调用 .numpy()。且 y_custom - 2 * y_standard.numpy() 涉及 NPU 张量与 numpy 值的跨设备运算。

修改方案:

改用 torch.allclose 在 NPU 上直接比较,避免 .numpy() 和跨设备运算。

修改文件: deepchem/models/torch_models/tests/test_pinns.py

# 修改前(line 64)
assert np.abs(y_custom - 2 * y_standard.numpy()) < 1e-6

# 修改后(line 64)
assert torch.allclose(y_custom, 2 * y_standard, atol=1e-6)

适配要点 7:NPU/CPU 张量算术运算

问题描述:

test_pinn_heat_equation 中 y_pred(NPU,predict 修复后返回 NPU 张量)与 y_true = x_test(CPU)做减法,跨设备报错。

修改方案:

将 y_true 迁移到 NPU,与 y_pred 同设备。

修改文件: deepchem/models/torch_models/tests/test_pinns.py

# 修改前(line 165)
y_true = x_test  # analytical solution: u(x) = x

# 修改后(line 165)
y_true = x_test.to(pinn.device)  # analytical solution: u(x) = x

适配要点 8:CPU 张量调用 NPU 模型计算残差

问题描述:

test_pinn_heat_equation 中 x_interior 从 CPU 上的 x_test 切片而来,仍在 CPU。heat_equation_residual(model, x_interior) 内部 model(x) 跨设备报错。

且 requires_grad_(True) 是原地操作,必须在 .to() 之后调用,确保梯度建立在 NPU 张量上。若顺序反过来,.to() 返回新 NPU 张量,梯度追踪关系可能丢失。

修改方案:

切片后先 .to(pinn.device) 迁移到 NPU,再 .requires_grad_(True) 启用梯度。

修改文件: deepchem/models/torch_models/tests/test_pinns.py

# 修改前(line 174)
x_interior = x_test[1:-1].clone().requires_grad_(True)

# 修改后(line 174)
x_interior = x_test[1:-1].clone().to(pinn.device).requires_grad_(True)

6. 测试结果

6.1 测试环境

  • 设备:Atlas 800T A2(单卡 NPU)
  • 镜像:torch-npu:2.7.1.post4-910b-openeuler24.03-py3.11
  • 代码分支:develop

6.2 模型测试结果

测试用例验证内容结果备注
test_pinns_overfit模型过拟合能力PASS最终 loss: 5.05e-11(阈值 < 1e-3)
test_pinn_default_model默认模型初始化与预测PASS输出 shape [2,1] 正确
test_pinn_custom_eval自定义评估函数PASStorch.allclose 通过
test_pinn_heat_equation1D 稳态热方程求解PASS含二阶自动微分

总体结果:4/4 全部通过

6.3 精度测试结果(test_pinn_heat_equation)

指标实测值阈值结果
MSE(预测 vs 解析解 u=x)4.80e-03< 1e-2PASS
边界条件 x=0:|y(0)|2.76e-02< 1e-1PASS
边界条件 x=1:|y(1)-1|1.72e-02< 1e-1PASS
PDE 残差 |du/dx - d²u/dx²|2.38e-03< 1e-2PASS

训练最终 loss: 0.00582

6.4 性能测试结果

测试耗时每 epochNPU 显存(allocated)
test_pinns_overfit(300 epochs, 2 样本)2.89s9.63ms0.1 MB
test_pinn_default_model(推理)1.48ms—0.2 MB
test_pinn_custom_eval(推理)19.54ms—0.2 MB
test_pinn_heat_equation(100 epochs, 2000 样本, batch_size=32)50.10s501ms0.3 MB

6.5 NPU 设备完整性验证

检查项设备状态
模型参数npu:0NPU
boundary_data (points/values)npu:0NPU
输入数据(_prepare_batch 后)npu:0NPU
前向输出npu:0NPU
一阶导数 du_dxnpu:0NPU
二阶导数 d2u_dx2npu:0NPU
PDE 残差npu:0NPU
data_loss / physics_loss / boundary_lossnpu:0NPU
梯度(backward 后)npu:0NPU
优化器参数npu:0NPU
predict 输出npu:0NPU
CPU fallback 检测无无 fallback

结论:PINN 模型完全运行在 NPU 上,不存在 CPU fallback。


7. FAQ

Q1:import deepchem 时发生段错误(Segmentation fault)?

A:deepchem 导入链中 graph_utils.py 先导入 torch,poly_wd_graph_utils.py 后导入 rdkit.Chem。torch 先于 rdkit 加载导致 C++ 符号冲突。解决方案是在 conftest.py 顶部添加 from rdkit import Chem,确保 rdkit 先于 torch 加载。根目录的 conftest.py 已包含此修复:

# conftest.py
try:
    from rdkit import Chem  # noqa: F401
except ImportError:
    pass

Q2:create_graph=True 的二阶自动微分在 NPU 上是否支持?

A:已验证支持。分三步测试:

  • Step 1-3:单独测试前向、一阶导数、二阶导数 → 通过
  • Step 4-6:完整训练步骤(前向 + PDE 残差 + backward + optimizer step)→ 通过
  • 完整测试:test_pinn_heat_equation 100 epoch 训练 + 推理验证 → 通过

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

A:检查容器是否挂载了 NPU 设备(--device /dev/davinci0 等)及 driver 目录;宿主机执行 npu-smi info 确认设备在线。

Q4:安装依赖时报 403 错误?

A:部分镜像源可能限制访问,尝试切换 pip 源:

pip install <package> -i https://pypi.org/simple/

Q5:requires_grad_(True) 和 .to(device) 的调用顺序为什么重要?

A:.to(device) 在目标设备与当前设备不同时返回新张量(非原地操作),.requires_grad_() 是原地操作。若先 requires_grad_(True) 再 .to(device),.to() 返回新的 NPU 张量,CPU 张量上的梯度追踪关系不继承到新张量。正确顺序是 .to(device).requires_grad_(True),确保梯度建立在最终的 NPU 张量上。