[LibTorch] How to print the content of a tensor in gdb?

(Miguel Varela Ramos) #1

Hey guys,

I’m relatively new to C++ and LibTorch, but I would like to know how to inspect a tensor content in the debugger, since my workflow involves a lot of usage of the debugger.

In gdb I’m trying to do:

print x

$8 = {impl_ = {target_ = 0x14dfa20}}

print x.data()

Couldn't find method at::Tensor::data

I know torch::Tensor is a pointer, but I just can’t figure out how to dereference it


(Dtmoodie) #2

You could try something like the following:

With some modifications it could be used for visualizing tensors.

(Miguel Varela Ramos) #3

how do you import that into gdb?

(Afshin Oroojlooy) #4

You can use some p *x[0].data<float>() if it is a single dimension tensor, or p *x.data<float>() if it is a no-dim tensor, and so on.


(Miguel Varela Ramos) #5

it is a 4 dimensional tensor, but I would like to know how to do it for a tensor of arbitrary size.

Basically what I’m looking for is an output similar to

std::cout << x << '\n';

if I have to implement a python extension, so be it… but I still don’t understand how to do it.

(Afshin Oroojlooy) #6

I think you can see the content using cout in either run or debug consoles. Since you asked about gdb, I mentioned that approach. If you want to use gdb, you need to add more dimensions, e.g. p *x[i][j][k][l].data<float>().

(Miguel Varela Ramos) #7

that is not working for me

it either says Could not find operator[]. or No symbol "operator*" in current context.

I also couldn’t use cout directly in gdb, so far.

I’m new to C++, so I might be doing something wrong.

(Afshin Oroojlooy) #8

you cannot use cout in gdb, you need to hard code it. The error of Could not find operator[] is your gdb error. Probably it does not mach torch.