Lesson 1.4 — Linear Transformations
From control systems to neural layers
Classical control
The state-space model maps a state and a control input to a new state.
Neural layer
Every output is a weighted sum of input features plus a bias. Weights decide how features mix.
Batch execution
Many samples share the same W and b; the last axis holds the input features.
Linear vs affine. A strict linear map satisfies superposition and
homogeneity, so it maps the origin to the origin. Adding a non-zero bias makes the
map affine. PyTorch keeps the engineering name nn.Linear and
includes a bias by default. Below we distinguish the mathematical column-vector
convention from PyTorch's last-axis feature convention.
The vocabulary of an affine layer
| Term | Shape | Meaning |
|---|---|---|
| Input x | (D_in,) | One sample's features |
| Weight W | (D_out, D_in) | One row per output feature, one column per input feature |
| Bias b | (D_out,) | One additive parameter per output feature |
| Output y | (D_out,) | New features, not a class label yet |
Dot product — weighted sum
Trace the products in one dot product
Dot Product Accumulator
Elementwise: x * w
The feature axis is preserved and the result is still a vector.
Dot product: x @ w
The shared axis is summed away, so the result is a scalar.
A dot product is not a weighted average. The weights need not be
non-negative and need not sum to one. Elementwise multiplication keeps the axis;
reducing with sum or @ removes it.
Matrix multiplication — row meets column
Hold the output row fixed and move to a different output column . The row of stays the same; the selected column of changes. The shared index runs through both operands inside each dot product.
Matrix Multiplication Explorer
Check in PyTorch
import torch
A = torch.tensor([[1,2,3],[4,5,6]], dtype=torch.float32)
B = torch.tensor([[-2,0],[-1,1],[0,2]], dtype=torch.float32)
C = A @ B
print(C.shape, C)
print((A[0] * B[:, 0]).sum())
The inner dimension K must match. Output rows come from A and output columns from B; K is contracted. If A is (2, 3) and B is (4, 2), then A @ B is invalid — broadcasting cannot repair the conflict between contracted sizes 3 and 4. For batched matmul the leading dimensions may broadcast, but the last two matrix axes follow the same rule. Matrix multiplication is not commutative in general, and matrix–vector multiplication is just one dot product per row of the matrix.
What does a matrix do to space?
Look at the unit square. Its top-right corner is reached by taking one horizontal step and one vertical step. After applying , the same journey uses the first column of for the horizontal step and the second column for the vertical step. Their sum lands on the transformed corner.
Apply the matrix. The dotted square is the input. The first column keeps a horizontal step horizontal. The second sends a vertical step up and to the right. This shears the square into a parallelogram.

Add the bias. The dashed parallelogram is the previous result. The arrow lifts every corner by the same distance. The two column arrows keep their lengths and directions.

The pictures use columns and and bias . For an arbitrary input, and scale the two arrows before you add them.
Read across row to calculate one output coordinate. Read down column to see how every output coordinate changes when input increases by one. Bias disappears from this change because both endpoints receive the same translation.
Explore a rotation, shear or collapse on the same grid
2D Transformation Playground
import torch
W = torch.tensor([[1,0.5],[0,1]], dtype=torch.float32)
b = torch.tensor([0,0], dtype=torch.float32)
x = torch.tensor([1,1], dtype=torch.float32)
print(W @ x + b)
print(W @ torch.zeros(2) + b)
A purely linear transformation maps the origin to the origin. A non-zero bias sends the origin to b instead. W need not be square: neural layers routinely use it to change the feature dimension, and a singular W can collapse a whole direction.
Weight, bias and output features
Neural Linear Layer Inspector
import torch
from torch import nn
x = torch.tensor([1,2,3], dtype=torch.float32)
W = torch.tensor([[1,2,-1],[2,-1,1]], dtype=torch.float32)
b = torch.tensor([0.5,-0.5], dtype=torch.float32)
print(W @ x + b)
layer = nn.Linear(3, 2, bias=True)
print(sum(p.numel() for p in layer.parameters()))
Parameter count
| Layer | Weight | Bias | Total parameters |
|---|---|---|---|
nn.Linear(3, 2) | 6 | 2 | 8 |
nn.Linear(128, 64) | 8,192 | 64 | 8,256 |
nn.Linear(768, 64, bias=False) | 49,152 | 0 | 49,152 |
Batch size does not change the parameter count. A layer applied to (2, 5, 768) and to (64, 5, 768) has exactly the same weights. More samples mean more computation, not more parameters.
From column vectors to batched row tensors
Mathematical convention
One sample is a column vector, so W multiplies on the left.
PyTorch convention
Features sit on the last axis, so the same W is transposed and multiplies on the right. The bias broadcasts over the leading axes.
Batched Affine Transformation
import torch
X = torch.tensor([[[-3,-2,-1],[0,1,2]],[[3,4,5],[-3,-2,-1]]], dtype=torch.float32)
W = torch.tensor([[-2,-1,0],[0,1,2]], dtype=torch.float32)
b = torch.tensor([-1,0], dtype=torch.float32)
Y = X @ W.T + b
Y_loop = torch.stack([torch.stack([W @ v + b for v in tr]) for tr in X])
torch.testing.assert_close(Y, Y_loop)
print(Y.shape)
nn.Linear transforms only the last feature axis. It does not mix
different times or different samples: those positions share parameters and are
otherwise independent. Making time steps interact requires another mechanism, which
comes later in the curriculum.
A state-space affine map
For inputs ordered as position, velocity and acceleration, the position row is and the velocity row is . The zero in the second row tells you that current position contributes nothing to next velocity.
Robot State Projection
import torch
p, v, u, dt = 1, 1, 1, 0.5
z = torch.tensor([p, v, u], dtype=torch.float64)
W = torch.tensor([[1, dt, .5*dt**2], [0, 1, dt]], dtype=torch.float64)
y = W @ z
expected = torch.tensor([p + dt*v + .5*dt**2*u, v + dt*u])
torch.testing.assert_close(y, expected)
print(y)
With state x = [position, velocity] and control u as
acceleration, a constant-acceleration model gives
p′ = p + Δt·v + ½Δt²·u and v′ = v + Δt·u. The model assumes
acceleration is constant inside one sampling interval and ignores friction and
actuator saturation. Real robot dynamics are usually nonlinear; this example simply
connects a familiar state map to an affine layer.
Learn by coding — PyTorch
01 — Dot product and matmul
torch.dot, elementwise multiplication and matrix multiplication should agree after the same reduction.
import torch
x = torch.tensor([1., 2., 3.])
w = torch.tensor([2., -1., 1.])
assert torch.dot(x, w).item() == 3.0
torch.testing.assert_close(x @ w, (x * w).sum())
A = torch.tensor([[1., 2., 3.], [4., 5., 6.]])
B = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])
C = A @ B
print(C)
02 — From a loop to nn.Linear
An explicit per-sample loop and the batched affine expression must produce the same numbers. Copying known weights into a layer is not training.
import torch
from torch import nn
X = torch.arange(12, dtype=torch.float32).reshape(2, 2, 3)
W = torch.tensor([[1., 2., -1.], [2., -1., 1.]])
b = torch.tensor([0.5, -0.5])
# Explicit loop: one output vector per time step
Y_loop = torch.stack([
torch.stack([W @ x + b for x in traj])
for traj in X
])
Y = X @ W.T + b
layer = nn.Linear(3, 2)
with torch.no_grad(): # set known parameters; no training
layer.weight.copy_(W)
layer.bias.copy_(b)
torch.testing.assert_close(Y_loop, Y)
torch.testing.assert_close(layer(X), Y)
print(Y.shape)
03 — Feature projection in a modern model
Batch and sequence axes are irrelevant to the parameter count; only the input and output feature dimensions matter.
import torch
from torch import nn
layer = nn.Linear(768, 64, bias=False)
X = torch.zeros(2, 5, 768)
Y = layer(X)
assert Y.shape == (2, 5, 64)
assert sum(p.numel() for p in layer.parameters()) == 768 * 64
print(layer.weight.shape)
768 × 64 = 49,152. A shape of (2, 5, 768) does not appear in the parameter count.
Mini project — a two-output linear probe
Goal: build X with shape (4, 3), W with shape (2, 3) and b with shape (2,). Compute Y by an explicit loop, by X @ W.T + b, and with nn.Linear after copying the weights. Assert that all three results agree and explain which axis was contracted.
import torch
from torch import nn
X = torch.tensor([[1., 2., 3.], [0., -1., 2.], [2., 0., 1.], [-1., 1., 0.]])
W = torch.tensor([[1., -1., 2.], [0.5, 2., -1.]])
b = torch.tensor([0.5, -1.])
# TODO: write the explicit per-sample loop
# TODO: write the batched expression
# TODO: copy W and b into nn.Linear and compare
# TODO: assert every shape and every value
If two predictions differ, check whether you multiplied by W or by W.T. Print shapes until they match, then compare values.