Tensor repr in debug should show shape first

I was debugging a lot of torch code recently, and can’t help complaining that string representation of tensor I see in debugger (PyCharm, but I assume it’s created by __repr__ method) is not helpful. I see tensor([[ 2.6877e+01, -1.0073e+01, 8.0276e+02, …, ]]), but what I want to know is what shape the tensor is. Ofc there is a partial hint - opening square brackets count - but I’d like to see the specific shape in the overview. Shape is basically a detail of the tensor type, which has more importance over what it is, where it comes from and what can be safely done with it than the specific numbers in the tensor IMO.

I know repr is usually such that copy-pasting it into python should yield code that recreates the original object, but this is anyhow not happening here because there are too many numbers to display, they are hidden with ellipsis … .

Does this make sense to anyone? :slight_smile:

1 Like

Hi,

you can print the shape of the tensor.

tensor = torch.rand((5, 10, 15, 20))
print(tensor.shape)
#Output
torch.Size([5, 10, 15, 20])

Or do you want it to be automatically in the _repr_ function of something specific?

yes, I think debuggers use __repr__ to show the value of variables in scope, so that’s what I’d suggest changing.

Oh sorry, I did not understand at first.

Yeah, I also think this would be a good idea to print the shape of the tensor.

Here is the link to the file, there you can make the suggestion directly to add the shape to the _repr_.

Or maybe someone will see this issue here.

If not, you can tell me and I can try to make the suggestion myself :blush:

A colleague suggested following hack solution (put the code early in your script):

normal_repr = torch.Tensor.__repr__
torch.Tensor.__repr__ = lambda self: f"{self.shape}_{normal_repr(self)}"

@Matias_Vasquez I would happily +1 your issue if you can create one. From what I know torch tries to be like numpy in many ways, so maybe this feature request should go to numpy as well.