Torch reshape order

Hello,
When you do torch.reshape() or .view() and, say, you flatten a matrix into an array, is there a guaranteed order the elements will be in?

In numpy you have an order argument that can specify a C/F/A order?

I am looking for something that preserves compatibility with numpy

Thanks in advance

1 Like

CPU tensors are compatible with numpy, you can use .numpy() to get a numpy array view on the storage.
You can inspect the memory layout using .stride(). C means highest stride first, F means lowest stride first.
For example

c = torch.randn(5,5)
print (c.stride())

returns (5,1) for me, so it would be in C order. Similarly, .continguous() makes C order.
A sightly convoluted way to get to F order would then be

cp = c.permute(list(numpy.argsort(c.stride()))).contiguous()
d = cp.permute(list(numpy.argsort(cp.stride())))

Now d.stride() will be (1,5) and (c==d).all().item() will be one.

Best regards

Thomas

3 Likes

@tom
torch.Size([4, 272, 352]) my tensor shape is this… 0,1 is one row in actual image , 2,3 is second row. But when i do reshape to get whole image , i get incorrect results compared to looping that gives correct image.

test_prd.rehape(520,704). #incorrect results compared row/column loop

Double post from here.