Homework · Runs in your browser
Convolution shapes, receptive fields, an LSTM step, RMSNorm and label smoothing from scratch
Build seven small pieces with nothing but the standard library: the output size of a convolution, its parameter count, the receptive field of a stack, a 2-D convolution with stride and padding, one LSTM step, RMSNorm, and cross-entropy with label smoothing. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest.
Hints:
- Output size along one axis: (n + 2 * padding - kernel) // stride + 1. The floor division drops a window that does not fit. Height and width are separate calculations.
- Parameters: kernel height * kernel width * input channels * output channels, plus one bias per output channel.
- Receptive field: keep r (starts at 1) and a jump (starts at 1). For each layer add (kernel - 1) * jump to r, then multiply the jump by the layer’s stride. Order matters.
- conv2d: pad with zeros first, then slide the window by the stride. Do not flip the kernel: deep learning libraries compute cross-correlation. A kernel with a single 1 in its top-left corner should return the top-left value of every window.
- LSTM: for each gate k in the order i, f, g, o compute Wx[k] x + Wh[k] h + b[k]. Use sigmoid for i, f, o and tanh for g. Then c_new = f * c + i * g and h_new = o * tanh(c_new). To test your gates, set big biases: forget +50 and input -50 should leave c unchanged.
- RMSNorm: divide every entry by sqrt(eps + mean of squares). Do not subtract the mean. Multiply by the gain after dividing.
- Label smoothing: the target is (1 - smoothing) on the true class plus smoothing / K on every class. Use the log-sum-exp trick so logits like [1000, 0] stay finite. With a smoothing of 0.1 and 10 classes the loss cannot go below about 0.5003.
Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.
Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.
Show a solution
Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.
import math
def conv_output_size(n, kernel, stride=1, padding=0):
"""Output length along one axis of a convolution or pooling window.
`padding` is the number of zeros added on EACH side. The result rounds down.
"""
return (n + 2 * padding - kernel) // stride + 1
def conv_param_count(k_h, k_w, c_in, c_out, bias=True):
"""Learnable parameters of a 2-D convolution layer: one k_h x k_w x c_in filter per output channel, plus one bias each."""
return k_h * k_w * c_in * c_out + (c_out if bias else 0)
def receptive_field(layers):
"""Receptive field (along one axis) of a stack of layers given as [(kernel, stride), ...], first layer first.
Each layer adds (kernel - 1) times the distance between neighbouring positions of its input
(the "jump", which starts at 1 and is multiplied by every earlier stride).
"""
r, jump = 1, 1
for kernel, stride in layers:
r += (kernel - 1) * jump
jump *= stride
return r
def conv2d(image, kernel, stride=(1, 1), padding=(0, 0)):
"""Single-channel 2-D cross-correlation, as deep learning libraries compute 'convolution' (the kernel is NOT flipped).
image is a list of rows (height x width), kernel a list of rows (k_h x k_w), stride = (s_h, s_w),
padding = (p_h, p_w) zeros on each side. Windows that do not fit are dropped (rounding down).
"""
s_h, s_w = stride
p_h, p_w = padding
k_h, k_w = len(kernel), len(kernel[0])
width = len(image[0])
padded = [[0.0] * (width + 2 * p_w) for _ in range(p_h)]
padded += [[0.0] * p_w + list(row) + [0.0] * p_w for row in image]
padded += [[0.0] * (width + 2 * p_w) for _ in range(p_h)]
out_h = conv_output_size(len(image), k_h, s_h, p_h)
out_w = conv_output_size(width, k_w, s_w, p_w)
return [
[sum(kernel[a][b] * padded[i * s_h + a][j * s_w + b] for a in range(k_h) for b in range(k_w)) for j in range(out_w)]
for i in range(out_h)
]
def _sigmoid(z):
return 1.0 / (1.0 + math.exp(-z))
def lstm_step(x, h, c, Wx, Wh, b):
"""One LSTM step. Gates are stacked in the order (input i, forget f, candidate g, output o).
x has length d, h and c have length H. Wx[k] is an H x d matrix, Wh[k] an H x H matrix and b[k] a length-H
vector for gate k = 0..3. Returns (h_new, c_new) with c_new = f * c + i * g and h_new = o * tanh(c_new).
"""
H = len(h)
pre = []
for k in range(4):
pre.append([
sum(Wx[k][r][j] * x[j] for j in range(len(x))) + sum(Wh[k][r][j] * h[j] for j in range(H)) + b[k][r]
for r in range(H)
])
i_gate = [_sigmoid(z) for z in pre[0]]
f_gate = [_sigmoid(z) for z in pre[1]]
g_cand = [math.tanh(z) for z in pre[2]]
o_gate = [_sigmoid(z) for z in pre[3]]
c_new = [f * cv + i * g for f, cv, i, g in zip(f_gate, c, i_gate, g_cand)]
h_new = [o * math.tanh(cv) for o, cv in zip(o_gate, c_new)]
return h_new, c_new
def rms_norm(x, gain=None, eps=1e-5):
"""RMSNorm: x_i / sqrt(eps + mean(x^2)) times a per-element gain (default 1). No mean is subtracted."""
rms = math.sqrt(eps + sum(v * v for v in x) / len(x))
gain = gain if gain is not None else [1.0] * len(x)
return [v / rms * g for v, g in zip(x, gain)]
def smoothed_cross_entropy(logits, target, smoothing=0.0):
"""Cross-entropy of softmax(logits) against the smoothed target (1 - smoothing) * one_hot + smoothing / K.
target is the index of the true class and K = len(logits). Must stay finite for logits like [1000, 0].
"""
K = len(logits)
m = max(logits)
lse = m + math.log(sum(math.exp(v - m) for v in logits))
log_p = [v - lse for v in logits]
q = [smoothing / K + (1.0 - smoothing if k == target else 0.0) for k in range(K)]
return -sum(qk * lp for qk, lp in zip(q, log_p))
Show the tests (test_starter.py)
import math
from starter import conv2d, conv_output_size, conv_param_count, lstm_step, receptive_field, rms_norm, smoothed_cross_entropy
IMG = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] # 4 high, 5 wide
KER = [[1, 0, -1], [2, 1, 0]] # 2 high, 3 wide, not symmetric
def test_output_size_known_cases():
assert conv_output_size(7, 3) == 5
assert conv_output_size(8, 3, 1, 1) == 8, "3x3 with padding 1 keeps the size"
assert conv_output_size(227, 11, 4, 0) == 55
assert conv_output_size(5, 5) == 1
def test_output_size_rounds_down_and_pads_both_sides():
assert conv_output_size(8, 3, 2, 0) == 3, "(8 - 3) / 2 = 2.5 rounds down to 2, plus 1"
assert conv_output_size(10, 3, 2, 1) == 5, "(10 + 2 - 3) / 2 = 4.5 rounds down to 4, plus 1"
assert conv_output_size(6, 5, 1, 2) == 6, "padding is added on each side"
assert conv_output_size(9, 2, 2, 0) == 4, "an odd length loses its last pixel to a 2x2 stride-2 window"
def test_param_count_uses_height_and_width_separately():
assert conv_param_count(3, 3, 3, 64) == 1792
assert conv_param_count(5, 3, 16, 32) == 7712
assert conv_param_count(5, 3, 16, 32, bias=False) == 7680
assert conv_param_count(1, 1, 256, 64) == 16448
assert conv_param_count(3, 7, 2, 5) == 215, "3 * 7 * 2 * 5 weights plus 5 biases"
def test_receptive_field_stacks_and_order_matters():
assert receptive_field([]) == 1
assert receptive_field([(7, 1)]) == 7
assert receptive_field([(3, 1)] * 3) == 7, "three 3x3 layers see 7 pixels"
assert receptive_field([(3, 2)] * 3) == 15, "stride 2 doubles the step each layer takes"
assert receptive_field([(5, 1), (3, 2), (3, 1)]) == 11
assert receptive_field([(2, 2), (3, 1)]) == 6, "pool first, then a 3-wide conv: each conv step spans 2 input pixels"
assert receptive_field([(3, 1), (2, 2)]) == 4, "the same layers in the other order see less"
def test_conv2d_valid_uneven_image_and_kernel():
assert conv2d(IMG, KER) == [[17, 20, 23], [32, 35, 38], [47, 50, 53]]
def test_conv2d_is_cross_correlation_not_flipped():
top_left = conv2d(IMG, [[1, 0], [0, 0]])
assert top_left == [[1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14]], "a kernel with 1 in its top-left reads the top-left of each window"
def test_conv2d_stride_and_padding_per_axis():
assert conv2d(IMG, KER, stride=(2, 1), padding=(1, 0)) == [[4, 7, 10], [32, 35, 38], [-2, -2, -2]]
assert conv2d(IMG, KER, stride=(1, 2), padding=(0, 1)) == [[4, 20, 32], [4, 35, 52], [4, 50, 72]]
assert conv2d(IMG, KER, stride=(2, 2), padding=(1, 1)) == [[1, 7, 13], [4, 35, 52], [-17, -2, 19]]
def test_conv2d_same_padding_keeps_shape_and_identity_kernel_copies_the_image():
ident = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
assert conv2d(IMG, ident, padding=(1, 1)) == [[float(v) for v in row] for row in IMG]
def test_conv2d_drops_a_window_that_does_not_fit():
row = [[1, 2, 3, 4, 5]]
assert conv2d(row, [[1, 1]], stride=(1, 2)) == [[3, 7]], "windows start at 0 and 2; the one starting at 4 would run off the edge"
def test_conv2d_shifting_the_input_shifts_the_output():
base = [[0.0] * 6 for _ in range(6)]
base[1][1], base[1][2], base[2][1] = 1.0, 2.0, 3.0
moved = [[0.0] * 6 for _ in range(6)]
for r in range(5):
for c in range(5):
moved[r + 1][c + 1] = base[r][c]
a, b = conv2d(base, KER), conv2d(moved, KER)
assert all(a[i][j] == b[i + 1][j + 1] for i in range(len(a) - 1) for j in range(len(a[0]) - 1)), "translation equivariance"
H = [0.2, -0.4]
C = [0.6, -0.3]
X = [1.0, -0.5]
WX = [[[0.5, -0.3], [0.1, 0.8]], [[-0.2, 0.4], [0.6, -0.1]], [[0.3, 0.3], [-0.5, 0.2]], [[0.7, -0.6], [0.05, 0.25]]]
WH = [[[0.2, -0.1], [0.4, 0.3]], [[0.1, 0.5], [-0.3, 0.2]], [[-0.4, 0.2], [0.1, 0.6]], [[0.3, 0.3], [-0.2, 0.1]]]
B = [[0.1, -0.2], [0.3, 0.05], [-0.1, 0.2], [0.0, 0.4]]
ZERO_WX = [[[0.0, 0.0], [0.0, 0.0]] for _ in range(4)]
ZERO_WH = [[[0.0, 0.0], [0.0, 0.0]] for _ in range(4)]
def test_lstm_step_matches_hand_computed_values():
h, c = lstm_step(X, H, C, WX, WH, B)
assert math.isclose(h[0], 0.12943654408734123, abs_tol=1e-9) and math.isclose(h[1], -0.21017402384909323, abs_tol=1e-9)
assert math.isclose(c[0], 0.18198068479868681, abs_tol=1e-9) and math.isclose(c[1], -0.39385425842979893, abs_tol=1e-9)
def test_lstm_forget_gate_keeps_the_old_cell_and_input_gate_blocks_new_content():
b = [[-50.0, -50.0], [50.0, 50.0], [0.0, 0.0], [0.0, 0.0]]
h, c = lstm_step(X, H, C, ZERO_WX, ZERO_WH, b)
assert math.isclose(c[0], 0.6, abs_tol=1e-9) and math.isclose(c[1], -0.3, abs_tol=1e-9), "f = 1, i = 0: the cell state passes through unchanged"
assert math.isclose(h[0], 0.5 * math.tanh(0.6), abs_tol=1e-9), "output gate sigmoid(0) = 0.5"
def test_lstm_forget_gate_clears_the_cell_and_input_gate_writes_the_candidate():
b = [[50.0, 50.0], [-50.0, -50.0], [0.5, -0.5], [0.0, 0.0]]
h, c = lstm_step(X, H, C, ZERO_WX, ZERO_WH, b)
assert math.isclose(c[0], math.tanh(0.5), abs_tol=1e-9) and math.isclose(c[1], math.tanh(-0.5), abs_tol=1e-9), "f = 0, i = 1: c = candidate"
def test_lstm_output_gate_scales_the_hidden_state():
b = [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [-50.0, 50.0]]
h, c = lstm_step(X, H, C, ZERO_WX, ZERO_WH, b)
assert abs(h[0]) < 1e-9, "o = 0 hides the cell"
assert math.isclose(h[1], math.tanh(c[1]), abs_tol=1e-9), "o = 1 shows tanh(c)"
def test_rms_norm_does_not_subtract_the_mean():
out = rms_norm([1.0, 2.0, 3.0, 6.0], eps=0.0)
expect = [v / math.sqrt(12.5) for v in (1.0, 2.0, 3.0, 6.0)]
assert all(math.isclose(a, b, rel_tol=1e-12) for a, b in zip(out, expect))
assert sum(out) / 4 > 0.8, "the mean is not centred to zero"
shifted = rms_norm([6.0, 7.0, 8.0, 11.0], eps=0.0)
assert math.isclose(shifted[0], 0.7302967433402215, rel_tol=1e-9), "adding 5 to every entry changes RMS norm, unlike layer norm"
def test_rms_norm_gain_and_eps_inside_the_root():
out = rms_norm([1.0, 2.0, 3.0, 6.0], gain=[1.0, 2.0, 1.0, 0.5], eps=0.0)
assert math.isclose(out[1], 1.131370849898476) and math.isclose(out[3], 0.848528137423857)
tiny = rms_norm([1e-3, 1e-3], eps=1e-5)
assert math.isclose(tiny[0], 0.3015113445777636, rel_tol=1e-9), "eps is added to the mean square, inside the square root"
assert rms_norm([0.0, 0.0], eps=1e-5) == [0.0, 0.0]
def test_rms_norm_ignores_the_overall_scale():
a = rms_norm([1.0, -2.0, 4.0], eps=0.0)
b = rms_norm([10.0, -20.0, 40.0], eps=0.0)
assert all(math.isclose(p, q, rel_tol=1e-12) for p, q in zip(a, b))
def test_smoothed_cross_entropy_known_values_with_true_class_not_first():
logits = [2.0, 0.5, -1.0]
assert math.isclose(smoothed_cross_entropy(logits, 2, 0.0), 3.241311296657157, rel_tol=1e-9)
assert math.isclose(smoothed_cross_entropy(logits, 2, 0.1), 3.091311296657157, rel_tol=1e-9)
assert math.isclose(smoothed_cross_entropy([1.0, 0.0, -1.0, 2.0], 1, 0.2), 2.340189698561195, rel_tol=1e-9), "the extra mass is eps / K on every class including the true one"
def test_smoothed_cross_entropy_full_smoothing_is_the_uniform_target():
l = [0.3, 1.1, -0.7, 0.0]
expect = math.log(sum(math.exp(v) for v in l)) - sum(l) / 4
assert math.isclose(smoothed_cross_entropy(l, 3, 1.0), expect, rel_tol=1e-12)
assert math.isclose(smoothed_cross_entropy(l, 0, 1.0), expect, rel_tol=1e-12), "the true class no longer matters"
def test_smoothed_cross_entropy_floor_is_the_target_entropy_not_zero():
gap = math.log(0.91 / 0.01)
assert math.isclose(smoothed_cross_entropy([gap] + [0.0] * 9, 0, 0.1), 0.5002880350577579, rel_tol=1e-9)
assert smoothed_cross_entropy([30.0] + [0.0] * 9, 0, 0.1) > smoothed_cross_entropy([gap] + [0.0] * 9, 0, 0.1), "too confident is penalised"
def test_smoothed_cross_entropy_is_stable_for_large_logits():
assert math.isclose(smoothed_cross_entropy([1000.0, 0.0], 1), 1000.0)
assert math.isclose(smoothed_cross_entropy([1000.0, 0.0], 0), 0.0, abs_tol=1e-12)
assert math.isfinite(smoothed_cross_entropy([1000.0, 0.0, -1000.0], 2, 0.1))