EnzymeAD / EnzymeAD/Enzyme

Incorrect derivative result when nested void functions and recursive nature functions are used.

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

Description

I have recently been running an experiment testing some of the limitations associated with using Enzyme and have found the following interesting case and was wondering if anyone could help me or if applicable be added as an issue. When running a function that uses nested void functions, as shown in the script below, the incorrect derivative result is produced when compared to the finite difference approximation result.

1.) Can Enzyme accommodate nested functions containing void functions ? It seems that it cannot.
---------------------------------------------------------------------------------------------------------------------------
```
void fnOne(double* rate) {

input[0] = input[0]*12;
input[1] = input[1]*24;
input[2] = input[2]*36;
}

void fnTwo(double* rate) {
input[0] = input[0]+ 12;
input[1] = input[1]/24;
input[2] = input[2] +0.058;
}

void fnThree(double* rate) {

double volatility = 0.023;
double r = 0.04;
double dt = 1/12;

for ( int i =0; i < 3; i++) {
rate[i] = rate[i] + (r - 0.5*vol*vol)*dt + vol*(0.5*dt)*0.05;
}
}

double sumtil(double* vec, int size) {
double ret = 0.0;
for (int i = 0; i < size; i++) {
ret += vec[i];
if (ret > 15) break;
ret += vec[i];
}
return ret;
}

double fn(double* rate, int size) {

fnOne (rate); //void
fnTwo(rate); //void
fnThree(rate); //void

double ret = sumtil(rate, size);

return ret;

}

```

2.) The second limiting case I found is that when a function uses a recursive function shown in the script below, Enzyme produces the wrong derivative result when compared to the finite difference approximation, is there a way around this ?
---------------------------------------------------------------------------------------------------------------------------

More specifically it seems that the [i-1] indexing may be the underlying issue here

```
double gbmSim(double* rate, double* previous, int index) {

double volatility = 0.023;
double r = 0.04;
double dt = 1/12;

rate[index] = rate[index -1] + (r - 0.5*vol*vol)*dt + vol*(0.5*dt)*0.05;

return rate[index];
}

double sumtil(double* vec, int size) {
double ret = 0.0;
for (int i = 0; i < size; i++) {
if( i > 0) {
double intermediateVal = gbmSim(vec, i);
ret += intermediateVal[i];
}
else {
ret += vec[i];
}

if (ret > 2.25) break;
ret += intermediateVal[i];
}
return ret;
}

double fn(double* rate, int size) {

double ret = sumtil(rate, size);

return ret;

}

```

Thanks again everyone, please let me know if you would like the accompanying enzyme calls from main.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.