How can I get the grad_fn name in C++?


(Daniel Falbel) #1

I would like to get the grad_fn name from the c++ side. Something like <AddBackward0> in python:

tensor([[3., 3.],
        [3., 3.]], grad_fn=<AddBackward0>)

I tried the following:

#include <torch/torch.h>

#include <iostream>

int main() {
  torch::Tensor x = torch::randn({2, 3});
  x.set_requires_grad(true);
  torch::autograd::Variable y(x);
  std::cout << y.grad_fn().get()->name << std::endl;
}

But it does not compile. The error is:

error: member access into incomplete type
      'std::__1::shared_ptr<torch::autograd::Function>::element_type' (aka 'torch::autograd::Function')
  std::cout << y.grad_fn().get()->name << std::endl;

Does anyone can help me?

Thanks in advance!


(Will Feng) #2

This will work:

#include <torch/torch.h>
#include <iostream>
#include <torch/csrc/autograd/function.h>

int main(int argc, const char* argv[]) {
    auto x = torch::randn({2, 3});
    x.set_requires_grad(true);
    auto z = x + x;
    torch::autograd::Variable y = torch::autograd::as_variable_ref(z);
    std::cout << y.grad_fn()->name() << std::endl;  // Prints: AddBackward0
    return 0;
}