Module contents
Lesson 4 of 24Core 90 min

Inside the ndarray: memory, dtypes, strides and views

An ndarray is a block of memory plus a recipe for interpreting it: dtype, shape, strides, and offset. This model explains why transposing is free, why some operations copy and others do not, when an array is contiguous, and how to build sliding windows without copying. The same model governs PyTorch tensors, so mastering it here pays off throughout the course.

After this lesson you can

  • Calculate the strides of C- and Fortran-order arrays and the memory address of any element by hand.
  • Predict whether an operation (slicing, transpose, reshape, ravel, advanced indexing, astype) returns a view or a copy and check it with np.shares_memory.
  • Choose dtypes consciously and anticipate result dtypes using NumPy 2 promotion rules.
  • Build overlapping views with sliding_window_view and as_strided without copying data and understand their risks.
  • Measure the effect of contiguity and traversal order on reduction time.

Motivation: the same result, two very different costs

Create a matrix of 4000×40004000 \times 4000 floating-point numbers, 128 MB, and try two expressions that return arrays with exactly the same values:

x = np.ones((4000, 4000))
y = x.T            # menos de un microsegundo, tenga x el tamaño que tenga
z = x.T.copy()     # del orden de 0.1 a 0.3 s: lee 128 MB a saltos y escribe otros 128 MB

y and z are equal element by element, but they are not the same kind of object. z has its own memory. y has none: it is a different way to read the bytes of x. That is why transposing a matrix of 4 elements costs the same as one of 16 million, and why y[0, 1] = 5 changes x[1, 0] without warning you.

This distinction appears as soon as you do something serious:

  • In PyTorch, t.T.view(-1) raises RuntimeError: view size is not compatible with input tensor's size and stride, whereas t.T.reshape(-1) works. The difference between the two calls is exactly what this lesson covers, and on an 8 GB GPU an implicit copy of an activation tensor can exhaust memory.
  • In time series, a matrix of every 250-day window of a series of a million prices would occupy about 2 GB if copied. Built as a view, it occupies zero additional bytes.
  • In vision, convolution implemented as im2col starts from such a strided view, and its memory cost appears precisely when that view becomes a matrix.
  • In debugging, the most puzzling NumPy errors involve aliasing: you modify what you believe is a copy and corrupt the original data, or conversely modify a copy and the changes do not reach where you expected.

Everything is explained by a small model: an ndarray is a block of bytes plus a recipe for interpreting it. The recipe has four ingredients (dtype, shape, strides, and offset), with which you can predict, before running anything, which operations are free, which copy, and how much traversing an array in one order or another costs.

Anatomy of an ndarray

Two different arrays can share the same buffer with different metadata. That is what a view is. The base attribute points to the object that owns the buffer, and OWNDATA says whether the array itself owns it. WRITEABLE indicates whether writing through this array is allowed: views created with broadcast_to or sliding_window_view start read-only precisely because several logical positions share a byte.

All this can be inspected. The __array_interface__ interface exposes the pointer to the first element, and we use it to calculate each view’s offset from the start of a:

[ ]Anatomy of an array and three of its viewsBrowser
import numpy as np

a = np.arange(12, dtype=np.float64).reshape(3, 4)
t = a.T

def anatomia(nombre, x, ref=a):
    ptr = x.__array_interface__["data"][0]
    print(f"{nombre:10s} shape={x.shape!s:8s} strides={x.strides!s:9s} "
          f"offset={ptr - ref.__array_interface__['data'][0]:3d} B  "
          f"C={x.flags.c_contiguous!s:5s} F={x.flags.f_contiguous!s:5s} "
          f"OWNDATA={x.flags.owndata!s:5s} WRITEABLE={x.flags.writeable}")

print("dtype:", a.dtype, "| itemsize:", a.itemsize, "B | nbytes:", a.nbytes, "B")
anatomia("a", a)
anatomia("a.T", t)
anatomia("a[1:]", a[1:])
anatomia("a[:, ::-1]", a[:, ::-1])
print("dueño del buffer:", a.base.shape, "| ¿t.base es a.base?", t.base is a.base,
      "| ¿comparten memoria?", np.shares_memory(a, t))
t[0, 1] = -1.0                       # escribir en la vista...
print("a[1, 0] =", a[1, 0])           # ...es escribir en a
print("primeros 16 bytes del buffer:", a.tobytes()[:16].hex(" "))

Notice four details in the output. a does not own its data (OWNDATA=False): np.arange created a 12-element array and reshape returned a view of it, so a.base is that flat array and all subsequent views point to it. The transpose has reversed strides, (8,32)(8, 32), and changes from C-contiguous to F-contiguous. a[:, ::-1] has a negative stride and an offset of 24 bytes: its first element is the last in row 0. The buffer bytes are the IEEE 754 representation of 0.00.0 and 1.01.0 in little-endian, the byte order of x86 and ARM: 00 … 00 and 00 00 00 00 00 00 f0 3f.

Addressing: an affine formula

The mapping from indices to bytes is affine: an offset plus a linear combination of indices. Almost everything that follows results from this rigid form. A view can only describe sets of positions that are the image of a box of indices under an affine map, and any selection without that structure requires copying.

When creating a new array, NumPy chooses strides according to the requested order. In C order (row-major, the default for C, NumPy, and PyTorch) the last index changes fastest; in Fortran order (column-major, used by Fortran, MATLAB, Julia, and LAPACK) the first changes fastest. With itemsize σ\sigma:

skC=σ∏j>knj,skF=σ∏j<knj.s_k^{\mathrm{C}} = \sigma \prod_{j > k} n_j, \qquad s_k^{\mathrm{F}} = \sigma \prod_{j < k} n_j.

