Enzyme icon indicating copy to clipboard operation
Enzyme copied to clipboard

Compilation error differentiating Eigen::Matrix::inverse() with Enzyme forward-mode when matrix size ≥ 4

Open shadow-orange41 opened this issue 10 months ago • 10 comments

When using Enzyme’s forward-mode API (__enzyme_fwddiff) to compute gradients through Eigen::Matrix<double, N, N>::inverse() for fixed-size matrices, compilation fails when N >= 4 (reproduced with N = 4). The same code compiles and runs correctly for N = 2 and N = 3.

Minimal reproducible example
#include <iostream>
#include <enzyme/enzyme>
#include <Eigen/Dense>
#include <vector>
#include <random>

int enzyme_dup;
int enzyme_dupnoneed;
int enzyme_out;
int enzyme_const;

template <typename return_type, typename... T>
return_type __enzyme_fwddiff(void*, T...);

template <typename return_type, typename... T>
return_type __enzyme_autodiff(void*, T...);

const size_t input_size = 2;
const size_t matrix_size = 4; // change to 2 or 3 works fine

using Matrix = Eigen::Matrix<double, matrix_size, matrix_size>;

void enzyme_func_matrix(Matrix* mats, double& sol) {
    Matrix M0;
    M0 = mats[0].inverse();
    sol = M0.sum();
}

template <auto F>
void compute_J_matrix_forward(
    std::vector<std::vector<std::vector<double>>> inputs,
    std::vector<std::vector<std::vector<double>>>& J_matrix_forward
) {
    J_matrix_forward.assign(input_size,
        std::vector<std::vector<double>>(
            matrix_size,
            std::vector<double>(matrix_size, 0.0)
        )
    );

    std::vector<Matrix> mats(input_size), dmats(input_size);

    for (size_t mat_idx = 0; mat_idx < input_size; mat_idx++) {
        for (size_t i = 0; i < matrix_size; i++) {
            for (size_t j = 0; j < matrix_size; j++) {
                mats[mat_idx](i, j) = inputs[mat_idx][i][j];
            }
        }
    }

    auto zero_gradients = [&]() {
        for (auto& M : dmats) {
            for (int i = 0; i < (int)matrix_size; i++) {
                for (int j = 0; j < (int)matrix_size; j++) {
                    M(i, j) = 0.0;
                }
            }
        }
    };

    double result, dresult;
    for (size_t mat_idx = 0; mat_idx < input_size; mat_idx++) {
        for (size_t i = 0; i < matrix_size; i++) {
            for (size_t j = 0; j < matrix_size; j++) {
                zero_gradients();
                dmats[mat_idx](i, j) = 1.0;

                __enzyme_fwddiff<void>((void*)F,
                    enzyme_dup, mats.data(),  dmats.data(),
                    enzyme_dup, &result,     &dresult);

                J_matrix_forward[mat_idx][i][j] = dresult;
            }
        }
    }
}

void generate_inputs(size_t matrix_size, std::vector<std::vector<std::vector<double>>>& inputs) {
    inputs.assign(2,
        std::vector<std::vector<double>>(
            matrix_size,
            std::vector<double>(matrix_size)
        )
    );

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<double> dist(0.0, 1.0);

    for (auto& mat : inputs) {
        for (auto& row : mat) {
            for (auto& val : row) {
                val = dist(gen);
            }
        }
    }
}

