TensorTau PathToAGI Neural Networks from First Principles Level 06

Level 06 · Neural Networks from First Principles · Chapter 087

Batch Computation

How can a network process many examples at once without writing a loop around every neuron?

1. Stack examples into a matrix

One example may be a feature vector [D]. Stack BB examples:

X∈RB×D.X\in\mathbb R^{B\times D}.

A dense layer then computes

Z=XW+bZ=XW+b

for every example simultaneously.

X [B,D] @ W [D,H] → [B,H]
                         + b [H]

Broadcasting adds the same learned bias to each row.

2. Why batches are efficient

Modern CPUs/GPUs are optimized for large vectorized matrix operations. One matrix multiplication usually uses hardware far better than thousands of tiny Python loops.

Batches also create the gradient estimate used by stochastic optimization.

3. Per-example versus reduced loss

Suppose predictions and targets have shape [B,C]. Cross-entropy can first produce one loss per example [B], then reduce:

loss = losses.mean()

If we average, parameter gradients represent the average contribution of the batch. If we sum, gradient magnitude grows roughly with batch size.

4. Shape Check: images

PyTorch convolution normally expects

[B,C,H,W]

A batch of 32 RGB 224×224 images is

[32,3,224,224]

Batch is an axis, not a neural-network layer.

5. Batches are also statistics

Batch size affects gradient noise, memory usage, throughput and sometimes normalization. We will study mini-batches explicitly in Chapter 92.

What to Remember

Batch computation stacks examples along a new axis and lets tensor operations process them together. Trace shapes before code.

Next → Build a Neural Network Without Autograd: can we now wire forward pass, loss and manual backward rules into a complete learner?

Six ways to work the chapter, climbing from explaining it in your own words to investigating it like a researcher. Reading is not enough — this is where the chapter lands.

  1. Explain: Batch dimension versus feature dimension.
  2. Calculate: Determine output shapes for [64,128]@[128,32].
  3. Predict: How does summing rather than averaging loss affect gradient scale as batch size doubles?
  4. Break: Feed HWC/BHWC data to an operation expecting BCHW and diagnose.
  5. Build: Vectorize a loop-based dense layer over a batch.
  6. Investigate: Benchmark loop versus vectorized execution for increasing batch sizes.