11

In the C++ version of Libtorch, I found that I can get the value of a float tensor by *tensor_name[0].data<float>(), in which instead of 0 I can use any other valid index. But, when I have defined an int tensor by adding option at::kInt into the tensor creation, I cannot use this structure to get the value of the tensor, i.e. something like *tensor_name[0].data<at::kInt>() or *tensor_name[0].data<int>() does not work and the debugger keeps saying that Couldn't find method at::Tensor::data<at::kInt> or Couldn't find method at::Tensor::data<int>. I can get the values by auto value_array = tensor_name=accessor<int,1>(), but it was easier to use *tensor_name[0].data<int>(). Can you please let me know how I can use data<>() to get the value of an int tensor?

I also have a same problem with bool type.

0

1 Answer 1

18

Use item<dtype>() to get a scalar out of a Tensor.

int main() {
  torch::Tensor tensor = torch::randint(20, {2, 3});
  std::cout << tensor << std::endl;
  int a = tensor[0][0].item<int>();
  std::cout << a << std::endl;
  return 0;
}

~/l/build ❯❯❯ ./example-app
  3  10   3
  2   5   8
[ Variable[CPUFloatType]{2,3} ]
3

The following code prints 0 (tested on Linux with the stable libtorch):

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

int main(int argc, const char* argv[])                  
{
    auto indx = torch::zeros({20},at::dtype(at::kLong));
    std::cout << indx[0].item<long>() << std::endl;

    return 0;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply. I have auto indx =torch::zeros({batch_size},at::dtype(at::kLong)); and then p indx[0].item<long>() gives me Couldn't find method at::Tensor::item<long>. Also, it comes with types like Byte, I even do not have same type in C++, and bool just does not work.
These commands work well for me on Linux and the stable libtorch.
So, you are saying auto indx =torch::zeros({batch_size},at::dtype(at::kLong)); and p indx[0].item<long>() works well for you, right? I am also using the stable version on Linux. So, what is the difference?
I see. Now, I have another problem. cout works fine, during the debug time, gdb cannot execute this code, which is weird. Do you have any idea about it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.