You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Pybind调用LAPACK时程序崩溃问题排查

问题:LAPACKE_dgetrf在Pybind封装后调用崩溃,替换为dgetrf2恢复正常

我实现了一个基于LAPACK的C函数用于计算矩阵的对数行列式,该函数在C单元测试中运行正常,但使用Pybind封装后在Python中调用相同矩阵时,程序在执行info = LAPACKE_dgetrf(LAPACK_COL_MAJOR, n, n, A, lda, ipiv);语句时崩溃。

添加输出日志后,发现Python调用时程序在执行上述语句后停止输出。后续将dgetrf替换为dgetrf2后程序恢复正常,想明确以下几点:

  • C++与Python调用场景下的差异
  • 导致崩溃的具体原因
  • 是否是所使用的LAPACKE C wrapper存在bug

相关C++代码

inline double logdet_chol(const Eigen::MatrixXd& M) {
    int n = M.rows();
    int lda = n;
    int info = 0;

    double* A = new double[n * n];
    std::copy(M.data(), M.data() + n * n, A);

    // Cholesky decomposition
    info = LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', n, A, lda);
    if (info != 0) {
        // If Cholesky decomposition fails, use LU decomposition (LAPACKE_dgetrf)
        int* ipiv = new int[n];
        std::fill(ipiv, ipiv + n, 0);
        std::copy(M.data(), M.data() + n * n, A);

        info = LAPACKE_dgetrf(LAPACK_COL_MAJOR, n, n, A, lda, ipiv);

        if (info != 0) {
            delete[] ipiv;
            throw std::runtime_error("LU decomposition failed.");
        }

        double ld = 0.0;
        double sign = 1.0;
        for (int i = 0; i < n; ++i) {
            ld += std::log(std::abs(A[i * lda + i]));
            if (A[i * lda + i] < 0) {
                sign = -sign;
            }
        }

        // Compute the determinant of the permutation matrix
        for (int i = 0; i < n; ++i) {
            if (ipiv[i] != i + 1) {
                sign = -sign;
            }
        }

        delete[] ipiv;

        if (sign <= 0) {
            return -std::numeric_limits<double>::infinity();
        }

        return ld;
    }
    // If Cholesky decomposition is successful, compute the log determinant
    double ld = 0.0;
    for (int i = 0; i < n; ++i) {
        ld += std::log(A[i * lda + i]);
    }

    return 2.0 * ld;
}

测试矩阵

np.diag([1089.942113770775, 1010.096696063498, 58.66178651250262, 5661.020957489456, -1589555826.24471, -3799865302.243693, -162987547.4735685, -1771081.02947091, 255.3627654232152, 151.2319507163488])

内容的提问来源于stack exchange,提问作者Lu Ezra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 13:15:01