Lesson 1.3 — Batch Processing & Broadcasting
Give each axis a meaning
A robot records its joint angle and angular velocity at three time slots. Stack two recordings, A and B, to get a tensor X with shape (B, T, D) = (2, 3, 2).
Index in X[b, t, d] | What changes when you move along this axis |
|---|---|
| Batch | Which trajectory you read |
| Time | Which time slot you read within that trajectory |
| Feature | Which measurement you read at that time: angle or velocity |
X[1, 2, 0] is the angle from trajectory B at its third time slot. The same three indices will tell us where an operation reads from and which measurements it groups together.
Apply a rule across the batch
Suppose a sensor calibration adds a fixed offset to each feature. You can calibrate one trajectory at a time and stack the results. You can also pass the stacked input directly to one tensor operation. Both expressions give the same answer because a trajectory's calibration uses only its own readings and the fixed offsets.
Apply the rule to each trajectory
Stack A′ and B′ to form the output batch.
Apply the rule to the whole batch
Each output trajectory stays in its original batch slot.
The leading axis represents the batch in this layout. A different layout can put it elsewhere. An operation that computes a statistic across the batch can make one trajectory's result depend on other trajectories.
Trace an elementwise operation
An elementwise operation combines one pair of operands to get each output. If a separate correction tensor C has the same shape as X, adding it reads X[b,t,d] + C[b,t,d].
For sensor calibration, we need only one correction per feature. Let bias have shape (D,). The angle bias goes to every angle, and the velocity bias goes to every velocity. The output still has shape (B,T,D).
Trace the two inputs to an output
Pick any output. Each time slot contains an angle and a velocity.
| Trajectory | Time 0 | Time 1 | Time 2 |
|---|---|---|---|
| A | |||
| B |
Y[0, 1, 0]=Source readingX[0, 1, 0]+Shared biasbias[0]All shaded outputs use bias[0], the angle bias.
The same source-index rule applies to elementwise subtraction and multiplication. In Lesson 1.4 · Linear Transformations, a matrix product will combine several input features into one output.
Read the broadcast alignment
Write both shapes with the right edges aligned. Pad the shorter shape on the left with implicit axes of length 1.
| Operand | Batch | Time | Feature |
|---|---|---|---|
X · (B,T,D) | |||
bias · (D,) | (implicit) | (implicit) | |
Y · (B,T,D) |
At each aligned axis, equal lengths share the same output index. A length of 1 supplies index 0 wherever the other operand needs it. The output gets the common length or the length of the other operand. If the lengths differ and neither is 1, the operation fails. For bias, alignment leaves only in its stored index, so changes in and leave the bias source unchanged.
Broadcasting describes which input value is reused. The operation can read the same source without first copying that input across the output shape. PyTorch broadcasting semantics
Group readings along an axis
A reduction takes all the readings in a group and returns one value for that group. The selected axis tells you which index varies within a group. The other indices label the result.
| Select an axis to average | Hold these indices fixed | Result with the axis removed |
|---|---|---|
Time, dim=1 | Trajectory and feature | (B,D), one mean per trajectory and feature |
Batch, dim=0 | Time and feature | (T,D), one mean per time and feature |
For example, the time mean is . The sum varies with and fixed. A sum or a maximum uses the same grouping and returns a different statistic. PyTorch mean
Broadcast the statistic back
To center each trajectory around its own time mean, every point on trajectory should subtract the same . With a constant baseline, subtracting it shifts the trajectory vertically and preserves differences over time.
Use X.mean(dim=1, keepdim=True) to keep time as a single slot in the mean tensor. The mean at mu[b,0,d] can then be reused across time. Removing the axis gives the same mean values in a layout with one fewer dimension.
Mean aligned under X | Batch slot | Time slot | Feature slot |
|---|---|---|---|
X | |||
| Keep the time axis | |||
| Drop the time axis | (implicit) |
With two trajectories and three time slots, dropping the axis produces a mismatch between 2 and 3. If the recordings instead have two time slots, those lengths match and the subtraction reads m[t,d]. A trajectory's early reading now uses A's mean and its late reading uses B's. Tracing the source index catches the error even when the output shape looks right.
If you already have m of shape (B,D), m.unsqueeze(1) restores the time slot before subtraction.
Fit a feature normalizer on training data
For a shared model input scale, compute one mean and one scale per feature. Reduce Batch and Time over the training recordings, so angle and velocity get separate statistics. Store both tensors as (1,1,D) to reuse them at every trajectory and time slot.
Fit on training recordings
Apply to any recording
For a training batch of equally long recordings, and are the mean and population standard deviation of the training readings for feature . The positive floor keeps division defined even for a constant feature. At inference, the saved statistics let you transform a single new reading without waiting for the rest of its trajectory. PyTorch standard deviation
Verify the indices in PyTorch
Compare batch calibration, centering and feature normalization
import torch
# Features: joint angle and angular velocity.
X = torch.tensor([
[[0., 1.], [2., 3.], [4., 2.]],
[[10., 4.], [12., 3.], [14., 2.]],
])
bias = torch.tensor([0.25, -0.5])
torch.testing.assert_close(X + bias, torch.stack([row + bias for row in X]))
torch.testing.assert_close((X + bias)[1, 2, 0], X[1, 2, 0] + bias[0])
# Group readings along time. Batch and feature stay fixed.
centered = X - X.mean(dim=1, keepdim=True)
torch.testing.assert_close(centered.mean(dim=1), torch.zeros_like(X[:, 0, :]))
# Two time slots make the wrong broadcast compatible.
short = X[:, :2, :]
mean = short.mean(dim=1)
correct = short - mean.unsqueeze(1)
wrong = short - mean
assert correct.shape == wrong.shape
torch.testing.assert_close(correct[0, 1], short[0, 1] - mean[0])
torch.testing.assert_close(wrong[0, 1], short[0, 1] - mean[1])
# Fit only on X; reuse its statistics on a new trajectory.
held_out = torch.tensor([[[16., 3.], [18., 2.], [20., 2.]]])
mu = X.mean(dim=(0, 1), keepdim=True)
scale = X.std(dim=(0, 1), correction=0, keepdim=True).clamp_min(1e-6)
Z = (held_out - mu) / scale
assert mu.shape == scale.shape == (1, 1, 2)
assert Z.shape == held_out.shape