torch.as_strided — PyTorch 2.7 documentation (original) (raw)

torch.as_strided(input, size, stride, storage_offset=None) → Tensor

Create a view of an existing torch.Tensor input with specifiedsize, stride and storage_offset.

Warning

Prefer using other view functions, like torch.Tensor.expand(), to setting a view’s strides manually with as_strided, as this function’s behavior depends on the implementation of a tensor’s storage. The constructed view of the storage must only refer to elements within the storage or a runtime error will be thrown, and if the view is “overlapped” (with multiple indices referring to the same element in memory) its behavior is undefined.

Parameters

Example:

x = torch.randn(3, 3) x tensor([[ 0.9039, 0.6291, 1.0795], [ 0.1586, 2.1939, -0.4900], [-0.1909, -0.7503, 1.9355]]) t = torch.as_strided(x, (2, 2), (1, 2)) t tensor([[0.9039, 1.0795], [0.6291, 0.1586]]) t = torch.as_strided(x, (2, 2), (1, 2), 1) tensor([[0.6291, 0.1586], [1.0795, 2.1939]])