For a 3×43 \times 4 matrix of float64 (σ=8\sigma = 8) this gives (32,8)(32, 8) in C order and (8,24)(8, 24) in F order. In C order, the flat index dir⁡/σ=4i1+i2\operatorname{dir}/\sigma = 4 i_1 + i_2 is a number written in mixed radix: digit i2i_2 counts units, digit i1i_1 counts “rows” of 4. This correspondence being a bijection makes a newly created array use its entire buffer without gaps or overlap.

The proof is an induction on the number of axes worth working through carefully once, because this is exactly the argument that reappears whenever we reason about reshape.

ProofC-order strides by induction
Prove: For a C-contiguous array of shape (n1,…,nd)(n_1, \dots, n_d) and itemsize σ\sigma, sk=σ∏j>knjs_k = \sigma\prod_{j>k} n_j and the map ϕd(i1,…,id)=∑kik sk/σ\phi_d(i_1, \dots, i_d) = \sum_k i_k\, s_k / \sigma is a bijection from the index box to {0,…,N−1}\{0, \dots, N-1\}.
0
In C order, the block of elements with fixed i1i_1 is a C-contiguous array of shape (n2,…,nd)(n_2, \dots, n_d), and the n1n_1 blocks are placed one after another in the buffer in increasing order of i1i_1.

Step 1 of 4. What is the base case?

The same proof, reading the axes in reverse, gives the F-order strides. We can now define precisely what contiguous means.

The exception for axes of size 1 matters: their index is always 0, so their stride never enters the formula and can have any value. Thus a vector with stride σ\sigma, or a 1×n1 \times n matrix with stride σ\sigma on its long axis, is both C- and F-contiguous; two arrays with the same data may also show different strides on size-1 axes without it mattering.

InteractiveThe linear memory behind an array
a.Twith a = np.arange(12, dtype=np.float64).reshape(3, 4)
012012304815926103711001821632443254064875686497210801188offseta buffer: memory position and first byte
  • contiguous step (+1 element)
  • memory jump
  • color: source row in a
addr(2,0)=0+2⋅8+0⋅32=16 B  ⇒  position 2\text{addr}(2, 0) = 0 + 2\cdot8 + 0\cdot32 = 16\ \text{B} \;\Rightarrow\; \text{position } 2
Base array
Shape of a
dtype (bytes per element)
Operations on the current view
Display
shape(4, 3)
strides (bytes)(8, 32)
offset (bytes)0
C / F contiguousno / yes
Shares memory with a?yes (view)
Transposing reverses the order of the shape and strides. The bytes stay where they are.
Above is the view's logical shape; below is the buffer of a, with each position's value (its original index) and starting byte. Start at a.T: the magenta arcs of logical traversal jump through memory, so the view is not C-contiguous. Apply operations and observe that the bytes never move: only shape, strides, and offset (the triangle) change. Hover over an element to see the sum o+∑kiksko + \sum_k i_k s_k that locates it. Then try reshape(12) on a.T, and reshape(2, 2, 3) on a.T: one of the two must copy.

What you should have seen:

  • Memory is unchanged by views. Transposing, reversing, trimming, or taking a step changes only shape, strides, and offset. Each cell’s color, marking its row in a, reveals where each element traveled in the logical shape, while everything remains in place in the strip below.
  • Contiguous means “short arcs.” When the view is C-contiguous, logical traversal advances from one cell to the next. After .T, [::-1], or a step, jumps appear.
  • The dtype only scales. Changing from int8 to float64 multiplies strides and offset by the itemsize and changes nothing else: strides are element counts multiplied by σ\sigma as long as you do not reinterpret the bytes.
  • Some reshapes copy. a.T.reshape(12) cannot be a view: logical traversal of a.T visits positions 0,4,8,1,5,9,…0, 4, 8, 1, 5, 9, \dots, and no single stride generates that sequence. A new buffer appears. By contrast, a.T.reshape(2, 2, 3) is a view. The next section explains why.

Views and copies

