Skip to content

Instantly share code, notes, and snippets.

@zetyquickly
Last active March 15, 2022 03:36
Show Gist options
  • Save zetyquickly/730fd23e37ff7d06cdc9654b62d2974c to your computer and use it in GitHub Desktop.
Save zetyquickly/730fd23e37ff7d06cdc9654b62d2974c to your computer and use it in GitHub Desktop.
View Contiguous
import torch
# Tensor of interest
tens_A = torch.rand((2,3,4)) # 3-dimensional tensor of shape (2,3,4)
def test_view(tensor, sizes):
try:
tensor.view(*sizes)
except Exception as e:
print(e)
print(f"View was Failed: tensor.is_contiguos == {tensor.is_contiguous()}")
else:
print(f"View was Successful: tensor.is_contiguos == {tensor.is_contiguous()}")
sizes = (3,4,2)
# Let's try to use view
test_view(tens_A, sizes)
# Apply view-function that change contiguity and try again
perm_tens_A = tens_A.permute(0,2,1) # change order of axis
test_view(perm_tens_A, sizes) # this will result in RuntimeError("Use .reshape(...) instead")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment