Torch.tensor.view() and torch.tensor.reshape(), what's the difference?

Some documentation is here.

I see .view and .reshape used somewhat interchangeably and would like to understand the differences a little better.

From what I understand from the docs, .view returns the original tensor, not a copy. reshape may return a copy under some circumstances. I’m not really clear on when reshape returns a copy vs. when it does not.

So it looks like .view may be more memory-efficient. Are there any other considerations?

2 Likes

Hey @jdbricker, I guess the only other consideration is that .view imposes contiguity constraints, unlike .reshpase. Found this answer https://stackoverflow.com/a/54507446 which sums your query, please check it out.

1 Like

To add to what PrajwalPrashanth already pointed out, it is similar to “passing parameters by value” vs “passing parameters by reference” in C++ pointer logic.

torch.view returns a pointer to the tensor, so any changes to original tensor are tracked in the viewed tensor as well. torch.reshape returns an entirely new tensor so that any changes in the original tensor are not reflected in the reshaped tensor.