The general rule follows from the affine formula: an operation can return a view if and only if its result can be described with new (o′,n′,s′)(o', n', s') on the same buffer. The table summarizes common operations.

OperationResultNew metadata
a[i0:i1:p] on one axis (basic slicing)viewo+=i0so \mathrel{+}= i_0 s, s←p ss \leftarrow p\,s, n←∣range⁡(i0,i1,p)∣n \leftarrow \lvert \operatorname{range}(i_0, i_1, p) \rvert
a[i] with an integerview (if axes remain)o+=i so \mathrel{+}= i\,s and the axis disappears
a.T, transpose, swapaxesviewshape and strides are permuted
a[:, None], squeeze, expand_dimsviewa size-1 axis is added or removed
np.broadcast_toread-only viewstride 0 on stretched axes
reshape, ravelview if possible, otherwise copysee theorem below
flatten, copyalways copies
indexing with lists or integer arraysalways copies
Boolean masksalways copies
astypecopy (except copy=False with the same dtype)
a + b, np.exp(a), any ufuncnew array
a += b, out=, a[...] = bwrite to the existing buffer

The lower rows deserve justification. A set of positions accessible with a one-axis view is an arithmetic progression o,o+s,o+2s,…o, o + s, o + 2s, \dots; more generally, the image of a box under an affine map. a[[0, 1, 3]] on a vector requests positions 0,1,30, 1, 3, which do not form a progression: no view describes it. NumPy does not bother distinguishing fortunate cases. Advanced indexing and Boolean masks always copy, even if the selection happens to be a progression, because the result type is decided by the index type, not its values. a[[0, 2]] copies; a[::2], with the same elements, is a view.

That leaves reshape, the subtlest case and the one causing the most performance errors. Reshape is always defined by logical C order: elements are read in that order and rearranged into the new shape in the same order. The question is whether strides exist that describe the result on the original memory. Two simple cases decide everything:

  • Splitting an axis is always possible. An axis of size n=pqn = pq and stride ss becomes two axes (p,q)(p, q) with strides (qs,s)(q s, s): element j=aq+bj = aq + b was at o+js=o+a(qs)+bso + j s = o + a(qs) + b s.
  • Merging two axes is not always possible. Axes kk and k+1k + 1, both larger than 1, can be merged into one of size nknk+1n_k n_{k+1} if and only if sk=nk+1 sk+1s_k = n_{k+1}\, s_{k+1}. If the merged axis has stride tt, logical element 11 (formerly (0,1)(0, 1)) is at o+to + t and o+sk+1o + s_{k+1}, so t=sk+1t = s_{k+1}; logical element nk+1n_{k+1} (formerly (1,0)(1, 0)) is at o+nk+1to + n_{k+1} t and o+sko + s_k. Conversely, if equality holds, iksk+ik+1sk+1=(iknk+1+ik+1)sk+1i_k s_k + i_{k+1} s_{k+1} = (i_k n_{k+1} + i_{k+1}) s_{k+1} and stride t=sk+1t = s_{k+1} works.

A general reshape combines splits and merges, and the theorem says those two rules suffice.

Proof

Cuts between blocks fall where cumulative products agree, so the old and new mixed-radix “digits” agree there: the indices of a block’s axes are the same number in both shapes, written in two different mixed bases. Therefore the address is a sum of independent contributions from each block, and it suffices to reason block by block. Fix a block; call its product PP, its internal flat index φ∈{0,…,P−1}\varphi \in \{0, \dots, P - 1\}, and the old contribution to the address A(φ)A(\varphi).

Sufficiency. If all old axes of the block satisfy the condition, applying it from inside out gives sk=si′∏j>k, j≤i′njs_k = s_{i'} \prod_{j > k,\, j \le i'} n_j: these are the block shape’s C-order strides scaled by si′s_{i'}, and by the C-order stride theorem, A(φ)=si′ φA(\varphi) = s_{i'}\,\varphi. The block behaves like a single axis of stride si′s_{i'}, and splitting an axis into (mj,…,mj′)(m_j, \dots, m_{j'}) is always possible with the stated strides.

