Назад к подготовке
ВопросСредняяdeep-learning-engineeringСкрининг · Автотехника

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.