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

FNOModel

FNO(Fourier Neural Operator,傅里叶神经算子)是一种用于学习函数空间映射的神经网络架构。它通过在傅里叶空间中使用频谱卷积高效捕获全局依赖关系,使其在求解偏微分方程(PDE)方面尤为有效。与仅捕获局部特征的传统 CNN 不同,FNO 利用傅里叶变换在频域中操作,以极少的参数量建模长距离全局依赖。


1. 模型分析

1.1 模型架构

FNOModel 基于傅里叶神经算子,主要计算流程如下:

阶段模块说明
输入提升Lifting LayerLinear(in→2w) → GELU → Linear(2w→w),将输入映射到高维表示
频谱卷积FNOBlock × depth每个块并联 SpectralConv(全局频域特征)与 1×1 Conv(局部特征),相加后 ReLU
输出投影Projection LayerLinear(w→2w) → GELU → Linear(2w→out),映射回输出空间

其中 SpectralConv 是核心算子,执行三步操作:

  1. torch.fft.rfftn:空间域 → 频域
  2. 截取低频模 + 复数 einsum 通道间线性变换
  3. torch.fft.irfftn:频域 → 空间域

1.2 模型规格

项目规格
任务类型偏微分方程求解 / 函数空间映射(回归)
框架依赖DeepChem + torch_npu
架构特点频谱卷积在频域捕获全局依赖,参数量与分辨率解耦
默认 depth4(FNOBlock 堆叠数)
默认 lossnn.MSELoss()
支持维度1D / 2D / 3D
位置编码可选 meshgrid positional encoding
运行设备Atlas 800T A2(单卡 NPU)

2. 快速开始

本章节为快速部署指引,详细参数见 §3 准备运行环境 与 §4 运行指导。

2.1 模型与代码路径

路径用途
deepchem/models/torch_models/fno.pyFNO 模型实现(FNOBlock、FNO、FNOModel)
deepchem/models/torch_models/layers.py:9455SpectralConv 频谱卷积层实现
deepchem/models/torch_models/tests/test_fno_npu.py端到端 NPU 测试脚本(14 个测试)

2.2 部署步骤(概览)

  1. 拉取并启动镜像(见 §3.3 / §3.4)
  2. 容器内安装 deepchem-ascend 二进制包(见 §4.2)
  3. 安装 Python 依赖(见 §4.1)
  4. 运行 test_fno_npu.py(见 §4.3 / §4.4)

3. 准备运行环境

3.1 软件环境

组件版本
Python3.11.15
PyTorch2.7.1+cpu
torch_npu2.7.1.post4
CANN9.0.0
deepchem-ascend0.0.8

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

# 安装 deepchem-ascend 二进制包及运行依赖
pip install deepchem-ascend==0.0.8 -i https://mirrors.aliyun.com/pypi/simple/
pip install pandas tqdm transformers scikit-learn rdkit -i https://mirrors.aliyun.com/pypi/simple/

4.2 迁移适配

直接安装 deepchem-ascend 二进制包,已基于适配代码重新编译成二进制包上传 pypi:

pip install deepchem-ascend==0.0.8 -i https://mirrors.aliyun.com/pypi/simple/

4.3 测试示例

"""
FNO Model NPU Test Script
Tests FNOBlock, FNO, FNOModel on NPU device
Covers: construction, forward, overfit, prediction, hyperparams, loss, reload
"""

from rdkit import Chem  # noqa: F401  must be imported before torch to avoid segfault
import pytest
import deepchem as dc
import tempfile

try:
    import torch
    import torch_npu
    has_torch = True
except (ModuleNotFoundError, ImportError):
    has_torch = False

torch.manual_seed(0)

npu_device = 'npu:0' if has_torch else 'cpu'
if has_torch:
    torch.npu.set_device(0)


@pytest.mark.torch
def test_fno_block_construction():
    """
    Test if FNOBlock can be constructed in 1D, 2D, and 3D.
    """
    from deepchem.models.torch_models.fno import FNOBlock
    block = FNOBlock(width=32, modes=8, dims=1)
    assert block is not None, "1D FNO Block construction failed"

    block = FNOBlock(width=32, modes=8, dims=2)
    assert block is not None, "2D FNO Block construction failed"

    block = FNOBlock(width=32, modes=8, dims=3)
    assert block is not None, "3D FNO Block construction failed"


