用 f2py 包装 LAPACK 子程序并自动生成 NumPy 接口

解读

国内互联网大厂、量化私募、AI 芯片公司面试时,经常把“能不能把遗留 Fortran 库无缝接入 Python 生态”作为区分“只会调包”与“能造轮子”的分水岭。
题目表面问 f2py,实则考察四点:

  1. 是否理解 NumPy 的内存模型与 dtype 对齐;
  2. 是否熟悉 LAPACK 的列主序、隐藏参数(work、lwork、info)与函数命名规则(sgesv、dgesv、cgesv、zgesv);
  3. 能否写出一次性通过编译的 .pyf 签名文件,并解决常见“段错误 / 非法指令”问题;
  4. 是否具备自动化思维:让后续新增子程序无需手工改接口,CI 可直接生成 wheel。
    面试官会层层追问:如何跨平台(Windows Intel-Fortran + Linux GCC)编译?如何做到线程安全?如何与 OpenBLAS/MKL 共存?如何发布到内部 PyPI?回答必须给出工程级方案,而非玩具级 demo。

知识点

  1. f2py 工作流:扫描 Fortran 源码 → 生成 .pyf 签名 → 编译成 .pyd/.so → 生成 numpy.ufunc 或 numpy.ctypeslib 封装。
  2. LAPACK 调用惯例:
    • 所有参数传指针;
    • 数组列主序,与 NumPy C-order 相反,需转置或设置 order='F';
    • 字符参数需用单字符 bytes(b'N'、b'U');
    • work 数组大小由 query 调用(lwork=-1)先获取最优值。
  3. 签名文件语法:intent(in,out,inout,copy,hide), depend(), check(),以及如何用 <ftype> 映射 {real,double precision,complex*16} → {float32,float64,complex128}。
  4. 构建系统:numpy.distutils 已废弃,推荐 meson-python + f2py 后端,或 scikit-build-core + CMake 调用 f2py;国内公司内网需配置私有仓库镜像。
  5. ABI 与线程:
    • 静态链接 OpenBLAS 时,export OPENBLAS_NUM_THREADS=1 避免与 Python 端 multiprocessing 死锁;
    • 使用 ILP64 接口时,需在 .pyf 里显式声明 integer*8,并在 meson 里加 -Duse-ilp64=true。
  6. 自动化脚本:
    • 用 clang-format + f2py-crackfortran 扫描头文件,自动生成 .pyf;
    • 用 cog / jinja2 模板渲染,把 Fortran 的 parameter(n=128) 映射到 Python 的 init.py 常量;
    • 在 GitLab CI 里跑 auditwheel repair,生成 manylinux_2_28_x86_64.whl,推送到内部 devpi。

答案

以下给出一个可直接落地的“工程模板”,以双精度 LU 分解 dgetrf + dgetrs 为例,演示如何“一键生成 NumPy 接口”并解决国内常见坑。

步骤 1:目录结构
lapack_f2py/
├─ src/
│ ├─ dgetrf.f (从 Netlib 下载,不做任何修改)
│ └─ dgetrs.f
├─ signature/
│ └─ lapack.pyf.j2 (jinja2 模板,后面用脚本渲染)
├─ scripts/
│ └─ gen_pyf.py (自动生成签名)
├─ pyproject.toml
└─ README.md

步骤 2:自动化签名生成(scripts/gen_pyf.py 节选)

import subprocess, re, jinja2
from pathlib import Path

# 1. 用 f2py 扫描源码,生成原始签名
raw = subprocess.check_output(
    ['python', '-m', 'numpy.f2py', 'src/dgetrf.f', '-h', '-m', 'lapack'],
    text=True, stderr=subprocess.STDOUT)

# 2. 正则提取参数列表
args = re.findall(r'.*intent\(.*\).*:: (\w+)', raw)

# 3. 渲染 jinja2 模板,隐藏 work 数组,设置 order='F'
tmpl = jinja2.Template(Path('signature/lapack.pyf.j2').read_text())
sig = tmpl.render(args=args, f2py_raw=raw)
Path('lapack.pyf').write_text(sig)

步骤 3:签名模板(signature/lapack.pyf.j2 节选)

python module lapack
  interface
    subroutine dgetrf(m,n,a,lda,ipiv,info)
      intent(c) dgetrf
      intent(callback, hide) :: mem_check
      integer intent(hide), depend(a) :: m = shape(a,0)
      integer intent(hide), depend(a) :: n = shape(a,1)
      double precision intent(inout,copy,order='F') :: a(m,n)
      integer intent(hide), depend(a) :: lda = max(1,m)
      integer intent(out) :: ipiv(min(m,n))
      integer intent(out) :: info
    end subroutine
  end interface