int main() {
    std::vector<std::vector<std::vector<double>>> J_matrix_forward;
    std::vector<std::vector<std::vector<double>>> inputs;

    generate_inputs(matrix_size, inputs);
    compute_J_matrix_forward<enzyme_func_matrix>(inputs, J_matrix_forward);

    for (size_t input_idx = 0; input_idx < input_size; input_idx++) {
        for (size_t i = 0; i < matrix_size; i++) {
            for (size_t j = 0; j < matrix_size; j++) {
                std::cout << "J_matrix_forward[" << input_idx << "]["
                          << i << "][" << j << "] = "
                          << J_matrix_forward[input_idx][i][j] << "\n";
            }
        }
    }
    return 0;
}
Compilation error log
In file included from ./main.cpp:3:
In file included from ../../../build/debug/include/Eigen/Dense:1:
In file included from ../../../build/debug/include/Eigen/Core:205:
../../../build/debug/include/Eigen/src/Core/arch/SSE/PacketMath.h:423:103: error: Enzyme: ; Function Attrs: mustprogress noinline optnone willreturn uwtable
define linkonce_odr dso_local noundef <2 x double> @preprocess__ZN5Eigen8internal4pxorIDv2_dEET_RKS3_S5_(ptr noundef nonnull align 16 dereferenceable(16) %a, ptr noundef nonnull align 16 dereferenceable(16) %b) #31 !dbg !15509 {
entry:
  call void @llvm.dbg.value(metadata ptr %a, metadata !15510, metadata !DIExpression()), !dbg !15511
  call void @llvm.dbg.value(metadata ptr %b, metadata !15512, metadata !DIExpression()), !dbg !15511
  %0 = load <2 x double>, ptr %a, align 16, !dbg !15513
  %1 = load <2 x double>, ptr %b, align 16, !dbg !15514
  %2 = bitcast <2 x double> %0 to <2 x i64>, !dbg !15515
  %3 = bitcast <2 x double> %1 to <2 x i64>, !dbg !15515
  %xor.i = xor <2 x i64> %2, %3, !dbg !15515
  %4 = bitcast <2 x i64> %xor.i to <2 x double>, !dbg !15515
  ret <2 x double> %4, !dbg !15516
}

 constantarg[ptr %a] = 0 type: {[-1]:Pointer, [-1,-1]:Float@double} - vals: {}
 constantarg[ptr %b] = 0 type: {[-1]:Pointer} - vals: {}
 constantinst[  call void @llvm.dbg.value(metadata ptr %a, metadata !15510, metadata !DIExpression()), !dbg !15511] = 1 val:1 type: {}
 constantinst[  call void @llvm.dbg.value(metadata ptr %b, metadata !15512, metadata !DIExpression()), !dbg !15511] = 1 val:1 type: {}
 constantinst[  %0 = load <2 x double>, ptr %a, align 16, !dbg !7229] = 0 val:0 type: {[-1]:Float@double}
 constantinst[  %1 = load <2 x double>, ptr %b, align 16, !dbg !7230] = 0 val:0 type: {}
 constantinst[  %2 = bitcast <2 x double> %0 to <2 x i64>, !dbg !7231] = 0 val:0 type: {[-1]:Float@double}
 constantinst[  %3 = bitcast <2 x double> %1 to <2 x i64>, !dbg !7231] = 0 val:0 type: {}
 constantinst[  %xor.i = xor <2 x i64> %2, %3, !dbg !7231] = 0 val:0 type: {[-1]:Float@double}
 constantinst[  %4 = bitcast <2 x i64> %xor.i to <2 x double>, !dbg !7231] = 0 val:0 type: {[-1]:Float@double}
 constantinst[  ret <2 x double> %4, !dbg !7232] = 1 val:1 type: {}
cannot handle unknown binary operator:   %xor.i = xor <2 x i64> %2, %3, !dbg !7231

template<> EIGEN_STRONG_INLINE Packet2d pxor<Packet2d>(const Packet2d& a, const Packet2d& b) { return _mm_xor_pd(a,b); }
                                                                                                      ^
