EnzymeAD / EnzymeAD/Enzyme

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

Open
#1,596 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
LLVM
Stars
1.7k
Forks
188
Avg merge
1d 22h
Merged PRs (30d)
26

Description

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

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

#include

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.

Contributor guide

Open the contributing guide

Research direction

Start by compiling the supplied foo/main reproducer with LLVM 16, Enzyme v0.0.98, and -O0 through -O3. Compare the behavior around __enzyme_autodiff and the N = p[(i + 1) % 5] expression. Done means val remains unchanged and the optimized build produces the same result as -O0 without requiring the +0 workaround.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.