x = torch.arange(12, dtype=torch.float32)
xDive into Deep Learning · §1.1
Tensors as Contiguous Memory, Geometric Views, and Parallel Compute
storage buffers · shapes & dtypes · zero-copy views · broadcasting · memory control
Motivation
PyObject*): Chasing 8-byte pointers to scattered 24-byte heap boxes causes cache misses and interpreter loop overhead.uint8, float32, bfloat16) sit back-to-back in RAM/HBM, feeding one vectorized CPU/GPU kernel + autograd.Systems View
Every tensor pairs a 1D contiguous storage buffer with a small metadata header (shape, strides, offset, dtype):
\textrm{index}(i_0, \ldots, i_{k-1}) = \textrm{offset} + \sum_{r=0}^{k-1} i_r s_r
X[1:3], transpose, broadcasting s_r = 0, and contiguous reshape where views are supported) create a new header over the same buffer.X + Y, gather, mask, cat) write a brand-new buffer.Geometry
() (e.g., loss \mathcal{L}) \;\to\; 1D vector (d,) (bias \mathbf{b}) \;\to\; 2D matrix (n, d) (weights \mathbf{W}).(N, C, H, W): our running Fashion-MNIST minibatch (256, 1, 28, 28) holds 256 \times 1 \times 28 \times 28 = 200{,}704 pixels.Getting Started
arange(n) allocates a 1D tensor of n sequential values [0, 1, \ldots, n-1] in a single contiguous buffer..shape (axis lengths) and element count (.numel() or .size, always equal to \prod_r d_r).tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.])
Data Types
float32 (4 B): Default for master weights, gradients, and loss reductions (4\text{ GB} / 10^9 params).bfloat16 (2 B): Keeps float32’s 8-bit exponent (same dynamic range, avoiding overflow) while halving HBM traffic for Tensor Core matmuls.uint8 (1 B) & int64 (8 B): Compact raw image pixels (0\ldots 255) and exact class/token indices.(torch.Size([256, 1, 28, 28]), torch.uint8)
Initialization
zeros and ones allocate fixed buffers for biases, padding masks, and accumulators; Python lists build small lookup tables.randn) breaks symmetry.Reproducibility
Reshaping
x.reshape(3, 4) replaces shape (12,) with (3, 4) without moving the 12 elements (row-major order: column stride 1, row stride 4).reshape updates only shape/stride metadata in O(1) time (allocating a copy only when strides are non-contiguous or the backend copies).tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
Reshaping in Pipelines
-1: images.reshape(-1, 784) infers batch size \textrm{size}/784 = 256 and survives smaller final epoch batches.None / squeeze): None inserts a length-1 axis for batching or broadcasting; squeeze drops length-1 axes.torch.Size([256, 784])
Subsetting
X[-1] returns the last row as a 1D vector (4,); images[0] returns one image (1, 28, 28).start:stop) preserves the axis (order stays unchanged): X[1:3] returns rows 1 and 2 as a (2, 4) matrix view; images[:32] takes a 32-image sub-batch.(torch.Size([1, 28, 28]), torch.Size([32, 1, 28, 28]), torch.Size([256]))
Check Your Understanding
Given images of shape (256, 1, 28, 28), predict the output shape and memory behavior of each expression:
images[5] versus images[5:6]images[:64, :, ::2, ::2]images.reshape(256, -1) versus images.reshape(-1, 784) on a final epoch batch of 96 images (96, 1, 28, 28)Answers:
images[5] has shape (1, 28, 28) (axis 0 removed); images[5:6] has shape (1, 1, 28, 28) (axis 0 kept with length 1). Both are O(1) zero-copy views.(64, 1, 14, 14): takes 64 images and every second row/column by doubling spatial strides, still a strided slice.reshape(256, -1) raises an error (96 \times 784 is not divisible by 256); reshape(-1, 784) safely infers (96, 784).Selective Indexing
where: Masking collapses matches to a 1D vector, whereas where(mask, X, 0) preserves the 2D shape for ReLU and attention masks.tensor([ 3., 4., 10.])
Views & Mutation
X = x.reshape(3, 4) is a view sharing x’s storage buffer, X[1, 2] = 17 writes to offset 1 \times 4 + 2 = 6 in place, mutating x[6] to 17 as well.(tensor([[ 0., 1., 2., 3.],
[ 4., 5., 17., 7.],
[ 8., 9., 10., 11.]]),
tensor([ 0., 1., 2., 3., 4., 5., 17., 7., 8., 9., 10., 11.]))
Elementwise Compute
+, -, *, /, **, exp) apply element-by-element: c_i = f(x_i, y_i). Note that x * y is the Hadamard product \mathbf{x} \odot \mathbf{y}, not a matrix product.(tensor([ 3., 4., 6., 10.]),
tensor([-1., 0., 2., 6.]),
tensor([ 2., 4., 8., 16.]),
tensor([0.5000, 1.0000, 2.0000, 4.0000]),
tensor([ 1., 4., 16., 64.]))
uint8 pixels images by 255 promotes the output to float32 in [0, 1] (0.8\text{ MB}), ready for gradient computation.torch.float32
tensor([102, 121, 210, 214], dtype=torch.uint8)
tensor([0.4000, 0.4745, 0.8235, 0.8392])
Comparisons & Reductions
x == y, x < y, x >= y) return a Boolean mask tensor of the exact same shape.sum, mean, max) aggregate across one or all axes; reducing all axes yields a 0D scalar tensor ().True counts as 1 and False as 0, (predictions == labels).sum() counts correct predictions without loops.Broadcasting
When two shapes differ, broadcasting aligns and virtually expands length-1 axes in two steps:
1 axes to the lower-order tensor: (3, 4) and (4,) align as (3, 4) and (1, 4).1.Zero-copy trick: Stretching a length-1 axis to length n sets its stride to 0, so the kernel reads the same memory address n times without copying data.
Broadcasting Pitfalls
(3, 2) + (2, 3)): Trailing axes 2 \neq 3 neither match nor equal 1.(B, 1) − (B,) \to (B, B)): Right-alignment treats y: (B,) as (1, B), turning y_hat - y into all B^2 pairwise differences.The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1
Combining Tensors
concatenate / cat joins along an existing axis (order unchanged):
axis=0 stacks rows: (3, 4) + (3, 4) \to (6, 4) (merging batches).axis=1 joins columns: (3, 4) + (3, 4) \to (3, 8) (fusing features).stack creates a new axis (order +1): stacking two (3, 4) matrices gives (2, 3, 4) on axis=0 or (3, 4, 2) on axis=2.(torch.Size([2, 3, 4]), torch.Size([3, 4, 2]))
Memory Efficiency
Y = Y + X): Evaluates Y + X into a new buffer and rebinds Y (id(Y) changes; costs 4\text{ GB} per temporary on 10^9 float32 parameters).Z[:] = X + Y or X += Y): Writes directly into the existing buffer (id unchanged). Use for optimizer steps, never on activations needed for backward gradients.True
Ecosystem Bridge
X.numpy() / torch.from_numpy(A)): Shares the same contiguous RAM buffer (zero copy), so mutating A mutates X and B..item(), float()): Converts a 1-element tensor to a Python number (triggers a GPU–CPU sync barrier, so log periodically).(tensor(100.), tensor(100.))
Key Takeaways
| Operation | Example | Output Shape | Memory Behavior | Primary Deep Learning Role |
|---|---|---|---|---|
| Reshape / Flatten | images.reshape(-1, 784) |
(256, 784) |
View (O(1) if contiguous) or copy | Bridge 4D spatial tensors to 2D linear layers |
| Slice / Stride | images[:32], X[1:3] |
(32, 1, 28, 28) |
Zero-copy view (O(1)) | Micro-batching, cropping, strided subsampling |
| Broadcasting | X + b ((3, 4) + (4,)) |
(3, 4) |
Virtual stride = 0 | Per-channel biases, batch normalization |
| Gather / Mask | X[rows, cols], X[mask] |
(3,), (k,) |
New buffer (O(k) copy) | Cross-entropy target log-probs, filtering |
| Concat / Stack | cat([X, Y], 0), stack |
(6, 4), (2, 3, 4) |
New buffer (O(N) copy) | Feature fusion (axis=1), minibatch assembly |
| In-Place Update | X += Y, Z[:] = X + Y |
Unchanged | Reuses buffer | Optimizer parameter steps (W \leftarrow W - \eta \nabla \mathcal{L}) |