Necessity. Suppose there is a view and the condition fails; let kk be the largest index in the block with sk≠nk+1sk+1s_k \ne n_{k+1} s_{k+1}. Axes k+1,…,i′k + 1, \dots, i' do satisfy the condition, so they form a merged axis of size S=nk+1⋯ni′S = n_{k+1}\cdots n_{i'} and A(φ)=si′φA(\varphi) = s_{i'}\varphi for 0≤φ<S0 \le \varphi < S; moreover A(S)=skA(S) = s_k, because φ=S\varphi = S is the index with 1 on axis kk and zeros afterward. Call the new shape’s cumulative products from the right Tl=ml+1⋯mj′T_l = m_{l+1}\cdots m_{j'}, strictly decreasing from Tj−1=PT_{j-1} = P to Tj′=1T_{j'} = 1. We have 1<S<P1 < S < P (axis kk is outside SS and axis i′i' inside, both of size greater than 1), and SS is no TlT_l: if S=TlS = T_l, the cumulative products from the left ni⋯nk=P/Sn_i \cdots n_k = P/S and mj⋯ml=P/Tlm_j \cdots m_l = P/T_l would agree at an internal cut in the block, contradicting its minimality. Thus some ll satisfies Tl<S<Tl−1T_l < S < T_{l-1}. For φ<Tl−1\varphi < T_{l-1}, the new view uses only axes l,…,j′l, \dots, j': B(φ)=tl⌊φ/Tl⌋+B′(φ mod Tl)B(\varphi) = t_l \lfloor \varphi / T_l \rfloor + B'(\varphi \bmod T_l). Since B=AB = A on [0,S)[0, S) and Tl<ST_l < S, we obtain B′(r)=si′rB'(r) = s_{i'} r for r<Tlr < T_l and tl=B(Tl)=si′Tlt_l = B(T_l) = s_{i'} T_l. Then B(φ)=si′φB(\varphi) = s_{i'}\varphi for all φ<Tl−1\varphi < T_{l-1}, in particular for φ=S\varphi = S: sk=A(S)=B(S)=si′S=nk+1 sk+1s_k = A(S) = B(S) = s_{i'} S = n_{k+1}\, s_{k+1}, contradicting the choice of kk.

∎

In practice, read the theorem as follows: reshape copies exactly when it has to merge axes with a gap or disorder in memory. With a.T of shape (4,3)(4, 3) and strides (8,32)(8, 32), shape (12,)(12,) forms one block with both axes and requires 8=3⋅328 = 3 \cdot 32: it copies. Shape (2,2,3)(2, 2, 3) forms two blocks, (4)↔(2,2)(4) \leftrightarrow (2, 2) and (3)↔(3)(3) \leftrightarrow (3), neither merges anything, and it is a view with strides (16,8,32)(16, 8, 32). This is the algorithm NumPy implements in C (_attempt_nocopy_reshape) and the one you will program in the exercises.

Now put it to the test. None of the following twelve rounds requires running code: the strides of a and the rules above suffice.

InteractiveView or copy?
Correct: 0 of 0
Round 1 of 12 · a = np.arange(24.0).reshape(4, 6), strides (48, 8)
r = a[::2, 1:]
r: shape (2, 5). Each value is also its position in a.0123401123451314151617a buffer (position and first byte)00182163244325406487568649721080118812961310414112151201612817136181441915220160211682217623184
r.shape?
r.strides?
Offset relative to a?
np.shares_memory(a, r)?
C / F contiguous · writable?
For each expression, guess whether r is a view of a or a copy; then see which bytes of a are pointed to by r (or the new buffer it allocates) and the actual metadata from NumPy 2. In the broadcast_to round, ×3 counts how many elements of r share each byte. At the end, the summary groups your mistakes by operation type.

Three tools to check your predictions in your own code:

  • np.shares_memory(a, b) answers exactly whether two arrays share any bytes. In rare cases (large arbitrary strides) the problem is difficult and may take time; np.may_share_memory only compares address ranges and may give false positives, for example with a[::2] and a[1::2].
  • x.base points to the buffer owner, but OWNDATA = False does not imply sharing memory with your array: a[::2].T.reshape(-1) is a view of a temporary copy, with no bytes in common with a.
  • x.flags shows contiguity and permissions. In NumPy 2, np.asarray(x) never copies unnecessarily, and np.array(x, copy=False, ...) raises ValueError if satisfying the request (a dtype, order="C") requires a copy: this explicitly forbids copying. For example, np.array(a.T, copy=False, order="C") fails.

dtypes: what the bytes mean

Shape and strides say where each element is; dtype says what number its bytes represent. Dtypes and their promotion rules also determine the result dtype of an operation between different types.

dtypebytesrange or precisiontypical use
bool1False, Truemasks
uint8100 to 255255pixels, raw bytes
int8, int161, 2−128-128 to 127127; −32768-32768 to 3276732767quantization, audio
int32, uint324±2.1⋅109\pm 2.1 \cdot 10^{9}; 00 to 4.3⋅1094.3 \cdot 10^{9}indices, moderate counts
int648±9.2⋅1018\pm 9.2 \cdot 10^{18}indices, counts, seeds
float162maximum 6550465504, ε≈9.8⋅10−4\eps \approx 9.8 \cdot 10^{-4}, about 3 digitsactivations, storage
float324ε≈1.2⋅10−7\eps \approx 1.2 \cdot 10^{-7}, about 7 digitsdeep learning, GPU
float648ε≈2.2⋅10−16\eps \approx 2.2 \cdot 10^{-16}, about 16 digitsscientific computing, statistics
complex64, complex1288, 16two float32 or two float64FFT, signals

Here ε\eps is machine epsilon, the relative distance between 11 and the next representable number; floating-point representation is studied in depth in numerical methods. In practice three facts suffice. First, float32 cannot distinguish 2242^{24} from 224+12^{24} + 1: above roughly 16 million, consecutive integers cease to be representable. Second, float16 has limited range on both ends: the largest finite value is 6550465504 (every value from 6552065520 rounds to infinity), and tiny gradients below about 3⋅10−83 \cdot 10^{-8} (half the smallest subnormal, 2−242^{-24}) round to zero, which is why mixed-precision training with float16 scales losses; bfloat16, which retains the range of float32 with less precision, exists in PyTorch but not NumPy. Third, the default integer depends on the platform: np.arange(3).dtype is int64 on Linux, macOS and, since NumPy 2, Windows, but int32 on 32-bit platforms, including the WebAssembly in which this page’s cells run. That is why the cells always specify dtype.

NumPy integers use modular arithmetic: a uint8 lives in Z/256Z\Z/256\Z and an int32 in two’s complement, in [−231,231)[-2^{31}, 2^{31}). On arrays, overflow produces no warning: 250+10250 + 10 in uint8 gives 260 mod 256=4260 \bmod 256 = 4. Only operations between NumPy scalars produce a RuntimeWarning, and only sometimes. Floating-point to integer conversions truncate toward zero (3.7→33.7 \to 3, −3.7→−3-3.7 \to -3), and if the value does not fit the target type the result is undefined and platform-dependent.

Since dtype is just metadata, it can also be changed without touching the bytes: x.view(np.uint8) is a view that reads the same buffer as individual bytes, and np.array([1.0]).view(np.uint8) gives [0, 0, 0, 0, 0, 0, 240, 63], the eight bytes of 1.01.0 seen in the first cell. This is the difference between view(dtype), which reinterprets, and astype(dtype), which converts each value and copies.

Before NumPy 2, “value-based casting” applied: uint8_array + 300 promoted to uint16 because 300 does not fit in one byte, while uint8_array + 100 stayed uint8: the type depended on the value. NEP 50 removed this, and code that worked with NumPy 1 can change dtype or raise OverflowError after upgrading. The cell covers the important cases.

[ ]Silent overflow and type promotionBrowser
img = np.array([250, 120, 30], dtype=np.uint8)
print("img + 10        ", img + 10, img.dtype)                       # 260 -> 4: módulo 256, sin aviso
print("(img + img) // 2", (img + img) // 2)                          # la media de dos imágenes, mal
print("bien            ", ((img.astype(np.uint16) + img) // 2).astype(np.uint8))

n = np.array([100_000], dtype=np.int32)
print("pares n(n-1)/2 en int32:", n * (n - 1) // 2, " en int64:", n.astype(np.int64) * (n - 1) // 2)

casos = {
    "uint8 + 1 (int de Python)": lambda: np.array([1], np.uint8) + 1,
    "float32 + 3.1 (float de Python)": lambda: np.array([1], np.float32) + 3.1,
    "float32 + np.float64(3.1)": lambda: np.array([1], np.float32) + np.float64(3.1),
    "int8 + 1.0": lambda: np.array([1], np.int8) + 1.0,
    "int8 + uint8": lambda: np.array([1], np.int8) + np.array([1], np.uint8),
    "int64 + uint64": lambda: np.array([1], np.int64) + np.array([1], np.uint64),
    "int32 + float32": lambda: np.array([1], np.int32) + np.array([1], np.float32),
    "int32 / int32": lambda: np.array([3], np.int32) / np.array([2], np.int32),
    "uint8 + 300": lambda: np.array([1], np.uint8) + 300,
}
for nombre, f in casos.items():
    try:
        r = f()
        print(f"{nombre:32s} -> {str(r.dtype):8s} {r}")
    except Exception as e:
        print(f"{nombre:32s} -> {type(e).__name__}: {e}")
print("float16: máximo", np.finfo(np.float16).max, " eps", np.finfo(np.float16).eps)
print("float32: eps", np.finfo(np.float32).eps, " 2**24 + 1 =", np.float32(2**24) + np.float32(1))
print("entero por defecto en esta plataforma:", np.arange(3).dtype)

The case float32 + np.float64(3.1) causes many inadvertent promotions: a scalar from a reduction in float64 (a separately computed mean, an np.pi converted with np.float64) converts an entire float32 array to float64, doubling memory and time; with tensors on a consumer GPU, where float64 is tens of times slower than float32, the cost is much higher. A Python float, by contrast, is harmless.

Sliding windows: custom strides

So far NumPy chose the strides. Nothing prevents choosing them by hand, and the most useful application is sliding windows. Given a series x0,…,xn−1x_0, \dots, x_{n-1}, a window of size kk, and a step pp, the window matrix is

Wij=xip+j,0≤i<m,0≤j<k,m=⌊n−kp⌋+1.W_{ij} = x_{ip + j}, \qquad 0 \le i < m, \quad 0 \le j < k, \qquad m = \left\lfloor \frac{n - k}{p} \right\rfloor + 1.

If xx has stride σ\sigma, the address of WijW_{ij} is o+(ip+j)σ=o+i (pσ)+j σo + (ip + j)\sigma = o + i\,(p\sigma) + j\,\sigma: an affine map of (i,j)(i, j). Thus WW is a view of shape (m,k)(m, k) and strides (pσ,σ)(p\sigma, \sigma), copying not one byte even though it contains mkmk elements. These arbitrary-stride views are constructed in two ways:

  • np.lib.stride_tricks.as_strided(x, shape, strides) creates the requested view without checking anything at all.
  • np.lib.stride_tricks.sliding_window_view(x, k) calculates shape and strides for you, returns a read-only view by default, and supports multiple axes; the step is applied afterward by slicing, sliding_window_view(x, k)[::p].
InteractiveSliding windows with strides
W = sliding_window_view(x, 4)[::2]
x in memory · bars show the bytes read by row 1 of W30×158×1416×2624×2832×2740×2948×21256×21064×21172×21380×11288×1?96?104?112?120end of bufferW, shape (5, 4)mean035464.50146876.252879129.003912101110.5041011131211.50
complete
  • aligned read
  • misaligned (garbage)
  • outside the buffer
  • ×n: windows sharing the element
Construction
Function
4
2
shape of W(5, 4)
strides (bytes)(16, 8)
new memory for the view0 B (uses the 96 B of x)
memory required for a copy160 B
W[1,0]W[1, 0] reads byte 1·16 + 0·816 → 4
Rows: m=⌊(12−4)/2⌋+1=5m = \lfloor (12 - 4) / 2 \rfloor + 1 = 5. The most shared element appears in 2 windows, at most ⌈k/s⌉=2\lceil k/s \rceil = 2, with one copy in memory.
A series of 12 float64 values (96 bytes) and its window matrix. With sliding_window_view, change kk and step ss: rows overlap on the same bytes, and the number under each element counts how many windows share it. Play to see the matrix built row by row; bars above the strip mark the bytes read by the current row. Then switch to as_strided and try the examples: one extra row reads beyond the buffer, and strides in elements instead of bytes mix bytes from two numbers on each read and produce garbage.

The interactive shows the two risks of as_strided. An extra row makes the last window end beyond the 96-byte buffer: NumPy reads whatever is in that memory (another object, garbage) or the process dies with a segmentation fault, without a Python error. Strides in elements, (2, 1) instead of (16, 8), make each read start halfway through a float64: the resulting values are tiny or huge numbers unrelated to the series. sliding_window_view makes both errors impossible, so it is the default choice; reserve as_strided for constructions the library does not offer.

The two-axis version uses the same idea. sliding_window_view(img, (kh, kw)) on an image with strides (s0,s1)(s_0, s_1) is a four-axis view with strides (s0,s1,s0,s1)(s_0, s_1, s_0, s_1), containing all kh×kwkh \times kw patches without copying. Converting it to a matrix of (parches,kh⋅kw)(\text{parches}, kh \cdot kw) (patches by flattened patch size) for multiplication by filters is a reshape that must merge the patch’s two axes, whose strides (s0,s1)(s_0, s_1) have s0=Ws1≠kw s1s_0 = W s_1 \ne kw\, s_1 for a C-contiguous image of width W>kwW > kw, and by the reshape theorem it copies: that is im2col’s memory cost, multiplying the image by kh⋅kwkh \cdot kw.

With this model, the rolling-statistics lab is straightforward. We construct the window matrix of a synthetic price series, calculate means and deviations per row, and compare with a loop, with sliding_window_view, and with the cumulative-sum formula. Finally we provoke the error of writing to an overlapping view.

[ ]Rolling statistics without copiesBrowser
from numpy.lib.stride_tricks import as_strided, sliding_window_view
import time

rng = np.random.default_rng(42)
n, k = 20_000, 50
precios = 100 * np.exp(np.cumsum(0.01 * rng.standard_normal(n)))   # paseo aleatorio geométrico

t0 = time.perf_counter()
media_bucle = np.array([precios[i:i + k].mean() for i in range(n - k + 1)])
t_bucle = time.perf_counter() - t0

s = precios.strides[0]                                              # 8 bytes
W = as_strided(precios, shape=(n - k + 1, k), strides=(s, s), writeable=False)
t0 = time.perf_counter()
media_W, std_W = W.mean(axis=1), W.std(axis=1)
t_vista = time.perf_counter() - t0

V = sliding_window_view(precios, k)
print("medias iguales al bucle:", np.allclose(media_bucle, media_W), "| W == V:", np.array_equal(W, V))
print("std de la ventana 1234:", np.isclose(std_W[1234], precios[1234:1234 + k].std()))
print(f"bucle {t_bucle * 1e3:.0f} ms, vista {t_vista * 1e3:.1f} ms")
print(f"W.nbytes = {W.nbytes / 1e6:.2f} MB (lógicos); comparte memoria con precios: {np.shares_memory(W, precios)};"
      f" precios ocupa {precios.nbytes / 1e6:.2f} MB")

# media móvil en O(n) con sumas acumuladas
c = np.concatenate([[0.0], np.cumsum(precios)])
media_cumsum = (c[k:] - c[:-k]) / k
print("máx |media con cumsum − media con la vista| =", np.abs(media_cumsum - media_W).max())

# escribir en una vista solapada: centrar cada ventana en el sitio
x = np.array([3.0, 5, 4, 6, 8, 7, 9, 12])
Wx = sliding_window_view(x, 3, writeable=True)
esperado = Wx - Wx.mean(axis=1, keepdims=True)       # en un array nuevo: correcto
Wx -= Wx.mean(axis=1, keepdims=True)                 # en el sitio: cada byte se escribe varias veces
print("x tras centrar en el sitio:", x.round(2))
print("¿coincide con lo esperado?", np.allclose(Wx, esperado))

Four readings of the output. The view is tens of times faster than the loop, because the 19 951 means are calculated in a single C traversal. W.nbytes reports almost 8 MB, but that is the logical size: the actual buffer is the 0.16 MB of precios, as np.shares_memory confirms. The cumulative-sum formula is cheaper still, O(n)\bigO(n) versus O(nk)\bigO(nk), at the cost of a small rounding error that grows with series length because it subtracts large, similar numbers. The final line shows corruption: each element of x belongs to several windows, each window subtracts a different mean, and the last write wins. The result is nobody’s window-centered series. Pandas rolling statistics solve the general case, and moving averages as filters are studied in time series.

Contiguity and performance

An operation being a view does not mean it is free to use. Memory is not read byte by byte: it moves in 64-byte cache lines. Traversing a float64 array with stride 8 uses all 8 numbers in each loaded line; traversing with stride 64 or more loads a whole line to use one number, eight times the traffic for the same calculation. This is cache locality, and its array version is simple: traverse in memory order.

[ ]The cost of strided traversalBrowser
def mejor(f, rep=7):
    ts = []
    for _ in range(rep):
        t0 = time.perf_counter()
        f()
        ts.append(time.perf_counter() - t0)
    return min(ts)

x = np.ones(8_000_000)                 # 64 MB
seguido = x[:1_000_000]                # un millón de elementos contiguos: stride 8 B
a_saltos = x[::8]                      # un millón de elementos con stride 64 B: uno por línea de caché
print(f"suma de 1M contiguos: {mejor(seguido.sum) * 1e3:6.2f} ms")
print(f"suma de 1M a saltos:  {mejor(a_saltos.sum) * 1e3:6.2f} ms   (mismo número de sumas)")

A = np.ones((2000, 2000))
print(f"A.T:        {mejor(lambda: A.T) * 1e6:8.1f} µs   (solo metadatos)")
print(f"A.copy():   {mejor(A.copy) * 1e3:8.1f} ms")
print(f"A.T.copy(): {mejor(A.T.copy) * 1e3:8.1f} ms   (lee con saltos de 16 000 B)")

The two sums perform exactly the same arithmetic on the same number of elements, and the jumping one takes several times longer; in this page’s Pyodide, five to seven times. The same holds for copies: A.copy() reads and writes in order, whereas A.T.copy() writes in order but reads jumping 16 000 bytes at each step. And A.T itself costs nothing measurable beyond creating the object. Three practical consequences:

  • Copy before repeated traversal. If you will traverse a noncontiguous view several times (an a.T entering a loop, a column of a large matrix), it may pay to call np.ascontiguousarray once: one jumping traversal to copy and the rest in order. If the array is already C-contiguous, np.ascontiguousarray returns it unchanged, without copying.
  • Implicit copies exist. Many functions need contiguous memory and silently copy when it is absent: reshape after transpose, BLAS calls with unsupported strides, np.ravel of something noncontiguous, conversion to other libraries. The cost does not appear in the code; it appears in the memory profile.
  • Loop order matters. If you write a compiled loop (Numba, Cython, a GPU kernel) over a C-contiguous array, the inner index should be the last axis. On GPUs the equivalent is coalesced access, covered with the memory hierarchy.

Implementation from scratch: a toy ndarray

To check that the model is complete, we implement it without NumPy: a MiniArray class on a bytearray, with dtype, shape, strides, and offset, supporting scalar indexing, stepped slicing (including negative steps), transpose, and reshape. Values are read and written with the standard-library struct module, which converts between bytes and numbers exactly as NumPy does on a little-endian machine.

[ ]MiniArray: an ndarray over a bytearrayBrowser
import struct
from math import prod

def c_strides(shape, itemsize):
    strides, acc = [], itemsize
    for n in reversed(shape):
        strides.append(acc)
        acc *= n
    return tuple(reversed(strides))

class MiniArray:
    """Un ndarray de juguete: un bytearray compartido más (dtype, shape, strides, offset)."""
    FORMATOS = {"float64": ("d", 8), "float32": ("f", 4), "int64": ("q", 8), "int32": ("i", 4), "uint8": ("B", 1)}

    def __init__(self, buffer, dtype, shape, strides=None, offset=0):
        self.buffer = buffer                                   # bytearray: la memoria, compartida entre vistas
        self.dtype = dtype
        self.fmt, self.itemsize = self.FORMATOS[dtype]
        self.shape = tuple(shape)
        self.strides = tuple(strides) if strides is not None else c_strides(self.shape, self.itemsize)
        self.offset = offset                                   # byte del elemento [0, ..., 0]

    @classmethod
    def from_values(cls, valores, dtype, shape):
        fmt, size = cls.FORMATOS[dtype]
        buf = bytearray(len(valores) * size)
        for k, v in enumerate(valores):
            struct.pack_into("<" + fmt, buf, k * size, v)      # little-endian, como NumPy en x86 y ARM
        return cls(buf, dtype, shape)

    def _leer(self, byte):
        return struct.unpack_from("<" + self.fmt, self.buffer, byte)[0]

    def __getitem__(self, key):
        if not isinstance(key, tuple):
            key = (key,)
        key = key + (slice(None),) * (len(self.shape) - len(key))
        offset, shape, strides = self.offset, [], []
        for k, n, s in zip(key, self.shape, self.strides):
            if isinstance(k, int):                             # entero: fija el índice y elimina el eje
                if k < 0:
                    k += n
                if not 0 <= k < n:
                    raise IndexError(f"índice {k} fuera de rango para un eje de tamaño {n}")
                offset += k * s
            else:                                              # slice: desplaza el offset y escala el stride
                start, stop, step = k.indices(n)
                offset += start * s
                shape.append(len(range(start, stop, step)))
                strides.append(step * s)
        if not shape:
            return self._leer(offset)                          # escalar: dirección = offset + Σ i_k s_k
        return MiniArray(self.buffer, self.dtype, shape, strides, offset)

    @property
    def T(self):
        return MiniArray(self.buffer, self.dtype, self.shape[::-1], self.strides[::-1], self.offset)

    def es_c_contiguo(self):
        c = c_strides(self.shape, self.itemsize)
        return all(n == 1 or s == cs for n, s, cs in zip(self.shape, self.strides, c))

    def tolist(self):
        def rec(eje, offset):
            if eje == len(self.shape):
                return self._leer(offset)
            return [rec(eje + 1, offset + i * self.strides[eje]) for i in range(self.shape[eje])]
        return rec(0, self.offset)

    def copy(self):
        def aplanar(x):
            return [y for z in x for y in aplanar(z)] if isinstance(x, list) else [x]
        return MiniArray.from_values(aplanar(self.tolist()), self.dtype, self.shape)

    def reshape(self, *shape):
        assert prod(shape) == prod(self.shape), "el número de elementos debe coincidir"
        if self.es_c_contiguo():                               # orden lógico = orden de memoria: vista gratis
            return MiniArray(self.buffer, self.dtype, shape, c_strides(shape, self.itemsize), self.offset)
        return self.copy().reshape(*shape)                     # criterio conservador: copiar

m = MiniArray.from_values(range(24), "float64", (2, 3, 4))
v = m[1, ::2, ::-1]
print("v: shape", v.shape, "strides", v.strides, "offset", v.offset, "->", v.tolist())
print("¿comparte buffer con m?", v.buffer is m.buffer)

The reshape of MiniArray is deliberately conservative: it returns a view only if the array is C-contiguous and copies in every other case. It is correct (it never returns wrong values) but copies more than necessary. The comparison suite against NumPy detects this:

[ ]Test suite against NumPyBrowser
a = np.arange(24, dtype=np.float64).reshape(2, 3, 4)
m = MiniArray.from_values(a.ravel().tolist(), "float64", a.shape)

pruebas = {
    "x[1]": lambda x: x[1],
    "x[:, ::2]": lambda x: x[:, ::2],
    "x[::-1, 1:, ::3]": lambda x: x[::-1, 1:, ::3],
    "x.T": lambda x: x.T,
    "x.T[1:, ::-1]": lambda x: x.T[1:, ::-1],
    "x[0, :, 1:3]": lambda x: x[0, :, 1:3],
    "x[1, 2, -1]": lambda x: x[1, 2, -1],
    "x.reshape(6, 4)": lambda x: x.reshape(6, 4),
    "x.reshape(4, 6).T": lambda x: x.reshape(4, 6).T,
    "x.T.reshape(24)": lambda x: x.T.reshape(24),
    "x.T.reshape(2, 2, 3, 2)": lambda x: x.T.reshape(2, 2, 3, 2),
    "x[:, :, ::2].reshape(2, 6)": lambda x: x[:, :, ::2].reshape(2, 6),
}
for nombre, op in pruebas.items():
    rn, rm = op(a), op(m)
    if np.ndim(rn) == 0:
        print(f"{nombre:26s} escalar, igual: {float(rn) == rm}")
        continue
    valores = rn.tolist() == rm.tolist()
    vista_np = bool(np.shares_memory(a, rn))
    vista_mini = rm.buffer is m.buffer
    if vista_np and vista_mini:
        nota = "vista en los dos, strides iguales" if rn.strides == rm.strides else f"strides {rn.strides} frente a {rm.strides}"
    elif vista_np != vista_mini:
        nota = "NumPy: vista, MiniArray: copia" if vista_np else "MiniArray: vista, NumPy: copia"
    else:
        nota = "copia en los dos"
    print(f"{nombre:26s} valores iguales: {valores!s:5s} {nota}")

All values match and, for views, so do strides, including negative ones. The last two rows are those missed by the conservative criterion: x.T.reshape(2, 2, 3, 2) only splits axis 0 of x.T, and x[:, :, ::2].reshape(2, 6) merges two axes satisfying sk=nk+1sk+1s_k = n_{k+1}s_{k+1} even though the array is not contiguous. Replacing that criterion with the reshape theorem is the final coding exercise.

The same model in PyTorch

A torch.Tensor is exactly this structure: a storage (the buffer, on CPU or GPU), a size, strides, and a storage_offset. Three convention differences are useful to remember when moving between the two: PyTorch measures strides in elements, not bytes; it does not support negative strides, so torch.flip copies; and it distinguishes with two methods what NumPy combines into one.

import torch, numpy as np

t = torch.arange(12.).reshape(3, 4)
t.stride(), t.T.stride()           # (4, 1), (1, 4): en elementos, no en bytes
t[:, 1:].storage_offset()          # 1
t.T.is_contiguous()                # False

t.T.view(-1)                       # RuntimeError: view size is not compatible with input tensor's
                                   # size and stride ... Use .reshape(...) instead.
t.T.reshape(-1)                    # funciona: copia, porque ninguna vista lo describe
t.T.reshape(2, 2, 3)               # vista: solo parte un eje, igual que en NumPy
t.T.contiguous().stride()          # (3, 1): copia a orden C

torch.arange(4.).expand(3, 4).stride()   # (0, 1): el broadcast_to de PyTorch, con stride 0
torch.arange(10.).unfold(0, 4, 2)        # ventanas de tamaño 4 y paso 2: vista de strides (2, 1)

a = np.arange(6.0)
torch.from_numpy(a[::2]).stride()  # (2,): comparte la memoria de a
torch.from_numpy(a[::-1])          # ValueError: At least one stride in the given numpy array is negative

view is the strict version: it returns a view or raises an error, never copies. reshape is permissive: a view if possible, otherwise a copy, exactly according to the theorem’s criterion. contiguous() copies to C order only if needed. Full PyTorch view semantics, including in-place operations and their interaction with autograd, are in the PyTorch tensors lesson; this is the same idea as tensor reshaping from the perspective of each axis’s meaning.

Common mistakes

Exercises

NumericFirst-axis stride
A C-contiguous float32 array has shape (8,16,32)(8, 16, 32). What is the stride, in bytes, of axis 0?
NumericAddress of a view element
Let a = np.arange(60, dtype=np.float32).reshape(3, 4, 5) and v = a[1:, ::2, ::-1]. At what byte, counted from the start of the buffer of a, is v[1, 1, 0]?
QuizChains of operations
Let a = np.zeros((6, 8)), of float64 with strides (64,8)(64, 8). Which expressions return a view of a? There may be several.

More than one answer may be correct.

QuizContiguous in both orders
Which arrays are both C-contiguous and F-contiguous according to NumPy?

More than one answer may be correct.

NumericThe mean of two images
Two uint8 images have value 250 at the same pixel. What value does (img1 + img2) // 2 give at that pixel?
QuizPromotion in NumPy 2
Which statements are true in NumPy 2 (NEP 50 rules)?

More than one answer may be correct.

NumericThe cost of copying windows
x is a float32 series of 10610^6 elements and W = sliding_window_view(x, 250)[::5]. How many bytes would W.copy() occupy?
CodeCan this reshape be a view?
Implement reshape_as_view(shape, strides, new_shape). It receives an array's shape and strides (in bytes) and a new shape with the same number of elements (neither of size 0). Return a tuple of strides for the new shape if the C-order reshape can be expressed as a view, or None if it requires a copy. Tests compare against np.shares_memory(a, a.reshape(new_shape)) for transposed, trimmed, stepped arrays, size-1 axes and stride 0, and use as_strided to check that your strides exactly reproduce a.reshape(new_shape). Size-1 axes may receive any stride.
def reshape_as_view(shape, strides, new_shape):
  # 1) quita los ejes de tamaño 1 de la forma vieja
  # 2) recorre las dos formas por bloques con el mismo producto
  # 3) en cada bloque: los ejes viejos deben cumplir s_k == n_{k+1} * s_{k+1};
  #    los nuevos reciben strides de orden C escalados por el stride del eje viejo más interno
  pass
Shift+Enter to run

Summary

Key idea
An ndarray is a byte buffer plus a recipe: dtype, shape, strides, and offset. Each element’s address is an affine function of its indices, o+∑kiksko + \sum_k i_k s_k, and everything else follows from this rigid form: an operation is a view exactly when the result is again affine over the same buffer.
  • Anatomy. The buffer does not move; views change shape, strides (in bytes, possibly negative or zero), and offset. base, OWNDATA, WRITEABLE, and np.shares_memory say who owns what.
  • Strides. In C order, sk=σ∏j>knjs_k = \sigma\prod_{j>k} n_j, and the flat index is a mixed-radix representation. Contiguous means logical order traverses memory without gaps; size-1 axes do not count.
  • Views and copies. Basic slicing, transposes, new axes, and broadcast_to are views. Advanced indexing, masks, astype, and flatten copy. A reshape is a view if and only if it need not merge axes with sk≠nk+1sk+1s_k \ne n_{k+1}s_{k+1}.
  • dtypes. Integers use modular arithmetic without warnings; float16, float32, and float64 trade memory for precision. In NumPy 2, result dtype depends only on types, and Python scalars are weak.
  • Windows. A series’ windows form a view with strides (pσ,σ)(p\sigma, \sigma): sliding_window_view constructs it safely, as_strided without a safety net. Do not write to overlapping views.
  • Performance and PyTorch. Strided traversal multiplies memory traffic; copy to contiguous storage if traversing many times. PyTorch uses the same model, with strides in elements, no negative strides, and view (strict) versus reshape (permissive).