PAYATHON 2026

SciPy spsolve/SuperLU 内存分配失败:有足够 RAM 仍报 SUPERLU_MALLOC

数据小陈

结论:先别继续加内存。SUPERLU_MALLOC fails ... intCalloc() 说明 SuperLU 内部的内存分配返回了 NULL,但这并不一定意味着物理内存已经用完。N=5000 时状态数约为 (N+3)(N+4)//2 - 3 = 12,517,503。直接做 LU 分解产生的填充,以及 SuperLU 内部使用的整数数组,都会比稀疏矩阵本身大得多。还要检查 32 位索引、cgroup/ulimit、overcommit,以及单次分配是否过大。可以尝试迭代法、外部直接求解器,或者先把矩阵构造优化掉一大块,同时确认索引位数。

1. 先确认规模,再查资源限制

先把矩阵规模打印出来,确认 nstates 和 A.nnz,同时检查进程限制:

N = 5000
M = N + 2
nstates = (M + 1) * (M + 2) // 2 - 3
print(nstates)  # 12517503
print(A.shape, A.nnz, A.dtype)
ulimit -a
cat /proc/sys/vm/overcommit_memory
cat /sys/fs/cgroup/memory.max 2>/dev/null || true
free -h

如果 ulimit -v 或 cgroup 的内存上限较小,free 即使显示还有很多空闲内存,malloc 仍可能失败。intCalloc() 失败也可能是单次请求太大,或者地址空间碎片造成的。

2. 不要用 lil_matrix 逐个元素构造

原代码用 lil_matrix 加 Python 字典保存 1250 万个状态,内存开销很大。可以改用 COO 三元组直接构造,并用二维整数数组代替 state -> index 字典。关键改动如下:

import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import spsolve

def fixation_probability_coo(N):
    M = N + 2
    idx = -np.ones((M + 1, M + 1), dtype=np.int32)
    states = []
    k = 0
    for r in range(M + 1):
        for b in range(M - r + 1):
            g = M - r - b
            if (r == M and b == 0 and g == 0): continue
            if (r == 0 and b == M and g == 0): continue
            if (r == 0 and b == 0 and g == M): continue
            idx[r, b] = k
            states.append((r, b, g))
            k += 1

    nstates = k
    rows, cols, data = [], [], []
    rhs = np.zeros(nstates)

    def boundary_value(r, b, g):
        if r == M and b == 0 and g == 0: return 1.0
        if r == 0 and b == M and g == 0: return 0.0
        if r == 0 and b == 0 and g == M: return 0.0
        if b == 0: return 0.0
        if g == 0: return 1.0
        if r == 0: return 0.0
        return None

    for i, (r, b, g) in enumerate(states):
        w1 = r * b
        w2 = b * g
        w3 = g * r
        rows.append(i); cols.append(i); data.append(w1 + w2 + w3)
        for weight, nr, nb, ng in ((w1, r+1, b-1, g), (w2, r, b+1, g-1), (w3, r-1, b, g+1)):
            if weight == 0: continue
            value = boundary_value(nr, nb, ng)
            if value is not None:
                rhs[i] += weight * value
            else:
                j = idx[nr, nb]
                rows.append(i); cols.append(j); data.append(-weight)

    A = coo_matrix((data, (rows, cols)), shape=(nstates, nstates)).tocsr()
    x = spsolve(A, rhs)
    return x[idx[1, 1]]

g 由 M - r - b 唯一确定,所以 idx 只存 (r,b) 就够了。这个改动主要是降低构造阶段的内存峰值,并不能保证 SuperLU 一定能完成 N=5000 的 LU 分解。

3. 先试迭代法

如果直接法的填充太大,可以先试 bicgstab 或 gmres,配合 ILU 预条件。迭代法一般内存占用低很多,但能不能收敛取决于矩阵条件数:

from scipy.sparse.linalg import bicgstab, spilu, LinearOperator

A = A.tocsr()
ilu = spilu(A, drop_tol=1e-4, fill_factor=10)
Mpre = LinearOperator(A.shape, ilu.solve)
x, info = bicgstab(A, rhs, rtol=1e-8, atol=0.0, maxiter=10000, M=Mpre)
print(info)
print(np.linalg.norm(A @ x - rhs) / np.linalg.norm(rhs))

spilu 本身也可能占不少内存,fill_factor 要从小值开始试。如果迭代法不收敛,再考虑外部直接求解器。

4. 换外部直接求解器

SciPy 的 spsolve 默认使用 SuperLU。可以试试 scikit-umfpack 提供的 UMFPACK 接口:

from scikits.umfpack import spsolve as umfpack_spsolve
x = umfpack_spsolve(A, rhs)

如果问题更大,可以考虑 MUMPS、STRUMPACK、PaStiX 或 PETSc 的并行直接求解器。它们通常支持 64 位索引、更好的排序和分布式内存,但安装和 API 成本更高。换库之前,先确认 Python 和 SciPy 都是 64 位版本,并检查 A.indices.dtype、A.indptr.dtype 是否为 int32。

注意事项

  • 加 RAM 不一定能解决 SUPERLU_MALLOC。先确认有没有 cgroup、ulimit 或单次分配上限。
  • N=5000 时 Python 对象本身就很占内存,states 列表和字典应尽量换成整数索引。
  • 直接法失败时,可以先减小 N,看收敛性和内存曲线,不要一上来就换更大的机器。
  • 如果最终只需要 P_R(1,1,N),可以研究利用马尔可夫链结构或稀疏迭代求解,不必完整做 LU 分解。

备注:内容仅供参考。