Skip to main content
CookLLM logoCookLLM Docs

Tensor Layout

Premium

Understand physical memory layout, strides, view vs reshape, and gradient tracking.

What Is a Tensor?

If you have seen this error, it is confusing at first:

RuntimeError: view size is not compatible with input tensor's size and stride

Or you may have wondered why PyTorch code often uses detach().clone() instead of just one of them.

These issues mix three different concepts: memory layout, view operations, and gradient tracking. The starting point is:

A PyTorch tensor = a flat memory buffer + metadata that interprets it.

The metadata includes:

  • Shape: dimensions and sizes
  • Stride: how many memory steps to move along each dimension
  • Storage offset: where the tensor starts in the underlying storage

Let’s verify:

import torch

x = torch.tensor([[1, 2, 3],
                  [4, 5, 6]])

print(x)
print(f"Shape: {x.shape}")     # torch.Size([2, 3])
print(f"Stride: {x.stride()}") # (3, 1)

Although we see a 2×3 matrix, PyTorch stores data as [1, 2, 3, 4, 5, 6] and interprets it with shape=(2,3) and stride=(3,1).

Log in to continue reading

This is premium content. Please log in to access the full article.