TensorPlay
Reference guides
latest (dev)
Copy
View Markdown

Latest development documentation · Updated 2026-10-08

Tensor views

A view is a tensor that shares its underlying data with another tensor. Reshaping, selecting dimensions, or reversing a tensor are all cheap — instead of copying the elements, the view stores different metadata (shape, strides) over the same storage. This is why operations like view, transpose, and squeeze are instant and memory-efficient.

import tensorplay as tp

x = tp.arange(12).reshape(3, 4)
y = x.t()          # a transposed view
print(x.data_ptr() == y.data_ptr())  # True — same underlying data
y[0, 0] = 99
print(x[0, 0].item())   # 99 — the change is visible through the view

The rule of thumb: an operation that only changes shape, strides, or layout produces a view; an operation that creates new elements copies. reshape may return a view or a copy depending on the memory layout — use view when you know the tensor is contiguous and want to guarantee no copy.

The view functions

tensorplay.as_strided

Create a view of an existing tensorplay.Tensor input with specified size, stride and storage_offset.

tensorplay.narrow

Returns a new tensor that is a narrowed version of input tensor.

tensorplay.expand

tensorplay.squeeze

Returns a tensor with all specified dimensions of input of size 1 removed.

tensorplay.unsqueeze

Returns a new tensor with a dimension of size one inserted at the specified position.

tensorplay.select

Slices the input tensor along the selected dimension at the given index.

tensorplay.t

Expects input to be <= 2-D tensor and transposes dimensions 0 and 1.

tensorplay.transpose

Returns a tensor that is a transposed version of input.

tensorplay.permute

Returns a view of the original tensor input with its dimensions permuted.

tensorplay.view

tensorplay.reshape

Returns a tensor with the same data and number of elements as input, but with the specified shape.

tensorplay.flatten

Flattens input by reshaping it into a one-dimensional tensor.

tensorplay.split

tensorplay.chunk

Attempts to split a tensor into the specified number of chunks.

Common ones in context:

x = tp.arange(6).reshape(2, 3)
print(x.transpose(0, 1).shape)   # (3, 2)
print(x.view(6))                 # flatten, no copy
print(x.narrow(1, 0, 2).shape)   # (2, 2) — rows 0:2 of the second dim
b = tp.ones(1, 3)
print(b.expand(4, 3).shape)      # (4, 3) — broadcast a size-1 dim, no copy

When data is not shared

Some operations rebuild the data and do not share storage:

  • clone() always copies.

  • contiguous() returns a copy when the tensor is non-contiguous (e.g. after transpose).

  • reshape copies when the required shape is not reachable with the current strides.

  • detach() shares data but cuts the autograd graph (see Autograd).

Where to go next

On this page

Ask DeepWiki