end python module

要点:

  • copy,order='F' 让 f2py 自动把 C-order 输入转列主序,返回时再拷回,避免用户手动转置;
  • 隐藏 lda,用 depend 自动推断;
  • ipiv 维度用 min(m,n) 符合 LAPACK 规范。

步骤 4:构建脚本(pyproject.toml,使用 meson-python)

[build-system]
requires = ["meson-python>=0.13", "numpy>=1.24"]
build-backend = "mesonpy"

[project]
name = "lapack_f2py"
version = "0.1.0"
dependencies = ["numpy>=1.24"]

[tool.meson-python.args]
setup = ['-Dlapack=openblas']

meson.build 节选:

project('lapack_f2py', 'c', 'fortran',
  default_options: ['warning_level=2', 'buildtype=release'])

openblas_dep = dependency('openblas', required: true)
py_mod = import('python')
py = py_mod.find_installation(pure: false)

py.extension_module('lapack',
  ['lapack.pyf', 'src/dgetrf.f', 'src/dgetrs.f'],
  dependencies: openblas_dep,
  install: true,
  subdir: 'lapack_f2py',
  fortran_args: ['-fPIC', '-fopenmp'],
  link_args: ['-fopenmp'])

步骤 5:Python 端友好封装(lapack_f2py/init.py)

import numpy as _np
from . import _lapack  # f2py 生成的 C 扩展

def lu_solve(a, b):
    a = _np.asarray(a, dtype=float, order='F')
    b = _np.asarray(b, dtype=float, order='F')
    if a.shape[0] != a.shape[1]:
        raise ValueError('a must be square')
    ipiv = _np.empty(min(a.shape), dtype=_np.intc)
    info = _lapack.dgetrf(a, ipiv)
    if info < 0:
        raise ValueError(f'非法参数: {-info}')
    x = b.copy(order='F')
    _lapack.dgetrs(a, ipiv, x, trans='N')
    return x

这样用户只需 from lapack_f2py import lu_solve; x = lu_solve(A, b),无需关心列主序、work 数组、info 检查。

步骤 6:国内镜像与 CI

  • 在 GitLab CI 里使用 registry.gitlab.com/openblas/openblas:v0.3.26-manylinux_2_28 镜像;
  • 设置 PIP_INDEX_URL=https://pypi.douban.com/simple 加速;
  • cibuildwheel 自动打 manylinux wheel,结束后 twine upload --repository-url $INTERNAL_PYPI。

常见坑速查表:

  1. Windows 下 Intel oneAPI Fortran 与 MSVC ABI 不匹配 → 用 ifort /names:lowercase /assume:underscore 统一符号;
  2. macOS arm64 出现 “Illegal instruction” → 指定 -target arm64-apple-macos11 且关闭 -mavx;
  3. 与 pytorch 同时 import 时 OpenBLAS 死锁 → 在 __init__.py 顶部 os.environ['OPENBLAS_NUM_THREADS'] = '1';
  4. 64 位整数接口混淆 → 在 .pyf 里统一 integer*8,并在 meson 加 -Dinterface64=true。

拓展思考

  1. 零拷贝策略:当数组已经是 order='F' 且 dtype=float64 时,如何跳过 f2py 的 copy 层?—— 在签名里用 intent(inout) 而非 copy,并暴露 a.flags.f_contiguous 检查,提供 lu_solve_inplace 接口。
  2. 批处理与广播:LAPACK 本身不支持批处理,如何用 f2py 生成“自动 fortran 循环”封装,使得输入 shape=(batch,n,n) 的数组一次性求解?—— 可在 Fortran 层写 thin wrapper,用 !$omp parallel do,再在 .pyf 里声明 depend(batch)。
  3. 与 CUDA 生态共存:公司内已有 cuSolver。如何做到运行时根据数组大小自动选择 cuSolver(>2048)或 LAPACK(<=2048)?—— 在 Python 层用 __array_ufunc__ 协议,把选择逻辑封装到 BackendSelector 类,实现无缝切换。
  4. 合规发布:LAPACK 许可证为 BSD,但 OpenBLAS 部分内核含 GPL 汇编,如何确保 wheel 合规?—— 采用 Netlib REFERENCE LAPACK + BLIS 替代 OpenBLAS,并在 wheel 标签里标注 *-blis 后缀,避免法务风险。