@pytest.mark.torch
def test_fno_block_forward():
    """
    Test if FNOBlock can be forward-passed in 2D on NPU, without any errors.
    """
    from deepchem.models.torch_models.fno import FNOBlock
    block = FNOBlock(width=32, modes=8, dims=2).to(npu_device)
    x = torch.randn(100, 32, 100, 100, device=npu_device)
    y = block(x)
    assert y.shape == (100, 32, 100, 100)
    assert y.device.type == 'npu', "Output is not on NPU"


@pytest.mark.torch
def test_fno_base_forward():
    """
    Test if FNO can be forward-passed in 2D on NPU, without any errors.
    """
    from deepchem.models.torch_models.fno import FNO
    model = FNO(in_channels=1, out_channels=1, modes=8, width=32, dims=2).to(npu_device)
    x = torch.randn(100, 1, 100, 100, device=npu_device)
    y = model(x)
    assert y.shape == (100, 1, 100, 100)
    assert y.device.type == 'npu', "Output is not on NPU"


@pytest.mark.torch
def test_fno_overfit():
    """Test that FNO model can overfit simple data."""
    from deepchem.models.torch_models import FNOModel

    model = FNOModel(in_channels=1,
                     out_channels=1,
                     modes=8,
                     width=128,
                     dims=1,
                     depth=4)
    X = torch.randn(10, 1, 32)
    y = X  # Identity mapping
    dataset = dc.data.NumpyDataset(X=X, y=y)
    loss = model.fit(dataset, nb_epoch=200)
    assert loss < 1e-1, "Model can't overfit"

4.4 运行测试代码

复制完整测试代码保存到 test_fno_npu.py(见 §4.3),执行:

python -m pytest test_fno_npu.py -m torch -v

输出示例:

deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_block_construction PASSED [  7%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_block_forward      PASSED [ 14%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_base_construction  PASSED [ 21%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_base_forward       PASSED [ 28%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_base_meshgrids      PASSED [ 35%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_construction       PASSED [ 42%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_overfit            PASSED [ 50%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_overfit_2d          PASSED [ 57%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_prediction_shape    PASSED [ 64%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_with_different_modes  PASSED [ 71%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_with_different_widths PASSED [ 78%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_with_different_depths PASSED [ 85%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_loss_function        PASSED [ 92%]
deepchem/models/torch_models/tests/test_fno_npu.py::test_fno_reload               PASSED [100%]

================== 14 passed, 20 warnings in 64.12s (0:01:04) ==================

5. 实现细节

5.1 关键适配步骤

步骤说明
1. 复数 einsum 算子适配SpectralConv.forward 中复数 einsum 在 NPU 上不支持,需分解为实部/虚部实数 einsum
2. rdkit 导入时序修复conftest.py 中 rdkit 必须先于 torch 加载,否则 C 扩展 ABI 冲突 segfault
3. Python 依赖补齐安装 tqdm、transformers、pandas、scikit-learn、rdkit(deepchem import 链所需)
4. NPU 测试覆盖新增 test_fno_npu.py,将 FNO/FNOBlock(纯 nn.Module)测试显式上 NPU 并断言设备
5. NPU 设备绑定测试脚本内 torch.npu.set_device(0) 绑定单卡

5.2 适配要点

  • 复数 einsum 分解为必选项:SpectralConv 的核心计算 torch.einsum("b i ..., i o ... -> b o ...", x_ft, weights) 中 x_ft 与 weights 均为 complex64。einsum 内部落到 aclnnBatchMatMul,该算子不支持 complex64 输入(报错 code 161002)。PyTorch CUDA 后端靠 cuBLAS 原生复数 GEMM(cublasCgemm)支持,NPU 无对应能力。适配方案为将 1 次复数 einsum 分解为 4 次实数 einsum,基于复数乘法公式 Re(z·w)=Re(z)·Re(w)−Im(z)·Im(w),Im(z·w)=Re(z)·Im(w)+Im(z)·Re(w),NPU 实数 bmm 原生支持。

  • rdkit 必须先于 torch 加载:deepchem import 链中 graph_utils.py 先导入 torch,poly_wd_graph_utils.py 后导入 rdkit.Chem。torch 先于 rdkit 加载会导致 C 扩展 ABI 冲突 segfault。根目录 conftest.py 需使用确定性导入(非 try/except)确保 rdkit 在 pytest 收集阶段最先加载。

  • deepchem-ascend 已封装为二进制包,无需手工修改 DeepChem 源码(SpectralConv 修复已含在源码 layers.py 中)。

  • FNO/FNOBlock 需显式设备迁移:FNO 和 FNOBlock 是纯 nn.Module,不会自动上 NPU。测试中需 .to(npu_device) 并断言 y.device.type == 'npu'。FNOModel 继承 TorchModel,__init__ 中已自动检测并迁移到 NPU。

  • 镜像内 PyTorch 为 CPU 版(2.7.1+cpu),NPU 算力通过 torch_npu 2.7.1.post4 提供,不要替换为 GPU 版 PyTorch。

5.3 修改文件清单

文件改动类型改动内容
deepchem/models/torch_models/layers.py:9583-9592修改复数 einsum 分解为 4 次实数 einsum(+9/-2 行)
conftest.py:7修改rdkit 改为确定性导入(+1/-4 行)
deepchem/models/torch_models/tests/test_fno_npu.py新增14 个 NPU 测试(合并自 test_fno.py + NPU 覆盖)

5.4 核心代码修改

修改点 1:SpectralConv.forward 复数 einsum 分解(layers.py:9583-9592)

# -------------------- 原代码 --------------------
        idx = (slice(None), slice(None)) + slices
        out_ft[idx] = torch.einsum("b i ... , i o ... -> b o ...", x_ft[idx],
                                   self.weights)

        x_out = torch.fft.irfftn(out_ft,
                                 s=x.shape[2:],
                                 dim=tuple(range(2, x.ndim))).real
        return x_out + self.bias

# -------------------- 修改后 --------------------
        idx = (slice(None), slice(None)) + slices
        x_slice_r, x_slice_i = x_ft[idx].real, x_ft[idx].imag
        w_r, w_i = self.weights.real, self.weights.imag
        out_r = torch.einsum("b i ... , i o ... -> b o ...", x_slice_r,
                             w_r) - torch.einsum("b i ... , i o ... -> b o ...",
                                                 x_slice_i, w_i)
        out_i = torch.einsum("b i ... , i o ... -> b o ...", x_slice_r,
                             w_i) + torch.einsum("b i ... , i o ... -> b o ...",
                                                 x_slice_i, w_r)
        out_ft[idx] = torch.complex(out_r, out_i)

        x_out = torch.fft.irfftn(out_ft,
                                 s=x.shape[2:],
                                 dim=tuple(range(2, x.ndim))).real
        return x_out + self.bias

修改点 2:conftest.py rdkit 确定性导入(conftest.py:7)

# -------------------- 原代码 --------------------
"""Pytest conftest for NPU environment.

Preloads rdkit.Chem before torch_npu to avoid a C extension ABI conflict
that causes a segfault when torch_npu is imported before rdkit.Chem.
The order rdkit -> torch_npu is safe; the reverse crashes.
"""
try:
    from rdkit import Chem  # noqa: F401
except ImportError:
    pass

# -------------------- 修改后 --------------------
"""Pytest conftest for NPU environment.

Preloads rdkit.Chem before torch_npu to avoid a C extension ABI conflict
that causes a segfault when torch_npu is imported before rdkit.Chem.
The order rdkit -> torch_npu is safe; the reverse crashes.
"""
from rdkit import Chem  # noqa: F401  must be imported before torch to avoid segfault

修改点 3:新增 test_fno_npu.py(完整文件)

# -------------------- 新增文件 --------------------
from rdkit import Chem  # noqa: F401  must be imported before torch to avoid segfault
import pytest
import deepchem as dc
import tempfile

try:
    import torch
    import torch_npu
    has_torch = True
except (ModuleNotFoundError, ImportError):
    has_torch = False

torch.manual_seed(0)

npu_device = 'npu:0' if has_torch else 'cpu'
if has_torch:
    torch.npu.set_device(0)


@pytest.mark.torch
def test_fno_block_construction():
    """
    Test if FNOBlock can be constructed in 1D, 2D, and 3D.
    """
    from deepchem.models.torch_models.fno import FNOBlock
    block = FNOBlock(width=32, modes=8, dims=1)
    assert block is not None, "1D FNO Block construction failed"

    block = FNOBlock(width=32, modes=8, dims=2)
    assert block is not None, "2D FNO Block construction failed"

    block = FNOBlock(width=32, modes=8, dims=3)
    assert block is not None, "3D FNO Block construction failed"


@pytest.mark.torch
def test_fno_block_forward():
    """
    Test if FNOBlock can be forward-passed in 2D on NPU, without any errors.
    """
    from deepchem.models.torch_models.fno import FNOBlock
    block = FNOBlock(width=32, modes=8, dims=2).to(npu_device)
    x = torch.randn(100, 32, 100, 100, device=npu_device)
    y = block(x)
    assert y.shape == (100, 32, 100, 100)
    assert y.device.type == 'npu', "Output is not on NPU"


@pytest.mark.torch
def test_fno_base_construction():
    """
    Test if FNO can be constructed in 1D, 2D, and 3D.
    """
    from deepchem.models.torch_models.fno import FNO
    model = FNO(in_channels=1, out_channels=1, modes=8, width=32, dims=2)
    assert model is not None, "FNO base model construction failed"


@pytest.mark.torch
def test_fno_base_forward():
    """
    Test if FNO can be forward-passed in 2D on NPU, without any errors.
    """
    from deepchem.models.torch_models.fno import FNO
    model = FNO(in_channels=1, out_channels=1, modes=8, width=32, dims=2).to(npu_device)
    x = torch.randn(100, 1, 100, 100, device=npu_device)
    y = model(x)
    assert y.shape == (100, 1, 100, 100)
    assert y.device.type == 'npu', "Output is not on NPU"


@pytest.mark.torch
def test_fno_base_meshgrids():
    """
    Test if meshgrids are properly generated on NPU.
    """
    from deepchem.models.torch_models.fno import FNO
    model = FNO(in_channels=1, out_channels=1, modes=8, width=32, dims=2).to(npu_device)
    x = torch.randn(100, 1, 100, 100, device=npu_device)
    meshgrid = model._generate_meshgrid(x)
    assert meshgrid.shape == (100, 2, 100, 100)
    assert meshgrid.device.type == 'npu', "Meshgrid is not on NPU"


@pytest.mark.torch
def test_fno_construction():
    """Test that FNO Model can be constructed without crash."""
    from deepchem.models.torch_models import FNOModel

    model_1d = FNOModel(in_channels=1,
                        out_channels=1,
                        modes=8,
                        width=32,
                        dims=1,
                        depth=2)
    assert model_1d is not None

    model_2d = FNOModel(in_channels=2,
                        out_channels=3,
                        modes=8,
                        width=64,
                        dims=2,
                        depth=3)
    assert model_2d is not None

    model_3d = FNOModel(in_channels=3,
                        out_channels=1,
                        modes=4,
                        width=32,
                        dims=3,
                        depth=2)
    assert model_3d is not None


@pytest.mark.torch
def test_fno_overfit():
    """Test that FNO model can overfit simple data."""
    from deepchem.models.torch_models import FNOModel

    model = FNOModel(in_channels=1,
                     out_channels=1,
                     modes=8,
                     width=128,
                     dims=1,
                     depth=4)
    X = torch.randn(10, 1, 32)
    y = X  # Identity mapping
    dataset = dc.data.NumpyDataset(X=X, y=y)
    loss = model.fit(dataset, nb_epoch=200)
    assert loss < 1e-1, "Model can't overfit"


@pytest.mark.torch
def test_fno_overfit_2d():
    """Test that 2D FNO model can overfit simple data."""
    from deepchem.models.torch_models import FNOModel

    model = FNOModel(in_channels=1,
                     out_channels=1,
                     modes=8,
                     width=64,
                     dims=2,
                     depth=3)
    X = torch.rand(10, 1, 32, 32)
    y = X
    dataset = dc.data.NumpyDataset(X=X, y=y)
    loss = model.fit(dataset, nb_epoch=200)
    assert loss < 1e-1, "2D Model can't overfit"


@pytest.mark.torch
def test_fno_prediction_shape():
    """Test that FNO predictions have correct shape."""
    from deepchem.models.torch_models import FNOModel

    model = FNOModel(in_channels=2,
                     out_channels=3,
                     modes=8,
                     width=32,
                     dims=1,
                     depth=2)
    X = torch.randn(10, 2, 50)
    y = torch.randn(10, 3, 50)
    dataset = dc.data.NumpyDataset(X=X, y=y)

    # Test prediction shape
    predictions = model.predict(dataset)
    assert predictions.shape == y.shape


@pytest.mark.torch
def test_fno_with_different_modes():
    """Test FNO with different numbers of modes."""
    from deepchem.models.torch_models import FNOModel

    X = torch.randn(10, 1, 32)
    y = torch.randn(10, 1, 32)
    dataset = dc.data.NumpyDataset(X=X, y=y)

    # Test with different mode counts
    for modes in [4, 8, 16]:
        model = FNOModel(in_channels=1,
                         out_channels=1,
                         modes=modes,
                         width=32,
                         dims=1,
                         depth=2)
        predictions = model.predict(dataset)
        assert predictions.shape == y.shape


@pytest.mark.torch
def test_fno_with_different_widths():
    """Test FNO with different widths."""
    from deepchem.models.torch_models import FNOModel

    X = torch.randn(10, 1, 32)
    y = torch.randn(10, 1, 32)
    dataset = dc.data.NumpyDataset(X=X, y=y)

    # Test with different widths
    for width in [16, 32, 64]:
        model = FNOModel(in_channels=1,
                         out_channels=1,
                         modes=8,
                         width=width,
                         dims=1,
                         depth=2)
        predictions = model.predict(dataset)
        assert predictions.shape == y.shape


@pytest.mark.torch
def test_fno_with_different_depths():
    """Test FNO with different depths."""
    from deepchem.models.torch_models import FNOModel

    X = torch.randn(10, 1, 32)
    y = torch.randn(10, 1, 32)
    dataset = dc.data.NumpyDataset(X=X, y=y)

    # Test with different depths
    for depth in [1, 2, 4, 6]:
        model = FNOModel(in_channels=1,
                         out_channels=1,
                         modes=8,
                         width=32,
                         dims=1,
                         depth=depth)
        model.fit(dataset, nb_epoch=5)
        predictions = model.predict(dataset)
        assert predictions.shape == y.shape


@pytest.mark.torch
def test_fno_loss_function():
    """Test that FNO loss function works correctly."""
    from deepchem.models.torch_models import FNOModel

    model = FNOModel(in_channels=1,
                     out_channels=1,
                     modes=8,
                     width=32,
                     dims=1,
                     depth=2)

    # Test loss function directly
    # Outputs and labels should have shape (batch, channels, spatial_dims)
    outputs = [torch.randn(10, 1, 32)]
    labels = [torch.randn(10, 1, 32)]

    loss_value = model._loss_fn(outputs, labels)
    assert isinstance(loss_value, torch.Tensor)
    assert loss_value.item() >= 0.0  # MSE loss should be non-negative


@pytest.mark.torch
def test_fno_reload():
    """Test that FNO model can be reloaded."""
    from deepchem.models.torch_models import FNOModel
    import numpy as np

    np.random.seed(123)
    torch.manual_seed(123)

    n_samples = 10
    n_features = 32
    X = torch.randn(n_samples, 1, n_features)
    y = torch.randn(n_samples, 1, n_features)
    dataset = dc.data.NumpyDataset(X=X, y=y)

    model_dir = tempfile.mkdtemp()
    orig_model = FNOModel(in_channels=1,
                          out_channels=1,
                          modes=8,
                          width=32,
                          dims=1,
                          depth=2,
                          model_dir=model_dir)
    orig_model.fit(dataset, nb_epoch=5)

    reloaded_model = FNOModel(in_channels=1,
                              out_channels=1,
                              modes=8,
                              width=32,
                              dims=1,
                              depth=2,
                              model_dir=model_dir)
    reloaded_model.restore()

    X_new = torch.randn(n_samples, 1, n_features)
    orig_preds = orig_model.predict_on_batch(X_new)
    reloaded_preds = reloaded_model.predict_on_batch(X_new)

    assert np.all(orig_preds == reloaded_preds), "Predictions are not the same"

6. 测试结果

6.1 测试环境

  • 设备:Atlas 800T A2(单卡)
  • 镜像:torch-npu:2.7.1.post4-910b-openeuler24.03-py3.11
  • 框架:PyTorch 2.7.1+cpu + torch_npu 2.7.1.post4 + CANN 9.0.0

6.2 功能测试结果

测试项验收标准测试数结果
FNOBlock 构造1/2/3D 构造无异常1PASS
FNOBlock 前向NPU 上输出 shape 正确 + device=npu1PASS
FNO 构造构造无异常1PASS
FNO 前向NPU 上输出 shape 正确 + device=npu1PASS
FNO 位置编码NPU 上网格 shape 正确 + device=npu1PASS
FNOModel 构造1/2/3D 多配置构造1PASS
FNO 过拟合 1D200 epoch 后 loss < 0.11PASS
FNO 过拟合 2D200 epoch 后 loss < 0.11PASS
FNO 预测 shape多通道预测 shape 正确1PASS
超参扫描 modesmodes∈{4,8,16} 均通过1PASS
超参扫描 widthswidth∈{16,32,64} 均通过1PASS
超参扫描 depthsdepth∈{1,2,4,6} 均通过1PASS
损失函数_loss_fn 返回非负 tensor1PASS
模型重载保存/加载后预测一致1PASS
合计1414 PASS

6.3 精度结果(NPU vs CPU 数值一致性)

测试项max_abs_err阈值结果
SpectralConv 1D2.38e-07< 1e-3PASS
SpectralConv 2D1.19e-07< 1e-3PASS
SpectralConv 3D1.19e-07< 1e-3PASS
FNOBlock 1D4.37e-04< 1e-3PASS
FNOBlock 2D4.24e-04< 1e-3PASS
FNOBlock 3D4.21e-04< 1e-3PASS
FNO 1D1.06e-05< 1e-3PASS
FNO 2D1.50e-05< 1e-3PASS
FNO 3D1.03e-05< 1e-3PASS
FNO 2D + positional_encoding9.76e-06< 1e-3PASS
Backward gradient 1D3.85e-06< 1e-3PASS
合计11 PASS / 11

6.4 性能结果(NPU vs CPU)

测试项参数量NPU 前向(ms)NPU 前向+反向(ms)CPU 前向(ms)加速比
SpectralConv 1D5,1521.633.60——
SpectralConv 2D40,9924.5625.0092.1520.2x
SpectralConv 3D12,3044.4632.33——
FNOBlock 1D6,2081.793.44——
FNOBlock 2D42,0484.1725.74——
FNOBlock 3D12,5764.8233.80——
FNO 1D (depth=4)29,2178.0924.79——
FNO 2D (depth=4)172,57716.82205.03468.5827.9x
FNO 3D (depth=2)104,99311.93225.76——
FNO 2D large (depth=4, w=64)1,410,11345.74757.58——

7. FAQ

Q1:运行时报 RuntimeError: call aclnnBatchMatMul failed, error code is 161002? A:SpectralConv 中复数 einsum 未适配。需修改 layers.py:9583-9592,将复数 einsum 分解为实部/虚部 4 次实数 einsum。详见 §5.4。

Q2:import deepchem 时 segfault(core dumped)? A:rdkit 未在 torch 之前加载,导致 C 扩展 ABI 冲突。需在 conftest.py 顶部添加 from rdkit import Chem,且不能用 try/except(必须确定性导入)。详见 §5.2。

Q3:报 ImportError: These classes require PyTorch to be installed.? A:实际不是 PyTorch 缺失,而是 tqdm 缺失导致 layers.py:15 的 except ModuleNotFoundError 误捕获。执行 pip install tqdm 即可。

Q4:报 ModuleNotFoundError: No module named 'transformers'? A:deepchem import 链中 lstm_generator_models.py 依赖 transformers,FNO 本身不需要。执行 pip install transformers 即可。

Q5:FNO/FNOBlock 前向测试在 CPU 上"假通过"? A:FNO 和 FNOBlock 是纯 nn.Module,不会自动上 NPU。需在测试中显式 .to('npu:0') 并断言 y.device.type == 'npu'。FNOModel 继承 TorchModel,会自动检测并迁移到 NPU,无需手动处理。