Data Manipulation

Dive into Deep Learning · §1.1

Tensors as Contiguous Memory, Geometric Views, and Parallel Compute
storage buffers · shapes & dtypes · zero-copy views · broadcasting · memory control

Why Tensors? From Python Pointers to Parallel Kernels

Motivation

  • Batch scale: One 256-image Fashion-MNIST batch (28 \times 28) holds 200{,}704 pixels; modern networks update billions of parameters per step.
  • Python lists (PyObject*): Chasing 8-byte pointers to scattered 24-byte heap boxes causes cache misses and interpreter loop overhead.
  • Contiguous tensor buffers: Unboxed values (uint8, float32, bfloat16) sit back-to-back in RAM/HBM, feeding one vectorized CPU/GPU kernel + autograd.

The Unifying Mental Model: Storage Buffer + Metadata Header

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

  • O(1) strided views (slices X[1:3], transpose, broadcasting s_r = 0, and contiguous reshape where views are supported) create a new header over the same buffer.
  • O(N) allocations (X + Y, gather, mask, cat) write a brand-new buffer.

Axes, Order (Rank), and Shape

Geometry

  • Order (rank) is the number of axes; shape lists each axis length; size is their product:
    • 0D scalar () (e.g., loss \mathcal{L}) \;\to\; 1D vector (d,) (bias \mathbf{b}) \;\to\; 2D matrix (n, d) (weights \mathbf{W}).
    • 4D image batch (N, C, H, W): our running Fashion-MNIST minibatch (256, 1, 28, 28) holds 256 \times 1 \times 28 \times 28 = 200{,}704 pixels.

Creating a Tensor and Inspecting Its Metadata

Getting Started

  • arange(n) allocates a 1D tensor of n sequential values [0, 1, \ldots, n-1] in a single contiguous buffer.
  • When debugging any model, check .shape (axis lengths) and element count (.numel() or .size, always equal to \prod_r d_r).
x = torch.arange(12, dtype=torch.float32)
x
tensor([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.])
x.shape
torch.Size([12])
x.numel()
12

Data Types Control Precision, Range, and Memory Footprint

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.
# 256 grayscale images of 28 x 28 pixels, each pixel an integer in [0, 255]
images = torch.randint(0, 256, (256, 1, 28, 28), dtype=torch.uint8)
images.shape, images.dtype
(torch.Size([256, 1, 28, 28]), torch.uint8)

Deterministic Construction vs. Random Weight Initialization

Initialization

  • Constants and literals: zeros and ones allocate fixed buffers for biases, padding masks, and accumulators; Python lists build small lookup tables.
  • Why weights must be random: If all neurons in a layer started with identical weights, every neuron would compute the exact same activation and receive the exact same gradient. Sampling from \mathcal{N}(0, 1) (randn) breaks symmetry.
torch.randn(3, 4)
tensor([[ 0.2763, -0.8037, -1.2709,  0.2572],
        [ 0.3519, -1.3422, -0.7240,  0.4446],
        [ 1.1666,  0.8201,  0.8971,  0.9919]])
torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
tensor([[2, 1, 4, 3],
        [1, 2, 3, 4],
        [4, 3, 2, 1]])

Reproducible Randomness: Seeds and PRNG State

Reproducibility

  • Training uses randomness everywhere: weight initialization, minibatch shuffling, dropout masks, and data augmentation.
  • Pseudorandom number generators (PRNGs) are deterministic state machines: resetting the seed reproduces the exact sequence of draws for repeatable experiments.
  • Global state: The framework advances a stateful generator with every draw, so a seed fixes the whole sequence that follows.
torch.manual_seed(42)
a = torch.randn(3)
b = torch.randn(3)  # The generator has moved on
torch.manual_seed(42)
c = torch.randn(3)  # Same seed: c repeats a
a, b, c
(tensor([0.3367, 0.1288, 0.2345]),
 tensor([ 0.2303, -1.1229, -0.1863]),
 tensor([0.3367, 0.1288, 0.2345]))

Reshaping Reinterprets Axes in Row-Major Order

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).
  • On contiguous mutable tensors, reshape updates only shape/stride metadata in O(1) time (allocating a copy only when strides are non-contiguous or the backend copies).
X = x.reshape(3, 4)
X
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]])

Automatic Dimension Inference (-1) and Singleton Axes

Reshaping in Pipelines

  • Flattening with -1: images.reshape(-1, 784) infers batch size \textrm{size}/784 = 256 and survives smaller final epoch batches.
  • Singleton axes (None / squeeze): None inserts a length-1 axis for batching or broadcasting; squeeze drops length-1 axes.
images.reshape(256, -1).shape
torch.Size([256, 784])

Indexing vs. Slicing: Rank Reduction vs. Rank Preservation

