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 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)raisesRuntimeError: view size is not compatible with input tensor's size and stride, whereast.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:
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, , 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 and 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 :
For a matrix of float64 () this gives in C order and in F order. In C order, the flat index is a number written in mixed radix: digit counts units, digit 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.
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 , or a matrix with stride 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.
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 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
int8tofloat64multiplies strides and offset by the itemsize and changes nothing else: strides are element counts multiplied by as long as you do not reinterpret the bytes. - Some reshapes copy.
a.T.reshape(12)cannot be a view: logical traversal ofa.Tvisits positions , 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 on the same buffer. The table summarizes common operations.
| Operation | Result | New metadata |
|---|---|---|
a[i0:i1:p] on one axis (basic slicing) | view | , , |
a[i] with an integer | view (if axes remain) | and the axis disappears |
a.T, transpose, swapaxes | view | shape and strides are permuted |
a[:, None], squeeze, expand_dims | view | a size-1 axis is added or removed |
np.broadcast_to | read-only view | stride 0 on stretched axes |
reshape, ravel | view if possible, otherwise copy | see theorem below |
flatten, copy | always copies | |
| indexing with lists or integer arrays | always copies | |
| Boolean masks | always copies | |
astype | copy (except copy=False with the same dtype) | |
a + b, np.exp(a), any ufunc | new array | |
a += b, out=, a[...] = b | write to the existing buffer |
The lower rows deserve justification. A set of positions accessible with a one-axis view is an arithmetic progression ; more generally, the image of a box under an affine map. a[[0, 1, 3]] on a vector requests positions , 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 and stride becomes two axes with strides : element was at .
- Merging two axes is not always possible. Axes and , both larger than 1, can be merged into one of size if and only if . If the merged axis has stride , logical element (formerly ) is at and , so ; logical element (formerly ) is at and . Conversely, if equality holds, and stride 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 , its internal flat index , and the old contribution to the address .
Sufficiency. If all old axes of the block satisfy the condition, applying it from inside out gives : these are the block shape’s C-order strides scaled by , and by the C-order stride theorem, . The block behaves like a single axis of stride , and splitting an axis into is always possible with the stated strides.
Necessity. Suppose there is a view and the condition fails; let be the largest index in the block with . Axes do satisfy the condition, so they form a merged axis of size and for ; moreover , because is the index with 1 on axis and zeros afterward. Call the new shape’s cumulative products from the right , strictly decreasing from to . We have (axis is outside and axis inside, both of size greater than 1), and is no : if , the cumulative products from the left and would agree at an internal cut in the block, contradicting its minimality. Thus some satisfies . For , the new view uses only axes : . Since on and , we obtain for and . Then for all , in particular for : , contradicting the choice of .
∎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 and strides , shape forms one block with both axes and requires : it copies. Shape forms two blocks, and , neither merges anything, and it is a view with strides . 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.
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_memoryonly compares address ranges and may give false positives, for example witha[::2]anda[1::2].x.basepoints to the buffer owner, butOWNDATA = Falsedoes not imply sharing memory with your array:a[::2].T.reshape(-1)is a view of a temporary copy, with no bytes in common witha.x.flagsshows contiguity and permissions. In NumPy 2,np.asarray(x)never copies unnecessarily, andnp.array(x, copy=False, ...)raisesValueErrorif 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.
| dtype | bytes | range or precision | typical use |
|---|---|---|---|
bool | 1 | False, True | masks |
uint8 | 1 | to | pixels, raw bytes |
int8, int16 | 1, 2 | to ; to | quantization, audio |
int32, uint32 | 4 | ; to | indices, moderate counts |
int64 | 8 | indices, counts, seeds | |
float16 | 2 | maximum , , about 3 digits | activations, storage |
float32 | 4 | , about 7 digits | deep learning, GPU |
float64 | 8 | , about 16 digits | scientific computing, statistics |
complex64, complex128 | 8, 16 | two float32 or two float64 | FFT, signals |
Here is machine epsilon, the relative distance between and the next representable number; floating-point representation is studied in depth in numerical methods. In practice three facts suffice. First, float32 cannot distinguish from : above roughly 16 million, consecutive integers cease to be representable. Second, float16 has limited range on both ends: the largest finite value is (every value from rounds to infinity), and tiny gradients below about (half the smallest subnormal, ) 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 and an int32 in two’s complement, in . On arrays, overflow produces no warning: in uint8 gives . Only operations between NumPy scalars produce a RuntimeWarning, and only sometimes. Floating-point to integer conversions truncate toward zero (, ), 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 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.
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 , a window of size , and a step , the window matrix is
If has stride , the address of is : an affine map of . Thus is a view of shape and strides , copying not one byte even though it contains 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].
float64 values (96 bytes) and its window matrix. With sliding_window_view, change and step : 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 is a four-axis view with strides , containing all patches without copying. Converting it to a matrix of (patches by flattened patch size) for multiplication by filters is a reshape that must merge the patch’s two axes, whose strides have for a C-contiguous image of width , and by the reshape theorem it copies: that is im2col’s memory cost, multiplying the image by .
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.
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, versus , 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.
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.Tentering a loop, a column of a large matrix), it may pay to callnp.ascontiguousarrayonce: one jumping traversal to copy and the rest in order. If the array is already C-contiguous,np.ascontiguousarrayreturns 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.ravelof 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.
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:
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 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
float32 array has shape . What is the stride, in bytes, of axis 0?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]?a = np.zeros((6, 8)), of float64 with strides . Which expressions return a view of a? There may be several.More than one answer may be correct.
More than one answer may be correct.
uint8 images have value 250 at the same pixel. What value does (img1 + img2) // 2 give at that pixel?More than one answer may be correct.
x is a float32 series of elements and W = sliding_window_view(x, 250)[::5]. How many bytes would W.copy() occupy?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
passSummary
- Anatomy. The buffer does not move; views change shape, strides (in bytes, possibly negative or zero), and offset.
base,OWNDATA,WRITEABLE, andnp.shares_memorysay who owns what. - Strides. In C order, , 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_toare views. Advanced indexing, masks,astype, andflattencopy. A reshape is a view if and only if it need not merge axes with . - dtypes. Integers use modular arithmetic without warnings;
float16,float32, andfloat64trade 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 :
sliding_window_viewconstructs it safely,as_stridedwithout 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) versusreshape(permissive).