../../../build/debug/include/Eigen/src/Core/arch/SSE/PacketMath.h:423:103: error: Enzyme: ; Function Attrs: mustprogress noinline optnone willreturn uwtable
define linkonce_odr dso_local noundef <2 x double> @preprocess__ZN5Eigen8internal4pxorIDv2_dEET_RKS3_S5_(ptr noundef nonnull align 16 dereferenceable(16) %a, ptr noundef nonnull align 16 dereferenceable(16) %b) #31 !dbg !15509 {
entry:
  call void @llvm.dbg.value(metadata ptr %a, metadata !15510, metadata !DIExpression()), !dbg !15511
  call void @llvm.dbg.value(metadata ptr %b, metadata !15512, metadata !DIExpression()), !dbg !15511
  %0 = load <2 x double>, ptr %a, align 16, !dbg !15513
  %1 = load <2 x double>, ptr %b, align 16, !dbg !15514
  %2 = bitcast <2 x double> %0 to <2 x i64>, !dbg !15515
  %3 = bitcast <2 x double> %1 to <2 x i64>, !dbg !15515
  %xor.i = xor <2 x i64> %2, %3, !dbg !15515
  %4 = bitcast <2 x i64> %xor.i to <2 x double>, !dbg !15515
  ret <2 x double> %4, !dbg !15516
}

 constantarg[ptr %a] = 0 type: {[-1]:Pointer, [-1,-1]:Float@double} - vals: {}
 constantarg[ptr %b] = 0 type: {[-1]:Pointer, [-1,0]:Integer} - vals: {}
 constantinst[  call void @llvm.dbg.value(metadata ptr %a, metadata !15510, metadata !DIExpression()), !dbg !15511] = 1 val:1 type: {}
 constantinst[  call void @llvm.dbg.value(metadata ptr %b, metadata !15512, metadata !DIExpression()), !dbg !15511] = 1 val:1 type: {}
 constantinst[  %0 = load <2 x double>, ptr %a, align 16, !dbg !7229] = 0 val:0 type: {[-1]:Float@double}
 constantinst[  %1 = load <2 x double>, ptr %b, align 16, !dbg !7230] = 0 val:0 type: {[0]:Integer}
 constantinst[  %2 = bitcast <2 x double> %0 to <2 x i64>, !dbg !7231] = 0 val:0 type: {[-1]:Float@double}
 constantinst[  %3 = bitcast <2 x double> %1 to <2 x i64>, !dbg !7231] = 0 val:0 type: {[0]:Integer}
 constantinst[  %xor.i = xor <2 x i64> %2, %3, !dbg !7231] = 0 val:0 type: {[-1]:Float@double}
 constantinst[  %4 = bitcast <2 x i64> %xor.i to <2 x double>, !dbg !7231] = 0 val:0 type: {[-1]:Float@double}
 constantinst[  ret <2 x double> %4, !dbg !7232] = 1 val:1 type: {}
cannot handle unknown binary operator:   %xor.i = xor <2 x i64> %2, %3, !dbg !7231

2 errors generated.

shadow-orange41 avatar Jan 28 '26 21:01 shadow-orange41

@shadow-orange41 it looks like Eigen is using some sse instructions in the N>=4 case which enzyme cannot differentiate. maybe try defining -DEIGEN_DONT_VECTORIZE and see if that helps?

jeffpollock9 avatar Mar 17 '26 18:03 jeffpollock9

Thank you @jeffpollock9! I tried this flag -DEIGEN_DONT_VECTORIZE, now for N=4 it compiles, but still not for N>4. I wonder if there are other instructions that are not supported by Enzyme maybe?

shadow-orange41 avatar Mar 17 '26 20:03 shadow-orange41

Thank you @jeffpollock9! I tried this flag -DEIGEN_DONT_VECTORIZE, now for N=4 it compiles, but still not for N>4. I wonder if there are other instructions that are not supported by Enzyme maybe?

I'm really not sure sorry 😔 what's the error?

jeffpollock9 avatar Mar 17 '26 21:03 jeffpollock9

Oh no worries! I attached the error. Looks like this one is different from the error log I shared before. Btw, how do you know this?

it looks like Eigen is using some sse instructions in the N>=4 case which enzyme cannot differentiate.

Is it from the error message?

error_matrix_size_5.txt

shadow-orange41 avatar Mar 17 '26 23:03 shadow-orange41