Subsetting

  • Integer indexing collapses an axis (order drops by 1): X[-1] returns the last row as a 1D vector (4,); images[0] returns one image (1, 28, 28).
  • Slicing (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.
images[0].shape, images[:32].shape, images[:, 0, 14, 14].shape
(torch.Size([1, 28, 28]), torch.Size([32, 1, 28, 28]), torch.Size([256]))

Concept Check: Predicting Shapes and Zero-Copy Views

Check Your Understanding

Given images of shape (256, 1, 28, 28), predict the output shape and memory behavior of each expression:

  1. images[5] versus images[5:6]
  2. images[:64, :, ::2, ::2]
  3. images.reshape(256, -1) versus images.reshape(-1, 784) on a final epoch batch of 96 images (96, 1, 28, 28)

Answers:

  1. 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.
  2. (64, 1, 14, 14): takes 64 images and every second row/column by doubling spatial strides, still a strided slice.
  3. reshape(256, -1) raises an error (96 \times 784 is not divisible by 256); reshape(-1, 784) safely infers (96, 784).

Integer Gather and Boolean Masking in Machine Learning

Selective Indexing

  • Integer gather: Pairs row and column indices—used in cross-entropy to pluck the true-class score per example.
  • Mask vs. where: Masking collapses matches to a 1D vector, whereas where(mask, X, 0) preserves the 2D shape for ReLU and attention masks.
rows, cols = torch.arange(3), torch.tensor([3, 0, 2])
X[rows, cols]
tensor([ 3.,  4., 10.])

Views and Mutability: Writing Through a Reshaped Tensor

Views & Mutation

  • Because 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.
X[1, 2] = 17
X, x
(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.]))
X[:2, :] = 12
X
tensor([[12., 12., 12., 12.],
        [12., 12., 12., 12.],
        [ 8.,  9., 10., 11.]])

Vectorized Elementwise Operations and Type Promotion

Elementwise Compute

  • Scalar operators (+, -, *, /, **, 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.
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2.0, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
(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.]))
  • Type promotion: Dividing uint8 pixels images by 255 promotes the output to float32 in [0, 1] (0.8\text{ MB}), ready for gradient computation.
scaled = images / 255
print(scaled.dtype, images[0, 0, 0, :4], scaled[0, 0, 0, :4], sep='\n')
torch.float32
tensor([102, 121, 210, 214], dtype=torch.uint8)
tensor([0.4000, 0.4745, 0.8235, 0.8392])

Boolean Comparisons and Axis Reductions

Comparisons & Reductions

  • Elementwise comparisons (x == y, x < y, x >= y) return a Boolean mask tensor of the exact same shape.
  • Reductions (sum, mean, max) aggregate across one or all axes; reducing all axes yields a 0D scalar tensor ().
  • Batch accuracy in one call: Since True counts as 1 and False as 0, (predictions == labels).sum() counts correct predictions without loops.
x == y
tensor([False,  True, False, False])
x.sum(), (x == y).sum()
(tensor(15.), tensor(1))

Broadcasting: Virtual Replication Without Copying Memory

Broadcasting

When two shapes differ, broadcasting aligns and virtually expands length-1 axes in two steps:

  1. Right-align shapes and prepend length-1 axes to the lower-order tensor: (3, 4) and (4,) align as (3, 4) and (1, 4).
  2. Match or stretch: At each axis, lengths must match or one must be 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.

X = torch.arange(12, dtype=torch.float32).reshape(3, 4)
v = torch.tensor([100.0, 200, 300, 400])
X + v
tensor([[100., 201., 302., 403.],
        [104., 205., 306., 407.],
        [108., 209., 310., 411.]])

When Broadcasting Fails and When It Creates Silent Bugs

Broadcasting Pitfalls

  • Loud error ((3, 2) + (2, 3)): Trailing axes 2 \neq 3 neither match nor equal 1.
  • Silent bug ((B, 1) − (B,) \to (B, B)): Right-alignment treats y: (B,) as (1, B), turning y_hat - y into all B^2 pairwise differences.
try:
    torch.ones((3, 2)) + torch.ones((2, 3))
except Exception as e:
    print(e)
The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1

Joining Tensors: Concatenation vs. Stacking

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.stack((X, Y)).shape, torch.stack((X, Y), dim=2).shape
(torch.Size([2, 3, 4]), torch.Size([3, 4, 2]))

Controlling Memory Allocation: Rebinding vs. In-Place Updates

Memory Efficiency

  • Rebinding (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).
  • In-place (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.
Z = torch.zeros_like(Y)
before = id(Z)
Z[:] = X + Y
id(Z) == before
True

Zero-Copy Interoperability with NumPy and Python Scalars

Ecosystem Bridge

  • Shared CPU buffer (X.numpy() / torch.from_numpy(A)): Shares the same contiguous RAM buffer (zero copy), so mutating A mutates X and B.
  • Scalar extraction (.item(), float()): Converts a 1-element tensor to a Python number (triggers a GPU–CPU sync barrier, so log periodically).
A[0, 0] = 100  # Write to the NumPy array
X[0, 0], B[0, 0]
(tensor(100.), tensor(100.))
a = torch.tensor(3.5)
a, a.item(), float(a), int(a)
(tensor(3.5000), 3.5, 3.5, 3)

Summary: Metadata Views vs. Memory Allocations

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})