Passing tensor to c++ extension function changes its options


(Serhii H) #1

Hello,

I have very simple c++ function:

#include <torch/extension.h>
#include <iostream>

void print_options(torch::Tensor x) {
    std::cout << x.options() << "\n";
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  m.def("print_options", &print_options, "");
}

which I use via JIT compiling extensions functionality:

import torch
from torch.utils import cpp_extension

cuda_module = cpp_extension.load(name="cpp_module", sources=["cpp_modue/my_fun.cpp"])
print_options = cuda_module.print_options

a = torch.zeros(2, 3)
a.requires_grad = True
print(a.requires_grad)

print_options(a)

And here is the output:

True
TensorOptions(dtype=float, device=cpu, layout=Strided, requires_grad=false)

Does anyone know why passing tensor to the c++ function changes its options (requires_grad in particular)?
I would appreciate any help on this issue.


(Serhii H) #2

This is expected behaviour. The answer is here.