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

Adding const quietly invalidates results #311

Open
alecjacobson opened this issue Jan 18, 2024 · 0 comments
Open

Adding const quietly invalidates results #311

alecjacobson opened this issue Jan 18, 2024 · 0 comments

Comments

@alecjacobson
Copy link
Contributor

This code works correctly

#include <autodiff/reverse/var.hpp>
#include <autodiff/reverse/var/eigen.hpp>

Eigen::MatrixXd matrix_gradient(
  const autodiff::var& f, 
  autodiff::MatrixXvar & x)
{
  autodiff::VectorXvar x_vec = autodiff::VectorXvar{x.reshaped()};
  Eigen::VectorXd dfdx_vec = gradient(f, x_vec);
  return dfdx_vec.reshaped(x.rows(), x.cols());
}

int main(int argc, char *argv[])
{
  // Autodiff requires variables to be put into a vector
  autodiff::MatrixXvar U(2,2);
  U << 1, 2, 3, 4;
  // Expression using U as a matrix
  autodiff::var f = U(0,0)*U(1,1) - U(0,1)*U(1,0);
  Eigen::MatrixXd dfdU = matrix_gradient(f, U);
  std::cout<<dfdU<<std::endl;
}

Producing:

 4 -3
-2  1

But if I change autodiff::MatrixXvar & xconst autodiff::MatrixXvar & x then I get no compilation error but the incorrect result at runtime:

0 0 
0 0

Is there a way to detect this as compilation error to avoid this gotcha?

(meanwhile, is there a better way for me to create a helper function to get gradients in the shape of my parameters?)

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