@shadow-orange41 I was curious so tried some different decompositions from here but none work for me :(

#include <cstdio>
#include <Eigen/Dense>

template <typename T, typename... Args>
T __enzyme_autodiff(void*, Args...) noexcept;

inline int enzyme_out;

constexpr int N = 11;

using Matrix = Eigen::Matrix<double, N, N>;


double objective(const double x) {
    Matrix matrix = Matrix::Zero();
    for (int i = 0; i < N; ++i) {
        matrix(i, i) = 3.14 + i * x;
    }
    // return matrix.inverse().sum();
    return matrix.fullPivLu().solve(Matrix::Identity()).sum();
}

int main() {
    double x = 1.0;
    double f = objective(x);
    double g = __enzyme_autodiff<double>((void*)objective, enzyme_out, x);
    std::printf("x=%f, f=%f, g=%f\n", x, f, g);
    return 0;
}

regarding the SSE stuff, I noticed in your output:

../../../build/debug/include/Eigen/src/Core/arch/SSE/PacketMath.h:423:103: error: Enzyme: ; Function Attrs: mustprogress noinline optnone willreturn uwtable
define linkonce_odr dso_local noundef <2 x double> @preprocess__ZN5Eigen8internal4pxorIDv2_dEET_RKS3_S5_(ptr noundef nonnull align 16 dereferenceable(16) %a, ptr noundef nonnull align 16 dereferenceable(16) %b) #31 !dbg !15509 {

which looks like enzyme is struggling with doing some SSE thing with 2 128 bits (2 doubles).

If you find a good solution please let me know!

jeffpollock9 avatar Mar 18 '26 12:03 jeffpollock9

Thank you @jeffpollock9 for the help! @wsmoses would the developer team have time to look into this?

shadow-orange41 avatar Mar 18 '26 14:03 shadow-orange41

so the IR itself seems pretty non-differentiable, xor'ing two doubles seems like a pretty hazardous operation. Is there a reason why that instruction should be differentiable?

if not we may want to look at the context which calls this to figure out when it is still a fully differentiable fn

wsmoses avatar Mar 20 '26 00:03 wsmoses

error_matrix_size_5.txt

I agree that xor does not seem to be differentiable. It appears to be introduced by Eigen through SSE vectorization when matrix_size ≥ 4.

After following @jeffpollock9’s suggestion and adding the flag -DEIGEN_DONT_VECTORIZE, the code compiles successfully for matrix_size = 4. However, for matrix_size > 4, it still fails to compile, but now with different errors (attached below).

In the new errors, I see messages like:

cannot handle unknown binary operator: %add3 = add nsw i64 %call2, %col
cannot handle unknown binary operator: %inc = add nsw i32 %8, 1

    ++nb_transpositions;

These operations look like to be differentiable?

Partial compilation error log (matrix_size>4)
In file included from main.cpp:3:
In file included from ../../../build/debug/include/Eigen/Dense:2:
In file included from ../../../build/debug/include/Eigen/LU:29:
../../../build/debug/include/Eigen/src/LU/PartialPivLU.h:387:11: error: Enzyme: ; Function Attrs: mustprogress noinline optnone willreturn uwtable
define linkonce_odr dso_local noundef i64 

...

 constantinst[  %10 = select i1 %cmp68, i1 %cmp69, i1 false, !dbg !35898] = 1 val:1 type: {[-1]:Integer}
 constantinst[  %first_zero_pivot.3 = select i1 %10, i64 %sub, i64 %first_zero_pivot.0, !dbg !35899] = 1 val:1 type: {[-1]:Integer}
 constantinst[  call void @llvm.dbg.value(metadata i64 %first_zero_pivot.3, metadata !60602, metadata !DIExpression()), !dbg !60588] = 1 val:1 type: {}
 constantinst[  ret i64 %first_zero_pivot.3, !dbg !35900] = 1 val:1 type: {}
cannot handle unknown binary operator:   %inc = add nsw i32 %8, 1, !dbg !35854

          ++nb_transpositions;
          ^
In file included from main.cpp:3:
In file included from ../../../build/debug/include/Eigen/Dense:1:
In file included from ../../../build/debug/include/Eigen/Core:277:
../../../build/debug/include/Eigen/src/Core/CoreEvaluators.h:1123:73: error: Enzyme: ; Function Attrs: mustprogress noinline nounwind optnone willreturn uwtable
define linkonce_odr dso_local noundef double 
...

dereferenceable(8) %m_startCol) #33, !dbg !35800] = 0 val:0 type: {}
 constantinst[  %add3 = add nsw i64 %call2, %col, !dbg !35801] = 0 val:0 type: {}
 constantinst[  %call4 = call noundef double @_ZNK5Eigen8internal9evaluatorINS_14CwiseNullaryOpINS0_18scalar_identity_opIdEENS_6MatrixIdLi5ELi5ELi0ELi5ELi5EEEEEE5coeffIlEEdT_SA_(ptr noundef nonnull align 1 dereferenceable(2) %m_argImpl, i64 noundef %add, i64 noundef %add3) #33, !dbg !35802] = 0 val:0 type: {}
 constantinst[  ret double %call4, !dbg !35803] = 1 val:1 type: {}
cannot handle unknown binary operator:   %add3 = add nsw i64 %call2, %col, !dbg !35801

...
../../../build/debug/include/Eigen/src/Core/products/GeneralBlockPanelKernel.h:101:24: error: Enzyme: cannot compute with global variable that doesn't have marked shadow global
@_ZZN5Eigen8internal20manage_caching_sizesENS_6ActionEPlS2_S2_E12m_cacheSizes = linkonce_odr dso_local global %"struct.Eigen::internal::CacheSizes" zeroinitializer, comdat, align 8, !dbg !34382

    *l1 = m_cacheSizes.m_l1;
                       ^
error: Enzyme: cannot compute with global variable that doesn't have marked shadow global
@_ZZN5Eigen8internal20manage_caching_sizesENS_6ActionEPlS2_S2_E12m_cacheSizes = linkonce_odr dso_local global %"struct.Eigen::internal::CacheSizes" zeroinitializer, comdat, align 8, !dbg !34382

error: Enzyme: cannot compute with global variable that doesn't have marked shadow global
@_ZZN5Eigen8internal20manage_caching_sizesENS_6ActionEPlS2_S2_E12m_cacheSizes = linkonce_odr dso_local global %"struct.Eigen::internal::CacheSizes" zeroinitializer, comdat, align 8, !dbg !34382

13 errors generated.

shadow-orange41 avatar Mar 20 '26 15:03 shadow-orange41

@shadow-orange41 you may or may not like this, but I put this into claude code and it has made a workaround via custom gradient for inverse. I don't think the code is great and it prints loads of enzyme stuff but does appear to give the right answer. so perhaps you can register custom gradients for inverse, etc then you will be unblocked?

#include <cstdio>
#include <Eigen/Dense>

template <typename T, typename... Args>
T __enzyme_autodiff(void*, Args...) noexcept;
inline int enzyme_out;

constexpr int N = 11;
using Matrix = Eigen::Matrix<double, N, N>;

// -------------------------------------------------------
// Wrapped inverse — noinline is the critical part
// -------------------------------------------------------
__attribute__((noinline))
void matrix_inverse(const Matrix& A, Matrix& Ainv) {
    Ainv = A.fullPivLu().solve(Matrix::Identity());
}

// -------------------------------------------------------
// Augmented forward: run primal, cache A^{-1} on tape
// -------------------------------------------------------
void* aug_matrix_inverse(const Matrix& A,  const Matrix& dA,
                         Matrix& Ainv, Matrix& dAinv) {
    Ainv = A.fullPivLu().solve(Matrix::Identity());

    Matrix* tape = new Matrix(Ainv);
    return (void*)tape;
}

// -------------------------------------------------------
// Reverse pass: dA += -A^{-T} * dAinv * A^{-T}
// -------------------------------------------------------
void rev_matrix_inverse(const Matrix& A,  Matrix& dA,
                        Matrix& Ainv, Matrix& dAinv,
                        void* tape) {
    Matrix* cached_inv = (Matrix*)tape;

    dA.noalias() += -cached_inv->transpose() * dAinv * cached_inv->transpose();
    dAinv.setZero();

    delete cached_inv;
}

// -------------------------------------------------------
// Register custom gradient
// -------------------------------------------------------
void* __enzyme_register_gradient_matrix_inverse[3] = {
    (void*)matrix_inverse,
    (void*)aug_matrix_inverse,
    (void*)rev_matrix_inverse
};

// -------------------------------------------------------
// Objective
// -------------------------------------------------------
double objective(const double x) {
    Matrix matrix = Matrix::Zero();
    for (int i = 0; i < N; ++i) {
        matrix(i, i) = 3.14 + i * x;
    }

    Matrix Ainv;
    matrix_inverse(matrix, Ainv);
    return Ainv.sum();
}

int main() {
    double x = 1.0;
    double f = objective(x);
    double g = __enzyme_autodiff<double>((void*)objective, enzyme_out, x);
    std::printf("x=%f, f=%f, g=%f\n", x, f, g);
    return 0;
}
jeff@jeff:~/workspace/misc$ clang++ -std=c++23 -I/home/jeff/.local/include/eigen3 -O3 -fplugin=/home/jeff/workspace/Enzyme/install/lib/ClangEnzyme-20.so enzyme_inverse.cpp &> /dev/null && ./a.out
x=1.000000, f=1.636613, g=-0.690897

jeffpollock9 avatar Mar 21 '26 10:03 jeffpollock9

Hi @jeffpollock9, thanks for the suggestion! Yeah, using a custom gradient for the inverse is a workaround. However, I'm more interested in having Enzyme compute the derivative by itself, without custom gradient rules. This makes me wonder if there are differentiable operations that should be supported by Enzyme but currently are not.

shadow-orange41 avatar Mar 22 '26 19:03 shadow-orange41