Skip to content

← Shapes and Strides step 1 of 9

Easy Primitives

Read the stride

Jump to the task

A stride tells you how many storage elements to advance when an axis index increases by one. Together with shape and storage offset, strides describe where a strided tensor's values are stored.

Read a contiguous layout

import torch

x = torch.arange(24).reshape(2, 3, 4)
print(list(x.shape))  # [2, 3, 4]
print(x.stride())  # (12, 4, 1)

The last axis advances one element at a time. Moving along the middle axis skips a row of four elements. Moving along the first axis skips a whole block of twelve.

For a freshly allocated tensor with positive dimensions in the default contiguous format, each stride is the product of the dimension sizes to its right. Shape (2, 3, 4) therefore gives strides (12, 4, 1).

That formula describes the layout constructed here, not every tensor that can be considered contiguous. Size-one dimensions do not constrain element spacing, and PyTorch also supports other memory formats.

Permute the strides with the axes

y = x.permute(2, 0, 1)
print(list(y.shape))  # [4, 2, 3]
print(y.stride())  # (1, 12, 4)
print(y[3, 1, 2].item())  # 23

Axis 0 of y came from axis 2 of x, so it inherits stride 1. The other strides follow the same ordering. For example, index [3, 1, 2] reaches storage element 3 * 1 + 1 * 12 + 2 * 4 = 23.

The permutation shares the existing data storage. It updates size and stride metadata without rearranging values. This result is not contiguous in the default format, but it still represents a valid tensor.

Your task

def permuted_stride(shape: list[int], order: list[int]) -> list[int]

Given positive dimension sizes and a valid permutation of their axis indices, return the strides of torch.zeros(shape).permute(*order) as a list. You may construct the tensor and inspect it or calculate the strides directly.

The starter returns the original strides without applying the permutation. That may match by coincidence if exchanged axes have equal strides, but it does not implement the requested ordering.