PINN(Physics-Informed Neural Network,物理信息神经网络)是一种将物理定律(偏微分方程)嵌入神经网络训练过程的深度学习方法。通过在损失函数中加入 PDE 残差项,使网络在拟合数据的同时满足物理约束,从而在少量数据下也能获得物理一致的解。本模型基于 DeepChem 的 TorchModel 实现,支持 Dirichlet、Neumann、Robin 三类边界条件,利用 torch.autograd.grad 配合 create_graph=True 计算高阶导数构建 PDE 残差。
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() | 调用评估函数进行推理 |
| 项目 | 规格 |
|---|---|
| 任务类型 | 偏微分方程求解(回归) |
| 框架依赖 | DeepChem + torch_npu |
| 核心机制 | create_graph=True 二阶自动微分 |
| 默认 batch_size | 32(热方程测试) |
| 默认 learning_rate | 0.001 |
| 精度参考 | MSE < 1e-2,PDE 残差 < 1e-2(100 epoch) |
| 运行设备 | Atlas 800T A2(单卡 NPU) |
| 路径 | 用途 |
|---|---|
deepchem/models/torch_models/pinns_model.py | PINN 模型实现 |
deepchem/models/torch_models/tests/test_pinns.py | 端到端 NPU 测试脚本 |
conftest.py(根目录) | pytest 入口,修复 rdkit/torch 导入顺序段错误 |
test_pinns.py 测试脚本(见 §4.3 / §4.4)| 组件 | 版本 |
|---|---|
| Python | 3.11.15 |
| PyTorch | 2.7.1+cpu |
| torch_npu | 2.7.1.post4 |
| CANN | 9.0.0 |
| DeepChem | develop 分支(本地源码安装) |
| 设备型号 | 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=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# 安装 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-depsPINN 模型的 NPU 适配代码已直接修改在 deepchem-ascend 源码中,无需额外安装二进制包。涉及修改 2 个文件共 8 处代码,详见 §5.2 适配要点。
"""
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)方式一:直接运行测试脚本
将上述测试代码保存为 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| 步骤 | 修改文件 | 修改位置 | 说明 |
|---|---|---|---|
| 1. 修复 CPU 累加器张量 | deepchem/models/torch_models/pinns_model.py | line 230 | _compute_pde_loss 中 torch.tensor(0.0) 默认创建在 CPU,与 NPU 张量做 += 跨设备报错,需添加 device=self.device |
| 2. 修复 CPU 累加器张量 | deepchem/models/torch_models/pinns_model.py | line 256, 258 | _compute_boundary_loss 中两处 torch.tensor(0.0) 默认创建在 CPU,与 NPU 张量做 += 跨设备报错,需添加 device=self.device |
| 3. 迁移 boundary_data 到 NPU | deepchem/models/torch_models/pinns_model.py | line 203-207(新增) | __init__ 中 boundary_data 的 points/values 张量在 CPU 上,需在 super().__init__() 后原地修改 dict 迁移到 NPU |
| 4. 修复 predict 设备迁移 | deepchem/models/torch_models/pinns_model.py | line 369-370(新增) | predict() 方法直接调用 eval_fn 未做设备迁移,需在调用前将输入张量迁移到 self.device |
| 5. 修复测试中 CPU 张量调用 NPU 模型 | deepchem/models/torch_models/tests/test_pinns.py | line 61 | 测试中直接用 CPU 张量调用已被迁移到 NPU 的模型,需添加 .to(pinn.device) |
6. 修复 .numpy() 用于 NPU 张量 | deepchem/models/torch_models/tests/test_pinns.py | line 64 | NPU 张量不能直接 .numpy(),改用 torch.allclose 在 NPU 上直接比较 |
| 7. 修复 NPU/CPU 张量算术运算 | deepchem/models/torch_models/tests/test_pinns.py | line 165 | y_pred(NPU)与 y_true(CPU)做减法跨设备报错,需将 y_true 迁移到 NPU |
| 8. 修复残差计算设备迁移 | deepchem/models/torch_models/tests/test_pinns.py | line 174 | x_interior 从 CPU 切片而来,需 .to(pinn.device).requires_grad_(True) 先迁移再启用梯度 |
| 9. 验证二阶自动微分 NPU 兼容性 | —(无代码修改,仅验证) | — | 分步验证 create_graph=True 二阶反向传播在 NPU 上正常工作 |
_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)_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)问题描述:
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__() 内部才赋值,迁移代码必须放在其后修改方案:
在 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)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)问题描述:
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)).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)问题描述:
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问题描述:
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)torch-npu:2.7.1.post4-910b-openeuler24.03-py3.11| 测试用例 | 验证内容 | 结果 | 备注 |
|---|---|---|---|
test_pinns_overfit | 模型过拟合能力 | PASS | 最终 loss: 5.05e-11(阈值 < 1e-3) |
test_pinn_default_model | 默认模型初始化与预测 | PASS | 输出 shape [2,1] 正确 |
test_pinn_custom_eval | 自定义评估函数 | PASS | torch.allclose 通过 |
test_pinn_heat_equation | 1D 稳态热方程求解 | PASS | 含二阶自动微分 |
总体结果:4/4 全部通过
| 指标 | 实测值 | 阈值 | 结果 |
|---|---|---|---|
| MSE(预测 vs 解析解 u=x) | 4.80e-03 | < 1e-2 | PASS |
| 边界条件 x=0:|y(0)| | 2.76e-02 | < 1e-1 | PASS |
| 边界条件 x=1:|y(1)-1| | 1.72e-02 | < 1e-1 | PASS |
| PDE 残差 |du/dx - d²u/dx²| | 2.38e-03 | < 1e-2 | PASS |
训练最终 loss: 0.00582
| 测试 | 耗时 | 每 epoch | NPU 显存(allocated) |
|---|---|---|---|
| test_pinns_overfit(300 epochs, 2 样本) | 2.89s | 9.63ms | 0.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.10s | 501ms | 0.3 MB |
| 检查项 | 设备 | 状态 |
|---|---|---|
| 模型参数 | npu:0 | NPU |
| boundary_data (points/values) | npu:0 | NPU |
| 输入数据(_prepare_batch 后) | npu:0 | NPU |
| 前向输出 | npu:0 | NPU |
| 一阶导数 du_dx | npu:0 | NPU |
| 二阶导数 d2u_dx2 | npu:0 | NPU |
| PDE 残差 | npu:0 | NPU |
| data_loss / physics_loss / boundary_loss | npu:0 | NPU |
| 梯度(backward 后) | npu:0 | NPU |
| 优化器参数 | npu:0 | NPU |
| predict 输出 | npu:0 | NPU |
| CPU fallback 检测 | 无 | 无 fallback |
结论:PINN 模型完全运行在 NPU 上,不存在 CPU fallback。
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:
passQ2:create_graph=True 的二阶自动微分在 NPU 上是否支持?
A:已验证支持。分三步测试:
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 张量上。