Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enzyme mutates enzyme_const array when optimization flag -O1 or further used #1596

Open
akdemironur opened this issue Dec 22, 2023 · 0 comments

Comments

@akdemironur
Copy link

[LLVM 16, Enzyme v0.0.98]
Here is the sample code:

void __enzyme_autodiff(void *, ...);
int enzyme_const, enzyme_dup, enzyme_out, enzyme_dupnoneed;

#include <stdio.h>

void foo(const double *p, double *r, int *type, double *val)
{
    for (size_t i = 0; i < 5; ++i)
    {
        double O, N;
        O = p[i];
        if (type[i] == 0)
        {
            N = val[i];
        }
        else
        {
            N = p[(i + 1) % 5];
        }
        r[i] = O + N;
    }
}

int main()
{
    int type[5] = {0};
    double val[5] = {0}, r[5] = {0}, grad_p[5] = {0}, grad_r[5] = {0, 0, 1, 0, 0};
    const double p[5] = {1};

    printf("val[init]:\t%6.3f %6.3f %6.3f %6.3f %6.3f\n", val[0], val[1], val[2], val[3], val[4]);

    foo(p, r, type, val);

    printf("val[foo]:\t%6.3f %6.3f %6.3f %6.3f %6.3f\n", val[0], val[1], val[2], val[3], val[4]);

    __enzyme_autodiff(foo, enzyme_dup, p, grad_p, enzyme_dupnoneed, r, grad_r, enzyme_const, type, enzyme_const, val);

    printf("val[enzyme]:\t%6.3f %6.3f %6.3f %6.3f %6.3f\n", val[0], val[1], val[2], val[3], val[4]);
}

When I compile this code with -O0 opt I get this output as expected:

val[init]:	 0.000  0.000  0.000  0.000  0.000
val[foo]:	 0.000  0.000  0.000  0.000  0.000
val[enzyme]:	 0.000  0.000  0.000  0.000  0.000

When I compile it with -O1/2/3

val[init]:	 0.000  0.000  0.000  0.000  0.000
val[foo]:	 0.000  0.000  0.000  0.000  0.000
val[enzyme]:	 0.000  0.000  1.000  0.000  0.000

The workaround I am using for this issue is, changing N = p[(i + 1) % 5]; to N = p[(i + 1) % 5] + 0; With this change compilation with optimization flags are working as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant