Enzyme icon indicating copy to clipboard operation
Enzyme copied to clipboard

Compilation failure when using enzyme_out with matrix derivatives

Open shadow-orange41 opened this issue 11 months ago • 0 comments

error_message.txt

Hi,

I'm working on using Enzyme to compute derivatives involving matrices, and I noticed an issue when using the enzyme_out annotation. Compilation fails in this case, but using enzyme_dup compiles successfully and produces correct results. I’m wondering whether this is a bug in Enzyme or related to Clang 16.

I've attached anexample below to reproduce the issue:

Code to reproduce

#include <iostream>
#include <enzyme/enzyme> 
#include <Eigen/Dense>
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 ... );


double objective(Eigen::Matrix<double, 3, 1>& x) {

   
    Eigen::Matrix<double, 2, 2> a = Eigen::Matrix<double,2,2>::Ones();
    
    a.array() += x[0];


    Eigen::Matrix<double, 1, 2> b = Eigen::Matrix<double,1,2>::Ones();
    
    b.array() += x[1];

    Eigen::Matrix<double, 1, 2> c;
    
    c = b * a;
    return c.sum();

}

void objective_ref(Eigen::Matrix<double, 3, 1>& x, double& result) {

    Eigen::Matrix<double, 2, 2> a = Eigen::Matrix<double,2,2>::Ones();
    
    a.array() += x[0];

    Eigen::Matrix<double, 1, 2> b = Eigen::Matrix<double,1,2>::Ones();
    
    b.array() += x[1];

    Eigen::Matrix<double, 1, 2> c;
    c = b * a;
    result =  c.sum();

}

struct double3{
        double x, y, z;
    };
    
void return_by_ref_reverse(){


    Eigen::Matrix<double, 3, 1> x;
    x << 1.0, 3.0, 42.0;

    double lambda = 1;
    double z = 0;

    // Fail to compile if using enzyme_out
    double3 res = __enzyme_autodiff<double3>((void*)objective_ref,
                        enzyme_out, x,
                        enzyme_dup, &z, &lambda);
    std::cout << "Return by reference reverse mode:" << std::endl;
    std::cout << "d_x: "<< res.x << ", " << res.y << ", " << res.z << std::endl;

}

void return_by_value_reverse(){

    Eigen::Matrix<double, 3, 1> x;
    x << 1.0, 3.0, 42.0;

    Eigen::Matrix<double, 3, 1> dx;
    dx << 0.0, 0.0, 0.0;

    // Fail to compile if using enzyme_out
    auto res = __enzyme_autodiff<double3>((void*)objective, 
                        enzyme_out, x);
    
    std::cout << "Return-by-value reverse mode 2:" << std::endl;
    std::cout << res << std::endl;
}

int main() {
    return_by_value_reverse();
    return_by_ref_reverse();

    
    return 0;
}

The full error message is included in error_message.txt.

Thanks!

shadow-orange41 avatar Dec 08 '25 16:12 shadow-orange41