PyTorch: view против reshape
PyTorch: view против reshape
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
view returns a new view over the same storage and requires compatible contiguous strides. reshape tries to return a view when possible but may allocate/copy when the tensor layout does not allow a view.Подробный разбор
Both operations change the logical tensor shape without changing values, but they differ in memory-layout requirements. view is strict: it can only reinterpret the existing storage with compatible strides. If the tensor is non-contiguous after operations such as transpose, slicing or permute, view often fails unless you call contiguous() first.
reshape is more permissive. It attempts to create a view if the current layout allows it; otherwise it creates a contiguous copy and returns a tensor with the requested shape. This makes reshape convenient, but it can hide a copy and therefore extra memory/time cost.
In production code, use view when you intentionally require no copy and know the tensor is contiguous. Use reshape when API convenience is more important and a copy is acceptable. For performance-sensitive code, check contiguity and profile.
Типичные ошибки
- Say that `reshape` always copies.
- Ignore non-contiguous tensors produced by transpose/permute.
- Call `view` after arbitrary slicing without checking strides.