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

Incorrect gradient for some cases of std::array used in loops #1086

Open
gojakuch opened this issue Sep 8, 2024 · 0 comments
Open

Incorrect gradient for some cases of std::array used in loops #1086

gojakuch opened this issue Sep 8, 2024 · 0 comments

Comments

@gojakuch
Copy link
Collaborator

gojakuch commented Sep 8, 2024

reproducer 1:

#include "clad/Differentiator/Differentiator.h"
#include "clad/Differentiator/STLBuiltins.h"
#include <iostream>

double fn(double x, double y) {
  std::array<double, 3> a;
  a.fill(x);

  for (size_t i = 0; i < 3; ++i) {
    a[i] *= i;
  }

  double res = 0;
  for (size_t i = 0; i < 3; ++i) {
    res += a[i];
  }

  return res;
}

int main(int argc, char* argv[]) {
    double dx, dy;
    auto df = clad::gradient(fn, "x, y");
    std::cout << fn(3, 4) << '\n';
    dx = 0; dy = 0;
    df.execute(3, 4, &dx, &dy);
    std::cout << dx << ' ' << dy << '\n';
}

expected output:
9
3 0
output:
9
2 0

a simpler (likely related) reproducer 2:

#include "clad/Differentiator/Differentiator.h"
#include "clad/Differentiator/STLBuiltins.h"
#include <iostream>

double fn(double x, double y) {
  std::array<double, 3> a;
  a.fill(x);
  for (size_t i = 0; i < 3; ++i) {
    a[i] *= i;
  }
  return a[0];
}

int main(int argc, char* argv[]) {
    double dx, dy;
    auto df = clad::gradient(fn, "x, y");
    std::cout << fn(3, 4) << '\n';
    dx = 0; dy = 0;
    df.execute(3, 4, &dx, &dy);
    std::cout << dx << ' ' << dy << '\n';
}

expected output:
0
0 0
output:
0
1 0

note that this works well for c-style arrays:

#include "clad/Differentiator/Differentiator.h"
#include "clad/Differentiator/STLBuiltins.h"
#include <iostream>

void fill(double t, double * a) {
  for (int i = 0; i < 3; ++i)
    a[i] = t;
}

double fn(double x, double y) {
  double a[3];
  fill(x, a);
  for (size_t i = 0; i < 3; ++i) {
    a[i] *= i;
  }
  return a[0];
}

int main(int argc, char* argv[]) {
    double dx, dy;
    auto df = clad::gradient(fn, "x, y");
    std::cout << fn(3, 4) << '\n';
    dx = 0; dy = 0;
    df.execute(3, 4, &dx, &dy);
    std::cout << dx << ' ' << dy << '\n';
}
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