Deep Learning & Vision — Neural Nets That See
"When features become too complex to engineer by hand, let the network learn the geometry."
01 · The hookThe $3M Defect Crisis at ChipGuard
Instead of telling the model which features matter, you let it learn its own. This page builds up to a network that sees images, and explains why the same idea needed a special architecture to work on pixels.
"We produce 500,000 silicon wafers per month. A single undetected micro-crack ruins an entire $50,000 server motherboard down the line. Human inspectors miss 12% of micro-cracks. I need an AI vision inspector running at 60 frames per second on the factory line that misses LESS than 0.1% of defects."
Put numbers on Dr. Thorne's pain and it gets sharp fast. Human inspectors fatigue after four hours at the microscope; their miss rate for subtle micro-cracks sits at 12.4%.
Every escaped defect eventually detonates inside a finished motherboard, and the warranty claims plus destroyed downstream assemblies add up to $3.2M a year.
The line runs at 60 frames per second, so whatever replaces the humans gets a hard budget of 16.6 ms per frame — that's the SLA, and it's not negotiable, because the conveyor doesn't stop.
Three numbers from that memo run through every page of this module. Here they are drawn once, so that when a paragraph later says "the 16.6 ms budget" you know exactly which mark on which ruler it means.
- The 12 filled dots. A miss rate is hard to feel as a percentage, so count it. Out of every 100 micro-cracks that pass under a tired inspector, about 12 are not reported. Dr. Thorne wants that down to fewer than one in a thousand, which on this grid would be one filled dot in ten of these panels.
- The two money bars. The tall bar is the $3.2M a year the 12 dots cost once they detonate inside finished motherboards. The short bar is what is left when the miss rate drops to 0.8%. The distance between the bars, $2.9M, is the number that pays for everything in this module.
- The production rate. 500,000 wafers a month is roughly 16,700 a day, and the conveyor presents them at 60 frames a second. This is why accuracy alone is not a passing grade: a model that is right and slow stops the line.
- The 16.6 ms mark. Sixty frames a second means one frame every 1000 ÷ 60 = 16.6 milliseconds. Everything the inspector does for one wafer — load, normalise, forward pass, decide — must fit left of that mark. A multimodal API call takes about 1,500 ms, so it sits far off the right-hand end of this ruler, which is why it can never serve the conveyor.
Your first instinct as an engineer is probably classical image processing: edge detectors, thresholds, contour matching. ChipGuard tried that.
It fails, and it fails for an instructive reason: wafer surfaces have complex metallic grain, illumination that shifts across the die, and defects that appear at wildly different scales.
Every hand-written rule that catches one crack pattern misses three others and false-alarms on a perfectly good solder trace. The features you'd need are too complex to engineer by hand.
This module is about the alternative: representation learning — instead of writing the feature extractors, you build a network that learns them from labeled examples, layer by layer, from raw pixels up to "micro-crack".
By the end you'll have built that inspector three ways: a from-scratch neural network in NumPy so you feel the mechanism, a PyTorch CNN that beats the latency SLA, and a fine-tuned pretrained backbone — plus the judgment call that matters most in 2026: knowing when to skip all of that and send the image to a multimodal LLM for a cent.
A neural network is function composition with learnable constants:
predict = f3(f2(f1(x))), where each f is a matrix multiply plus a
nonlinearity, and "training" means auto-tuning the constants against an error metric.
Backpropagation is reverse-mode automatic differentiation — the chain rule executed as a reverse walk over the call graph, exactly like a build system propagating a change backwards through its dependency graph.
A convolution kernel is a regex for pixels: a small pattern slid across the whole input, firing wherever it matches. And you've already built a neuron: Module 02's logistic regression is a single neuron with a sigmoid activation. This module just stacks them.
02 · The intuitionNeurons, Convolutions & Transfer Learning
Dr. Thorne's memo is now three measured things: 12 cracks in every 100 missed, $3.2M a year burned, 16.6 ms per frame to work in. Hand-written edge rules already failed on the wafer grain, so the team needs a machine that learns its own detectors from labelled tiles. This section builds that machine in three pieces — the neuron, the convolution, and the borrowed backbone — and each piece exists to beat one of those three numbers.
The MLP: an assembly line for abstractions
Start with the smallest part ChipGuard needs: one neuron. No wafers yet, no images — just the unit that turns a row of numbers into one firing strength. It matters because everything later on this page is copies of this unit, wired differently. Get the single neuron and the 529,666-parameter inspector in section 05 is the same arithmetic, repeated.
A multi-layer perceptron (MLP) is a factory assembly line for meaning. Raw pixel values enter at one end.
The first station of workers — neurons — each computes a weighted
sum of its inputs plus a bias (w·x + b), then passes the result through an
activation function that decides how strongly to fire.
The next station combines those firings into higher-level signals: edges become corners, corners become shapes, shapes become "that looks like a crack". The last station emits a single number: the probability of a defect.
The activation function is the part people underrate. Without it, stacking 100 linear
layers collapses mathematically into one linear layer — matrix products of matrices
are still matrices, so the whole tower could only ever draw straight decision boundaries.
The nonlinearity (today, almost always ReLU: max(0, x)) is
what lets depth buy expressiveness. And backpropagation is how the weights
learn: compute how much each weight contributed to the final error, using the chain rule
to pass blame backwards through the network, then nudge every weight slightly against its
gradient. That loop — forward, loss, backward, step — is all of deep learning. Everything
else is scale and plumbing.
Run the input forward.
Measure the loss.
Pass the blame backward.
Step every weight against its gradient.
Each line is one station of the circuit in Fig. 4.1b. Forward is station 1: push the four XOR rows through the weights and read the predictions. Loss is station 2: one number, 0.9258 on the first lap. Backward is station 3: turn that one number into a gradient for each of the 17 weights and biases. Step is station 4: subtract a little of each gradient. Then back to station 1, 5,001 times, until the loss reads 0.0024.
xor_backprop.py prints when you run it in section 03.- Station 1, forward. The inputs travel through every layer and come out as predictions. Nothing is corrected here; the network simply states its current opinion. On the first lap that opinion is near-random, because the weights are random.
- Station 2, loss. All four predictions are compressed into a single number that says how wrong the network was: 0.9258 on lap one. It has to be one number, because the next station needs something to differentiate, and you can only take the slope of a single quantity.
- Station 3, backward. That one number is turned into 17 numbers, one per weight and bias, each saying "if you nudged me up a little, the loss would move this much". This is the only station that is arithmetic you have not done before, and section 03 does it by hand.
- Station 4, step. Every weight moves a little against its own gradient, then the lap starts again. After 5,001 laps the loss reads 0.0024. Every trained model you will ever use, of any size, was made by this circuit turning.
Now the same picture a second time, with this module's real files in the boxes. Fig. 4.1 shows one signal moving forward. The loop you just chanted moves it forward, scores it, sends blame back, and steps. Every stage of that loop is a line you will read in the two scripts named in the table.
You have not met these files yet. xor_backprop.py is section 03 and
chipguard_cnn.py is section 05. Skim the table now for the shape of the loop, and
come back to it when each line has been explained.
| Stage | In the 50-line version (xor_backprop.py, section 03) | In the PyTorch version (chipguard_cnn.py, section 05) | What flows out |
|---|---|---|---|
| Input | X, a 4×2 array holding the four XOR cases | A batch x of shape [32, 3, 64, 64] pulled from DataLoader(SyntheticWaferDataset(...)) | Numbers ready for the first layer |
| Feature layers | z1 = X @ W1 + b1 then a1 = sigmoid(z1): four hidden neurons | self.features: two blocks of nn.Conv2d, nn.BatchNorm2d, nn.ReLU, nn.MaxPool2d | Learned features: 4 numbers per example, or 32 feature maps of 16×16 per image |
| Head | z2 = a1 @ W2 + b2 then a2 = sigmoid(z2) | self.head: nn.Flatten, nn.Dropout(0.3), two nn.Linear layers | One probability per example, or two raw class scores (logits) per image |
| Loss | The -np.mean(y * np.log(a2) + ...) line: cross-entropy by hand | criterion = nn.CrossEntropyLoss(), called as criterion(logits, y) | One number: how wrong this batch was |
| Backward | Seven lines from dz2 = (a2 - y) / len(X) down to db1 | loss.backward() | A gradient for every weight and bias (.grad on each parameter) |
| Step | W1 -= lr * dW1 and its three siblings, with lr = 1.0 | opt.zero_grad() before, opt.step() after, with torch.optim.AdamW(..., lr=1e-3) | Slightly better weights, and the loop repeats |
| Evaluate | print(f"step ... loss ...") every 1,000 steps, then the four predictions | model.eval() and torch.inference_mode() over val_loader, then benchmark() | Validation accuracy and a latency verdict against 16.6 ms |
Before reading on: ChipGuard's scans are 1024×1024 RGB. Feed one into an MLP whose first hidden layer has just 1,024 neurons. How many weights does that first layer need? And what happens to the trained network's output if the exact same micro-crack appears 3 pixels to the right of where it appeared in training images?
Reveal the answer
1024 × 1024 × 3 inputs × 1,024 neurons ≈ 3.2 billion weights — in the first layer alone.
Worse, the MLP has no concept of space: pixel (10,10) and pixel (10,13) connect to entirely different weights, so a crack shifted 3 pixels right is, to the network, a completely new pattern it never trained on.
You'd need every defect at every position in your training data. Both problems — parameter explosion and positional brittleness — are exactly what convolutions fix, which is why the next section exists.
That answer is worth drawing, because "3.2 billion" and "448" are both just words until you see them on the same axis.
- The bar you can see. This is the first dense layer on one 1024×1024 colour frame: every pixel of every channel wired to every one of 1,024 neurons. Three and a quarter billion numbers, before the second layer exists. A frame of that size at 60 per second would also have to read all of them, 60 times a second.
- The sliver you cannot. The convolution that replaces it has nine weights per input channel per output map: 3 · 3 · 3 · 16 + 16 = 448. On the bar above it is one ten-thousandth of a pixel wide, which is the honest way to draw the ratio. The ladder underneath is the same comparison with each rung worth ten times the one before it, so both numbers fit on one page.
- Why the gap does not close. The dense count grows with the image: double the width and it roughly quadruples. The convolution count does not contain the image size at all, so a bigger scan costs more arithmetic but not one extra weight. That is the property the rest of this section is built on.
"Why can't I just use a bigger random forest on the pixels? I spent all of Module 03 learning that trees beat everything."
— an engineer fresh from Module 03, at the word "pixels"
You can, and on small, centred images it is a fair baseline. A random forest on the 12,288 raw values of a 64×64 image scores well above chance. The trouble is what a tree split can express. A split asks one question of one column: is pixel (10, 10) brighter than 0.6? A crack is not a property of pixel (10, 10). It is a thin line that can sit anywhere in the frame.
Trees have no notion of "the pixel to the right". Every column is an independent fact to them, so a crack shifted three pixels over is a brand-new pattern that needs its own branch. The forest has to memorize every position. That is marker 1 of Fig. 4.1c — the 3,221,225,472 weights a dense layer needs — made worse, because a forest needs a branch per position on top of a threshold per pixel. A convolution kernel builds "look at a small neighbourhood, everywhere" into the structure, and that assumption is right for images.
The honest cost: the network needs more labelled data, a slower training loop, and it gives you a probability with no readable rule behind it. Module 03's lesson stands for tabular data, where a column has one stable meaning. It even survives here in a hybrid form: a common production pattern feeds the CNN's learned features into a gradient-boosted model for the final decision.
CNNs: the sliding magic flashlight
The Brain Power just handed Dr. Thorne a bill for 3,221,225,472 weights in the first layer alone, and told him that a crack three pixels to the right is a pattern the network has never seen. Neither survives contact with a 60-frames-per-second conveyor. What ChipGuard needs is a layer that looks at one small neighbourhood at a time and reuses the same detector everywhere on the wafer. That layer is the convolution, and it is what turns marker 1 of Fig. 4.1c into marker 2.
A convolutional neural network (CNN) refuses to look at the whole image at once.
Instead, it takes a tiny window — a kernel or filter, typically 3×3 — and slides it across the image like a flashlight, computing one number per position: the dot product of the window's pixels with the kernel's weights.
Where the patch under the flashlight matches the kernel's pattern, the dot product spikes; where it doesn't, it stays near zero. The grid of those numbers is a feature map — literally a map of "where in the image this pattern occurs".
Here is the whole exercise drawn, with your four answers written in the cells they belong to.
- The window, not the image. The heavy square is the only part of the tile the kernel can see at this moment. It covers nine of the sixteen cells. The kernel will occupy four such squares in total — right, down, and down-right — which is why a 4×4 tile and a 3×3 kernel give a 2×2 map.
- The kernel is a question, not a picture. Its nine weights ask "is the left column brighter than the right column?" The 1s add what is on the left, the −1s subtract what is on the right, and the middle column is ignored. Nothing about the tile is stored in it; the same nine numbers are asked at every position.
- The signs carry the answer. −27 at the left of the map means bright appeared to the right of dark: the stripe is beginning. +27 at the right means the stripe is ending. A feature map is not a picture of brightness; it is a signed map of how strongly one pattern matched, and where.
- The zero case is the point. Turn the stripe on its side and this kernel reports nothing at all, four times. It is not broken; it was only ever asking one question. Sixteen kernels ask sixteen questions, and the layer above combines the answers into corners and textures.
Two structural wins over the plain fully-connected network.
Weight sharing. The same 9 kernel weights are reused at every position. So detecting "vertical edge" costs 9 parameters instead of billions — and a crack shifted 3 pixels right still triggers the same kernel, just at a different map location.
Hierarchy. Stack convolution layers and the second layer's kernels slide over the first layer's feature maps. That composes edges into textures, textures into shapes, and shapes into micro-crack signatures.
Between convolution layers, a max-pooling layer downsamples each feature map, keeping only the strongest activation in each 2×2 patch.
That buys three things at once: it halves the spatial size, cuts compute, and gives a little translation invariance — a crack detected slightly left or right still wins its pool.
chipguard_cnn.py.- The quadrants. The two heavy lines cut the map into four 2×2 blocks. Pooling takes the largest number in each block and throws the other three away: 9, 2, 4 and 3. There is nothing to learn here — no weights, no choices, just a maximum.
- Why the shift does not matter. In the second panel the strong response of 9 has moved one cell up and left. It is still the largest number in the same block, so the pooled map is identical. A crack that lands a pixel or two off from where it sat in training still produces the same summary, which is exactly the brittleness the Brain Power warned about, partly cured.
- The honest limit. Move the 9 far enough and it crosses into the next block, and then the output does change — one cell over. Pooling buys tolerance of small shifts, not of large ones. In the real model it also halves 64×64 to 32×32, which cuts the work of every later layer by four.
Questions you might be asking now
BE the convolution used one grey 4×4 tile and a kernel somebody wrote down. The first layer of chipguard_cnn.py reads three sensor channels, pads the border and learns its own kernels. The questions below slow down for those three differences, and every answer uses the same three 5×5 tiles.
| Row | Tile A · optical | Tile A · infrared | Tile B · optical | Tile B · infrared | Tile C · optical and infrared |
|---|---|---|---|---|---|
| 1 | 5 5 5 5 5 | 5 5 5 5 5 | 5 5 5 5 5 | 5 5 5 5 5 | 5 5 5 5 5 |
| 2 | 5 5 5 5 5 | 8 8 8 8 8 | 5 5 5 5 5 | 5 5 5 5 5 | 5 5 5 5 5 |
| 3 | 5 9 9 9 9 | 8 8 8 8 8 | 5 9 9 9 9 | 5 5 5 5 5 | 5 5 5 5 5 |
| 4 | 5 5 5 5 5 | 8 8 8 8 8 | 5 5 5 5 5 | 5 5 5 5 5 | 5 5 5 5 5 |
| 5 | 5 5 5 5 5 | 5 5 5 5 5 | 5 5 5 5 5 | 5 5 5 5 5 | 5 5 5 5 5 |
Slide a 3×3 kernel over a 5×5 tile by hand. How many numbers come out, and what does padding=1 change?
Nine numbers without padding, and 25 with it. A 3-wide window fits in only three places along a 5-wide row, so the tile shrinks to 3×3. padding=1 adds a frame of zeros so that every pixel gets a window of its own, which is how ChipGuardCNN keeps 64×64. The price is a fake edge: on clean tile C the border cells read 10 and 15 instead of 0.
Use tile A's optical channel and a kernel that asks one question: is the middle row brighter than the rows above and below it? Its rows are −1, −1, −1, then 2, 2, 2, then −1, −1, −1. The nine weights add up to 0, so a flat patch scores 0 however bright it is.
Without padding: nine windows
Put the window's left edge on column 1, then column 2, then column 3. A fourth start would hang off the tile, because the window needs three columns. Rows work the same way. Three starts across times three starts down is nine windows, and each window writes one output cell.
- Top row of the window. Place the window on rows 2–4, columns 1–3. Row 2 holds 5, 5, 5, and each is multiplied by −1: −15.
- Middle row. Row 3 holds 5, 9, 9, because the crack starts at column 2. Each is multiplied by 2: 10 + 18 + 18 = 46.
- Bottom row. Row 4 holds 5, 5, 5. Times −1: −15.
- Add the three rows. −15 + 46 − 15 = 16. That is the first cell of the map's middle row.
- Slide one column right. The middle row is now 9, 9, 9, which gives 54, so the cell is −15 + 54 − 15 = 24. One more slide gives 24 again.
- Slide one row up. On rows 1–3, columns 2–4, the crack sits under the bottom row of weights: −15 + 30 − 27 = −12. A line in the wrong row of the window scores negative.
The full map, row by row, is −8, −12, −12, then 16, 24, 24, then −8, −12, −12. The large numbers sit in the middle row, where the crack is. The size comes from the formula in section 06:
out = ⌊(n + 2p − k) ÷ s⌋ + 1
Symbol key: n is the input width, p the padding, k the kernel width, and s the stride (how many pixels the window jumps per slide). ⌊ ⌋ means round down, and ÷ is divide. For this tile: ⌊(5 + 0 − 3) ÷ 1⌋ + 1 = 3.
With padding=1: 25 windows and a fake edge
Without padding the tile loses a ring of pixels, and the edges are under-read: a corner pixel sits in only one window, while the centre pixel sits in nine. padding=1 fixes both by drawing a one-pixel frame of zeros around the tile before sliding. The tile becomes 7×7, and the window has ⌊(5 + 2 − 3) ÷ 1⌋ + 1 = 5 starts per row.
- Top row of the top-left window. Frame only: 0, 0, 0, so 0.
- Middle row. Frame, then 5, 5, times 2: 20.
- Bottom row. Frame, then 5, 5, times −1: −10.
- Add. 0 + 20 − 10 = 10: an edge between the black frame and the grey wafer, not on the wafer.
- The window's starts. The heavy square is one of nine places a 3×3 window fits on a 5×5 tile. The top-left pixel sits in one window only; the centre pixel sits in nine.
- The 3×3 map. One window, one cell. The middle row, 16, 24, 24, is the crack running through the middle of the window; 16 is lower because the crack starts at column 2. The −8 and −12 are the crack seen from the wrong row.
- The frame of zeros. padding=1 makes the tile 7×7, so the window has five starts per row and every pixel, corners included, sits at the centre of one window. That is how padding=1 keeps a 64×64 tile at 64×64.
- The fake edge. The map's top and bottom rows read 10, 15, 15, 15, 10 on tile A and on clean tile C alike. A black frame above grey wafer looks like an edge. Copying the edge pixels outward instead of zeros removes it.
| No padding | padding=1 | |
|---|---|---|
| Map size on a 5×5 tile | 3×3 | 5×5 |
| Pixels that sit at the centre of some window | 9 of 25 | 25 of 25 |
| Clean tile C's map | 0 in every cell | 10, 15, 15, 15, 10 on top and bottom, 0 inside |
| ChipGuardCNN's 64×64 tile, layer by layer | conv 62, pool 31, conv 29, pool 14; flatten 32 × 14 × 14 = 6,272 | conv 64, pool 32, conv 32, pool 16; flatten 32 × 16 × 16 = 8,192 |
| Weights in the dense layer after it | 401,472 | 524,352 |
The honest limit is the frame. Zero padding tells the kernel that the world beyond the tile is black, so a crack along the outermost row is read through a fake edge. nn.Conv2d also accepts padding_mode='replicate', which copies edge pixels outward; on tile C that gives 0 everywhere. chipguard_cnn.py keeps the default, zeros.
Without padding a 3×3 kernel shrinks the tile by 2 in each direction; padding=1 keeps the size and adds a fake edge along the border.
The real tile has three channels. Is a 3×3 kernel still only nine weights? Where does 448 come from?
No, it has 27. In nn.Conv2d(3, 16, kernel_size=3) each kernel holds a 3×3 grid for every input channel, plus one bias: 28 numbers. It still writes one number per position. Sixteen kernels of 28 numbers make 448. Reading the channels together is also what lets one kernel tell tile A's warm crack from tile B's cold solder trace.
A channel is one grid of numbers per sensor. ChipGuard's tile is three 64×64 grids stacked: optical, infrared and x-ray. That is the 3 in the shape [3, 64, 64]. The three 5×5 tiles in the table above have the same three layers.
A kernel for a three-channel input is three 3×3 slices, stacked the same way. Each slice multiplies its own channel. The three sums and one bias are added into a single number. So one kernel does not produce three maps; it produces one.
Here is one such kernel. The optical slice is the line kernel from the previous answer. The infrared slice is 0, 0, 0, then 1, 1, 1, then 0, 0, 0, which asks "is the middle row warm?". The x-ray slice is all zeros, and the bias is −39.
- Optical slice on the optical channel. Window rows 2–4, columns 2–4 of tile A. This is the previous answer's arithmetic: −15 + 54 − 15 = 24.
- Infrared slice on the infrared channel. Rows 2–4 of tile A's infrared are all 8. Only the middle row has weights of 1: 8 + 8 + 8 = 24.
- X-ray slice on the x-ray channel. Nine 5s times nine zeros is 0. The multiplies still happen; they add nothing.
- Add the three parts and the bias. 24 + 24 + 0 − 39 = 9.
- Apply ReLU. max(0, 9) = 9: one number, written into one cell of one map.
Now the same kernel on the same window of all three tiles.
| Tile A, crack | Tile B, solder trace | Tile C, clean | |
|---|---|---|---|
| Optical part | 24 | 24 | 0 |
| Infrared part | 24 | 15 | 15 |
| X-ray part | 0 | 0 | 0 |
| Plus the bias | −39 | −39 | −39 |
| Total, then after ReLU | 9, then 9 | 0, then 0 | −24, then 0 |
| Whole 3×3 map after ReLU | 0, 0, 0 / 1, 9, 9 / 0, 0, 0 | 0 in every cell | 0 in every cell |
| The optical slice alone, no bias | 24 | 24 | 0 |
Compare the last row with the row above it. The optical slice alone scores the crack and the solder trace the same, 24 each. Only the kernel that also reads infrared separates them. That is why a convolution reads every channel at once: a pattern can be required to appear in two sensors at the same spot.
- Three slices, one sum. The optical slice finds the bright line: 24. The infrared slice checks that the middle row is warm: 24. The x-ray slice adds 0. The bias is added once, not once per channel, so the cell holds 9.
- Why read all channels at once. Tile B's bright line also scores 24 on the optical slice, but its cold infrared adds only 15, and 24 + 15 − 39 = 0. ReLU passes the crack's 9 and silences the solder trace.
- The count. Each of the 16 boxes is one kernel of 27 weights and a bias. The layer holds 448 numbers at any tile size, but the work grows with size: one 64×64 tile costs 1,769,472 multiplies.
Counting to 448
Each kernel is 3 × 3 × 3 = 27 weights plus 1 bias: 28 numbers. nn.Conv2d(3, 16, ...) asks for 16 kernels, so 16 × 28 = 448. The output, [16, 64, 64], has one map per kernel; that 16 counts kernels, not colours.
conv2 reads those 16 maps as 16 channels, so each of its kernels holds 3 × 3 × 16 + 1 = 145 numbers, and 32 kernels make 4,640. BatchNorm adds two learned numbers per channel, which are the "+ 32" and "+ 64" in section 05's shape table.
Image size appears nowhere in that count, which is Fig. 4.1c's point. The arithmetic does grow with size. On a 1024×1024 scan the same layer is still 448 numbers, but it does 452,984,832 multiplies per frame.
The honest limit: a kernel mixes channels only inside its own 3×3 patch. It cannot compare a bright line here with heat twenty pixels away; that reach comes from stacking layers after pooling. And the −39 was picked by hand to keep the numbers whole. A real layer learns all 448 numbers, which is the next question.
Each kernel spans every input channel, 3 × 3 × channels + 1 numbers, and writes one map: 16 × 28 = 448.
Who decides the nine numbers inside a kernel? The exercise handed me 1, 0, −1.
Nobody types them. A kernel starts as random numbers, and the training loop moves them exactly like the weights in section 03. One 3×3 kernel trained on 600 synthetic wafer tiles went from 58.3% on the validation tiles, the score of calling every tile clean, to 100% after 100 steps. Its nine numbers turned into a detector for the crack's lower edge.
The 1, 0, −1 kernel in BE the convolution, and the hand-picked kernel in the previous answer, were teaching props. In chipguard_cnn.py all 448 numbers of the first layer start random, and no line of code ever sets them. The only teacher is the label on each tile.
To watch that happen, kernel_learns.py builds the smallest detector that still has a kernel in it. One 3×3 kernel slides over the optical channel. The strongest response anywhere on the tile, plus one bias, goes through a sigmoid to become a probability. That is ten numbers. It trains on the first 600 tiles of SyntheticWaferDataset(1200, seed=42) and is scored on the 300 validation tiles.
One step, one tile
Here is tile 10, the first cracked tile in the training set, at step 0, while the kernel is still random.
- Slide and keep the strongest. A 3×3 window fits 62 × 62 = 3,844 times on a 64×64 tile. The kernel's largest response is −0.3112, at the window centred on row 19, column 9. The crack is on rows 25 and 26, so the random kernel is looking at grain.
- Turn it into a probability. Add the bias, which starts at 0, and apply the sigmoid: p = 0.4228. The label is 1, cracked.
- Prediction minus truth. p − y = 0.4228 − 1 = −0.5772. This is the same blame signal as dz in section 03's pencil exercise. The loop averages over 600 tiles, so this tile's share is −0.5772 ÷ 600 = −0.000962.
- The blame lands on the nine weights through the winning window. Each weight moves by −(learning rate) × (share) × (the pixel under it), with a learning rate of 2.0. The top-left pixel of the winning window was 0.709, so the top-left weight gets −2.0 × −0.000962 × 0.709 = +0.00136 from this tile.
- Add up all 600 shares. The combined first update lowers every one of the nine weights, by between 0.02 and 0.05. Then the loop starts again with the new kernel.
Only the winning window gets any blame, because the maximum ignores every other position. The same is true of max pooling in Fig. 4.2c.
Three hundred steps later
| Step | Kernel, rows top to bottom | Loss | Validation accuracy |
|---|---|---|---|
| 0 | 0.61, −0.77, 0.13 / −0.17, −0.14, −0.06 / −0.61, −0.07, −0.26 | 0.6643 | 58.3% |
| 50 | 2.73, −0.58, −0.53 / 2.59, −0.48, −0.54 / −0.67, −0.60, −0.64 | 0.4301 | 94.0% |
| 100 | 4.50, −0.11, −0.89 / 4.50, −0.10, −0.77 / −1.13, −1.11, −1.18 | 0.2854 | 100% |
| 300 | 5.28, 2.71, 1.34 / 5.44, 2.82, 1.46 / −3.12, −2.92, −3.04 | 0.0430 | 100% |
- Four snapshots. At step 0 the kernel is random and the detector calls every tile clean: 58.3%. By step 50 the left column of the top two rows passes 2.5 and accuracy is 94.0%; by step 100 it is 100%. The last 200 steps only lower the loss, to 0.0430.
- What it learned. Rows 25 and 26 of tile 10 are crack; row 27 is background. The kernel's rows add up to +9.32, +9.72 and −9.07, so it fires on bright, bright, dark: the crack's lower edge. At step 0 its strongest window on this tile was grain at row 19.
- Hand-written against learned. With the best possible cut-off the random kernel is barely better than calling everything clean. The exercise's vertical-edge template reaches 94.7%, because each crack's two ends are vertical edges. A hand-written line reaches 98.7%. The loop found a better question on its own.
Read the last row of the table as a picture. The top two rows are large and positive; the bottom row is negative. Bright, bright, then dark is the lower edge of a crack two pixels high, which is exactly what the generator paints. On tile 10 the trained kernel's strongest window is centred on row 26, column 34, with its top two rows on crack rows 25 and 26.
It also leans left, with column sums of 7.6, 2.61 and −0.24, and its bias ended at −11.1. Nobody designed either; they simply lowered the loss on these 600 tiles.
The honest limit is the data. These synthetic cracks are a +0.45 line on noise with a spread of 0.08, so one kernel reaches 100%. Real defects vary in angle, width and contrast, which is why the real layer learns sixteen kernels and a second layer of thirty-two reads their maps.
A kernel is a weight like any other: it starts random, and the labels, through prediction-minus-truth and a step, turn it into whatever question lowers the loss.
How it learns: rolling downhill, carefully
ChipGuard now has a shape for its inspector, but every weight inside it is still a random number, and a random 3×3 kernel finds nothing. The team has 2,000 labelled wafer tiles and needs a procedure that turns random numbers into crack detectors using only those labels. That procedure is gradient descent, and it has exactly one knob that decides whether it works at all: how far to move on each step.
Training is gradient descent on a loss surface: imagine the loss as a valley whose floor is the best set of weights, and every training step as one stride downhill in the direction the gradient points. The learning rate (η) is your stride length, and it's the single most consequential hyperparameter you'll tune. Too small and training crawls; too large and each stride overshoots the valley floor, bouncing from wall to wall — often climbing upward while you watch the loss curve in disbelief.
Before reading on: initialization matters too. What would happen if you initialized every weight in the network to exactly zero and started training?
Reveal the answer
Nothing useful — forever. With identical weights, every neuron in a layer computes the identical output, so backprop assigns every one of them the identical gradient, so they all update identically and stay clones.
Your 4-neuron hidden layer behaves as one neuron with extra steps. This is the symmetry problem, and it's why weights are initialized with small random values: randomness breaks the tie so different neurons can specialize into different feature detectors.
(Biases can be zero — they're already differentiated by their random incoming weights.)
Transfer learning: hire the experienced inspector
Training the inspector from nothing would need something like 500,000 labelled wafer images. ChipGuard has 2,000, and Dr. Thorne wants the line fixed this quarter, not in two years. So the team does what a factory does when it cannot train a specialist from scratch: it hires someone who already knows how to look at things, and teaches them only the wafer part. In software that means starting from a network trained on 1.2 million photographs.
Training a CNN from scratch means teaching it what edges, lighting, and textures are — from nothing. That takes something like 500,000 labeled images and days of GPU time.
The experienced-inspector move: take a network already trained on ImageNet's 1.2M images (a ResNet, an EfficientNet, a MobileNet), which already knows generic vision — edges, shading, textures, shapes — and only teach it your specialty.
Freeze the pretrained layers, chop off the final classification head, bolt on a fresh small head for your classes, and train only that head on your 2,000 wafer images. Minutes of training, and typically better accuracy than a from-scratch model could reach with 100× your data.
One more workhorse idea before the code: data augmentation. Factory-line images vary in rotation, brightness, and position, so during training you randomly flip, rotate, zoom, and re-light every image on the fly. This forces the model to learn position-invariant defect features rather than memorizing exact pixel coordinates — it's regularization you get by lying (plausibly) to your model, and in computer vision it's considered mandatory, not optional.
03 · Build it yourselfBackprop by Hand: XOR in 50 Lines
ChipGuard's inspector will end up as a PyTorch model with 529,666 parameters, and
PyTorch will do all of the calculus without showing you any of it. Before that happens, do the calculus
once yourself, on four data points, so that nothing in the real loop is a black box. The four points are
XOR rather than wafers for one reason: it is the smallest problem a single neuron provably cannot solve,
so it forces the hidden layer that the wafer model also needs. Every line you write here comes back in
chipguard_cnn.py.
Before PyTorch does the calculus for you, do it once yourself. XOR is the perfect victim: four data points, and provably unlearnable by a single neuron (no straight line separates the classes — the exact wall Module 02's logistic regression would hit).
One hidden layer solves it. The code below is the entire deep learning loop with nothing hidden: forward pass, loss, backward pass, weight update.
The four lines of the backward pass are backpropagation — everything in the rest of this module is these four lines, industrialized.
X and y; the predictions and losses in marker 3 are what the run prints.- The four points. Filled means the label is 1 (the inputs differ), hollow means 0 (they match). The two filled points sit on opposite corners, and so do the two hollow ones. That diagonal arrangement is the entire difficulty.
- Why one neuron fails. A single neuron computes w₁x₁ + w₂x₂ + b and calls everything above some threshold a 1. That is a straight line, and you can slide or tilt it forever: every straight line leaves one filled point on the same side as one hollow point. Lines A and B are two of the infinitely many failures.
- What the hidden layer buys. Four hidden neurons draw four lines, and the output neuron combines them. Keeping the band between two of those lines separates the corners from the middle, which is a shape no single line can make. This is the concrete meaning of "depth buys expressiveness".
- The result to expect. After 5,001 laps of the loop in Fig. 4.1b, the network answers 0.000 and 0.004 for the hollow points and 0.997 twice for the filled ones, and the loss has fallen from 0.9258 to 0.0024. If your run prints these numbers, your weights and the page's are the same.
You have not been taught NumPy's @ operator, the sigmoid function, or any of the
d-variables below yet. That is on purpose. Guess first, then check. Every line in this
table is explained in the step-by-step list above the code and again in the paragraph after it.
The calculus behind the backward pass is spelled out in section 06.
Step-by-step: what xor_backprop.py does, in plain English
- Bring in
numpyand make a random-number generator with seed 0, so every run starts from the same random weights and prints the same losses. - Define the four XOR examples
X(the input pairs) and their labelsy: 0 when the two inputs match, 1 when they differ. - Create the weights.
W1is 2-by-4 and connects the two inputs to four hidden neurons;W2is 4-by-1 and connects those four to one output. Weights are random numbers; biases start at zero. Random values break the symmetry that would otherwise make all four hidden neurons identical. - Define
sigmoid, the activation function: it squashes any number into the range 0 to 1. - Set the learning rate to 1.0 and loop 5,001 times. Each pass is one training step over all four examples at once.
- Forward pass.
z1 = X @ W1 + b1is the weighted sum for each hidden neuron, anda1 = sigmoid(z1)is its firing. The same two lines again for the output layer givea2, the predicted probability. Every intermediate is kept because the backward pass needs it. - Loss: cross-entropy, averaged over the four examples. It is near 0 when the network is confident and right, and large when it is confident and wrong.
- Backward pass, output layer.
dz2 = (a2 - y) / len(X)is prediction minus truth, the shortcut that sigmoid plus cross-entropy allows.dW2 = a1.T @ dz2anddb2are how much each output weight and bias is to blame. - Backward pass, hidden layer.
da1 = dz2 @ W2.Tcarries the blame back throughW2.dz1 = da1 * a1 * (1 - a1)multiplies by the sigmoid's slope, which is station 3 of Fig. 4.1b happening one layer further down.dW1 = X.T @ dz1anddb1land the blame on the first-layer weights. - Step: subtract the learning rate times each gradient from each weight and bias. All four updates are the same operation.
- Every 1,000 steps print the loss, so you can watch it fall.
- After training, run the forward pass once more and print the prediction for each input pair.
# pip install "numpy>=2.1"
"""XOR by hand: a 2-layer network + backprop in ~50 lines, zero frameworks."""
import numpy as np
rng = np.random.default_rng(0)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
# 2 inputs -> 4 hidden -> 1 output. Random init breaks symmetry: if every
# weight started at 0, all hidden neurons would compute (and learn) the
# exact same thing forever.
W1, b1 = rng.normal(0, 1.0, (2, 4)), np.zeros((1, 4))
W2, b2 = rng.normal(0, 1.0, (4, 1)), np.zeros((1, 1))
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
lr = 1.0
for step in range(5001):
# ---- forward pass: cache every intermediate — backprop needs them all
z1 = X @ W1 + b1 # pre-activation, layer 1
a1 = sigmoid(z1) # activation, layer 1
z2 = a1 @ W2 + b2
a2 = sigmoid(z2) # prediction in (0, 1)
loss = -np.mean(y * np.log(a2) + (1 - y) * np.log(1 - a2))
# ---- backward pass: the chain rule, one layer at a time
# For sigmoid + cross-entropy the first delta collapses to (pred - truth).
dz2 = (a2 - y) / len(X)
dW2 = a1.T @ dz2 # how much each hidden output mattered
db2 = dz2.sum(axis=0, keepdims=True)
da1 = dz2 @ W2.T # push blame back through W2...
dz1 = da1 * a1 * (1 - a1) # ...through sigmoid's derivative a(1-a)...
dW1 = X.T @ dz1 # ...onto the first-layer weights
db1 = dz1.sum(axis=0, keepdims=True)
# ---- descend: nudge every weight against its gradient
W1 -= lr * dW1; b1 -= lr * db1
W2 -= lr * dW2; b2 -= lr * db2
if step % 1000 == 0:
print(f"step {step:5d} loss {loss:.4f}")
print("\npredictions after training:")
for xi, pred in zip(X, sigmoid(sigmoid(X @ W1 + b1) @ W2 + b2)):
print(f" {xi} -> {pred[0]:.3f}")
Run it. The loss falls from ~0.93 to under 0.01, and the final predictions land at
0.000, 0.997, 0.997, 0.004 — XOR, learned. Now read the backward pass again with Fig. 4.1 in view: each
d-variable is "how much does the loss change if this thing changes", computed by
multiplying local derivatives backwards along the exact edges the forward pass walked. Notice
that the backward pass reuses a1 and a2 from the forward pass —
that's why frameworks cache activations during training, and why training needs so much more
memory than inference. When PyTorch's loss.backward() appears in the next section,
you'll know precisely what it's doing: this, for a graph with a few million more edges.
04 · Watch it breakThe Vanishing Gradient
The XOR network worked, and it was two layers deep. ChipGuard's inspector will not be two layers deep; a real vision model is 20 to 150. Before the team commits to depth, they need to know what depth does to the training signal, because a network whose early layers never learn will never see a micro-crack, and it will not report an error while failing. This section makes that failure happen on purpose and puts a number on it.
Our XOR net used sigmoid everywhere and got away with it — at depth 2. Real vision models are 20 to 150 layers deep. Stack sigmoids that deep and training silently dies.
The reason is arithmetic, not mysticism: the sigmoid's derivative is at most 0.25, and backprop multiplies one derivative per layer.
Ten layers deep, your gradient has been multiplied by numbers ≤ 0.25 ten times — it arrives at layer 1 up to a million times smaller than it left the loss.
The early layers, the ones that are supposed to learn edges, receive effectively zero signal and never learn anything.
vanishing_gradient.py, drawn on a logarithmic axis. Its printed values are 4.63e-02, 3.98e-06, 1.30e-13 and 1.05e-25 for sigmoid and 4.81e-01, 2.00e-01, 2.61e-03 and 3.91e-06 for ReLU; the labels here round them to two digits, as the paragraphs do.- Read the bars as a decay, not as sizes. The axis is logarithmic: every tick is ten times the previous one. A bar half as long is not half as much gradient, it is roughly a thousand billion times less. That is the only way to show 4.8e-01 and 1.1e-25 in one picture.
- Depth 2: both activations are fine. This is the XOR network's depth, and the sigmoid bar is close to the ReLU one. Everything you built in section 03 worked because it was this shallow. Nothing in that code was wrong; it simply never met the problem.
- Depth 40: the two stories separate. The sigmoid bar has shrunk to a stub, 1.1e-25, because each layer multiplied the signal by a slope of at most 0.25. The ReLU bar is still at 3.9e-06, twenty orders of magnitude healthier, because a live ReLU unit passes a slope of exactly 1. The remaining ReLU decay comes from the units that are switched off, and He initialization is the cure for that.
- Why this is silent. Nothing raises an error. The loss just sits there while the top few layers do all the learning and the bottom layers keep their random weights. In a wafer inspector that means the edge detectors never form, and the accuracy plateaus for a reason no log line mentions.
Step-by-step: what vanishing_gradient.py does, in plain English
- Bring in
numpyand make a random-number generator with seed 7. - Define
first_layer_gradient(depth, act, act_grad, width). It buildsdepthrandom weight matrices of size width-by-width. They are scaled by 1 over the square root of width, so the signal neither explodes nor shrinks on the way forward. - Forward: start from a random input row. At each layer compute
z = a @ W, keepz, and apply the activation. The keptzvalues are what the backward pass needs. - Backward: start with a pretend gradient of all ones at the output. For each layer from last to first, multiply by the activation's slope at that layer's
z, then by the transposed weights. That is one chain-rule step per layer, the same two moves asdz1 = da1 * a1 * (1 - a1)andda1 = dz2 @ W2.Tin the XOR script. - Return the average absolute gradient that reaches layer 1.
- Define the two activations and their slopes. The sigmoid's slope peaks at 0.25. ReLU's slope is exactly 1 for any positive input and 0 otherwise.
- Print a header row, then for depths 2, 8, 20 and 40 measure the surviving gradient under each activation and print both numbers in scientific notation.
# pip install "numpy>=2.1"
"""Measure the gradient that survives to layer 1 of a deep stack: sigmoid vs ReLU."""
import numpy as np
rng = np.random.default_rng(7)
def first_layer_gradient(depth, act, act_grad, width=64):
"""Forward one input through `depth` layers, backprop a unit error,
return the mean |gradient| that reaches layer 1 alive."""
Ws = [rng.normal(0, 1 / np.sqrt(width), (width, width)) for _ in range(depth)]
a, pre_acts = rng.normal(0, 1, (1, width)), []
for W in Ws:
z = a @ W
pre_acts.append(z)
a = act(z)
g = np.ones((1, width)) # pretend dLoss/dOutput = 1
for W, z in zip(reversed(Ws), reversed(pre_acts)):
g = (g * act_grad(z)) @ W.T # one chain-rule step per layer
return float(np.abs(g).mean())
sigmoid = lambda z: 1 / (1 + np.exp(-z))
sig_grad = lambda z: sigmoid(z) * (1 - sigmoid(z)) # peaks at 0.25!
relu = lambda z: np.maximum(0, z)
relu_grad = lambda z: (z > 0).astype(float) # exactly 1 while alive
print(f"{'depth':>6} | {'sigmoid grad':>13} | {'relu grad':>10}")
for depth in (2, 8, 20, 40):
s = first_layer_gradient(depth, sigmoid, sig_grad)
r = first_layer_gradient(depth, relu, relu_grad)
print(f"{depth:6d} | {s:13.2e} | {r:10.2e}")
Run it and watch the sigmoid column collapse: 4.6e-02 at depth 2,
4.0e-06 at depth 8, and 1.1e-25 by depth 40 — below float32's
meaningful precision. The network isn't training slowly; it's not training at all
below the top few layers. The ReLU column decays too — to 3.9e-06 at depth 40 —
but that's twenty orders of magnitude healthier, and its remaining decay has a
specific, fixable cause we'll name in a moment. If you histogrammed the activations layer by
layer you'd see the same story from the forward side: sigmoid activations pile up against
0 and 1 — the saturated flats where the derivative is ~0 — while ReLU layers keep a healthy
spread of live positive values (plus a spike of exact zeros: units that are "off" for this
input).
The fix that unlocked modern depth is embarrassingly simple: ReLU. Its derivative is exactly 1 for any positive input, so gradients pass through active units undiminished.
The gentle decay you still see in the ReLU column comes from the roughly half
of units that are "off" (outputting zero) at each layer — and that is precisely what
He initialization corrects: it doubles the weight variance to
2/width instead of our demo's 1/width, and that factor of √2 per
layer compounds to bring the depth-40 gradient right back to order 1.
vanishing_gradient.py with the weight scale changed from 1/√width to √2/√width, which is exactly what He initialization does.- The stub. Forty sigmoid layers leave 1.1e-25 of the signal. This bar is the whole failure of this section, and it is the reason nobody builds deep sigmoid networks any more.
- The middle bar. ReLU alone rescues twenty orders of magnitude but still decays, because about half the units are switched off at each layer and pass nothing back. 3.9e-06 trains, slowly, and the first layers still learn last.
- The bar that ends the problem. He initialization doubles the variance of the starting weights to 2/width, which multiplies the signal by roughly √2 at every layer and cancels the half that ReLU switches off. At depth 40 the gradient arrives at 1.8 — the same order as the gradient that left the loss. Depth stops costing anything.
Swap it into the demo and the depth-40 bar grows from 3.9e-06 to 1.8: that is marker 3 of Fig. 4.4e, drawn on the same axis as the two bars it replaces. The third reinforcement in every production network is batch normalization, which re-centers each layer's activations every step so they stay in the healthy, non-saturated range.
ReLU's one vice — a unit whose input goes permanently negative "dies" and its gradient stays zero forever — is exactly what BatchNorm and sane learning rates keep in check.
Before the two of them start, look at what each one actually controls. The left half of the picture is everything The Architecture decides. The right half is everything The Optimizer decides. Every claim in the chat below points at a number on this picture.
- The architecture's side. Three decisions, all made before a single step is taken: which activation (and therefore how much gradient survives each layer), which kind of layer (and therefore whether the first layer costs 3,221,225,472 weights or 448), and whether the activations are normalised on the way through. None of these can be fixed later by tuning.
- The optimizer's side. One job, repeated: read the gradients, move the weights. The falling curve is 5,001 repetitions of that on the XOR network. The two rate bars are the fine-tuning recipe — a normal stride for the new head, a stride ten times shorter for pretrained weights you do not want to destroy.
- The two curves at the bottom. This is the practical payoff of the argument. A loss that never moves from 0.69 (which is −log 0.5, the score of a model guessing between two classes) points at the architecture or at a learning rate of zero. A loss that climbs points at the stride. Knowing which half of the picture to look at is most of debugging.
Tonight's talk: The Architecture and The Optimizer argue over the question, "Who's more important?"
Start with the failure everyone just watched, and look at marker 1 of Fig. 4.4f. Two bars: the slope a ReLU layer hands back is 1.0, the slope a sigmoid layer hands back is at most 0.25. Multiply 0.25 by itself forty times and you get the 1.1e-25 that reached layer 1. I swapped the activation and that number came back to 3.9e-06. You did nothing. You could not.
the activation function decides how much of the training signal survives each layer. Changing it is a change of shape, and no learning-rate setting could have rescued the forty-layer sigmoid network.
I stepped on whatever gradient you handed me. That is the job. And before you take a bow for ReLU, read the last line of my half, marker 2 in Fig. 4.4f. A unit whose input goes permanently negative outputs zero forever, and its gradient with it. Your units die by the hundred when my stride is too long. The bouncing path in Fig. 4.3 is my failure, and shortening the stride is my fix.
ReLU's flat half has a price: a unit pushed permanently negative stops learning for good. Too large a learning rate is what pushes it there, so that particular failure belongs to the optimizer.
Dead units are shared blame, fine. Representation is mine alone. Fig. 4.4b, marker 1: four points, two filled and two hollow on opposite corners. No straight line separates them, so one neuron cannot learn XOR at any learning rate, on any schedule, in any number of steps. Add one hidden layer and it takes you five thousand. Decide what can be expressed. Then you may step.
some problems are impossible for a given shape of network no matter how well it is trained. XOR with a single neuron is the smallest example there is.
Decide, and then sit there. A random 2-by-4 matrix expresses nothing. Marker 2 of Fig. 4.4f, the little curve: 0.9258 down to 0.0024, over 5,001 repetitions of W minus lr times dW. That is what turned your noise into a network answering 0.997 and 0.004. Every weight the reader ever ships has my fingerprints on it and none of yours. You are the shape of the container. I am what fills it.
a network starts as random numbers that predict nothing. Only the optimizer's repeated small steps turn those numbers into a working model, and the falling curve is that happening.
The container is the whole story on images. Marker 1 again, the long bar: a dense first layer on a 1024-by-1024 colour frame needs 3,221,225,472 weights. My 3-by-3 convolution needs 448 — the sliver you cannot see next to it — and a crack three pixels to the right still fires the same kernel. You could run forever on the dense version and still be memorising positions.
the choice of layer decides how many weights exist before training starts. A convolution reuses one small detector across the whole frame, which is why it needs 448 numbers where a dense layer needs three billion.
And you would be nowhere without the right stride on the new head. The two rate bars in marker 2. In finetune_timm.py the backbone is frozen: requires_grad is False on every one of your pretrained weights, and I am handed the head alone at 1e-3. Then phase two unfreezes the last block and drops me to 1e-4, ten times shorter, or I erase what made the backbone worth borrowing. That is a decision about how I move, not about how you are built.
freezing and learning rates are choices about motion, not structure. Pretrained weights are only valuable while they stay close to what they were, so phase two moves them ten times more slowly.
And who keeps the activations somewhere you can move at all? The last two lines of marker 1. BatchNorm re-centres every channel to mean 0 and variance 1 on every step you take, which is the only reason your larger stride is safe. He initialization sizes my starting weights so the depth-40 gradient arrives at 1.8 instead of 3.9e-06 — that is marker 3 of Fig. 4.4e. Your walk is safe because I made the valley walkable.
normalisation and initialisation are architecture choices that reshape the loss surface itself. They are the reason a larger learning rate stops being dangerous.
Walkable is not walked. And AdamW is not the plain step in xor_backprop.py. I keep a running average of each parameter's gradient and of its square, and from that history I size that parameter's own stride, so no weight is left behind and none is thrown across the valley. Then I shrink every weight a little each step; that is the W in the name. You hand me one loss surface. I hand each of your 529,666 parameters its own step.
AdamW gives every parameter a step length worked out from that parameter's own recent gradients, and also shrinks weights slightly on every step, which acts as a mild regulariser.
Then we agree on the reader's first debugging question — marker 3, the two small curves. Loss flat at 0.69 from step one: that is a symmetry problem or a dead gradient, and they look at me. Loss climbing: that is your stride, and they look at you.
the shape of the loss curve says which half of this picture to suspect. Flat from the very first step points at the architecture; rising points at the learning rate.
A flat curve can also be my learning rate left at zero, which prints exactly the same picture, so check that one number before rebuilding a network. But I will let you have it tonight. We revisit this when the validation curve comes in.
a learning rate of zero and a dead gradient produce identical flat curves, and the learning rate takes one second to check.
It will come in on my feature maps.
whatever that validation number turns out to be, it is computed from the features the architecture produced.
One step at a time.
neither of them wins. Both have to be right, and the page's advice is to ask which symptom you are looking at before you touch either.
05 · The industry toolPyTorch, Pretrained Backbones, and the API Option
You now own the mechanism: forward, loss, backward, step, proved on four points by hand. Dr. Thorne needs that same mechanism running on wafer scans at 60 frames a second, inside a 16.6 ms budget, missing fewer than one defect in a thousand. That means PyTorch rather than NumPy, a real architecture rather than four hidden neurons, and a latency measurement honest enough to put in front of a VP. This section builds the inspector three ways and ends with the decision Dr. Thorne actually has to make: own a model, borrow one, or rent one.
Now the real thing, three tiers deep. Tier 1: the ChipGuard CNN in PyTorch — same forward/loss/backward/step loop as your XOR code, but with autograd doing the derivatives and an architecture built from the parts you just learned: conv blocks, BatchNorm, ReLU, pooling, dropout, and a latency benchmark against the 16.6 ms SLA.
Before the code, one picture of what actually travels through it. Every shape below is printed by the model on a batch of 32 tiles, and every parameter count is the one PyTorch reports.
ChipGuardCNN. The squares are drawn to scale with the height and width of the feature maps; the bars are drawn to scale with the parameter counts, so 524,352 is 198 pixels and 448 is a fifth of one.- The first number never changes. Every shape starts with 32, the batch size: thirty-two independent wafer tiles moving through the network together, because one matrix multiply on 32 tiles is far faster than 32 multiplies on one. It is also the number that decides how much memory training needs, which is the first thing to lower when a GPU runs out.
- Squares shrink, channels grow. Height and width halve at each pool — 64, 32, 16 — while the channel count rises from 3 to 16 to 32. That is the trade the whole architecture is built on: fewer positions, more kinds of pattern remembered at each position. By the last row the network holds 32 different answers about each of 256 patches, instead of 3 colour values at each of 4,096 pixels.
- The bars say where the weights live. The two convolutions that do all the visual work are two hairlines. The single dense layer bridging 8,192 flattened numbers to 64 is the long bar: 524,352 of the 529,666 parameters, 99% of the model. That is why the dropout sits directly in front of it — the bridge is where a CNN overfits.
"Do I need a GPU to learn this? My laptop has no CUDA, and I am not buying a graphics card to do a course."
— a backend engineer, about to run chipguard_cnn.py
No. Every script on this page runs on a CPU. The XOR network trains in a second.
chipguard_cnn.py trains five epochs on 1,200 tiles of 64 by 64 in about a minute, and
its benchmark prints a latency verdict for whatever hardware you have. The script picks
cuda if it exists and cpu if it does not; nothing else changes. The
mechanism you are learning (forward, loss, backward, step) is identical on both.
What a GPU changes is scale. Look at marker 1 of Fig. 4.4g: the 32 at the front of every shape is
the batch, and training has to hold the activations of all 32 tiles at once so the backward pass can
reuse them. On a CPU that memory is plentiful and slow; on a GPU it is fast and finite.
finetune_timm.py resizes every tile to 224 by 224 before the backbone sees it, which
multiplies every square in marker 2 by about twelve, and on a laptop CPU each epoch takes several minutes instead of
seconds. A free Colab T4 makes it comfortable. If you go that route, keep one habit: report
latency numbers with the hardware named. A 16.6 ms verdict on a T4 says nothing about the
factory's edge box.
The honest downside of staying on CPU: two lessons stay theoretical. You will not see
torch.cuda.synchronize() matter, because there is no queue to wait on. And you will
not feel training memory grow with batch size, because CPU memory is large and forgiving. Both
bite the first time you touch a real GPU, so read the benchmark function even if you cannot
exercise it.
You have not been taught any of the torch.nn calls below yet. That is on
purpose. Guess first, then check. The step-by-step list above the code walks every one. The
anatomy after the code takes the training step apart, and the three paragraphs after that cover
BatchNorm, train versus eval mode, and the benchmark.
Build it in chunks
We build chipguard_cnn.py in four chunks. Chunks 1, 2 and 4 run on any laptop in seconds; chunk 3 trains a model, so it is shown but not run here.
-
Chunk 1 — a fake wafer scanner: 3-channel tiles with and without cracks
A vision model needs images. We draw random noise tiles with three channels (optical, infrared, x-ray) and, for about 40% of them, paint a bright crack line plus a warm halo. Writing it as a
Datasetis what lets PyTorch feed it to a model later.Step-by-step: what chunk 1 does, in plain English
- Start every tile as grey noise around 0.5, shaped 3 channels by 64 by 64.
- Flip a weighted coin: about 40% of tiles are defective.
- For a defective tile, pick a random row and column range, brighten two rows of the optical channel and four rows of the infrared channel.
- Clip values to the 0-to-1 range and remember the label.
__getitem__hands back one tile and its label as tensors.
chipguard_cnn.py — chunk 1runs offlineclass SyntheticWaferDataset(Dataset): """Synthetic wafer surface scans, 3 channels: [0] optical surface [1] infrared heatmap [2] x-ray reflectance A defect is a bright micro-crack line plus a thermal halo around it. """ def __init__(self, num_samples=1000, img_size=64, seed=42): rng = np.random.default_rng(seed) self.images, self.labels = [], [] for _ in range(num_samples): base = rng.normal(0.5, 0.08, (3, img_size, img_size)).astype(np.float32) label = int(rng.random() > 0.6) # ~40% defect rate if label: row = int(rng.integers(10, img_size - 10)) c0 = int(rng.integers(5, img_size - 25)) c1 = c0 + int(rng.integers(10, 20)) base[0, row:row + 2, c0:c1] += 0.45 # optical crack line base[1, row - 1:row + 3, c0 - 2:c1 + 2] += 0.30 # thermal halo self.images.append(np.clip(base, 0.0, 1.0)) self.labels.append(label) def __len__(self): return len(self.images) def __getitem__(self, idx): return torch.from_numpy(self.images[idx]), torch.tensor(self.labels[idx])torch.utils.data.Dataset— any class with__len__and__getitem__.torch.from_numpy— wraps a NumPy array as a tensor without copying.Run
python3 chunk1_dataset.py(needstorch). Tiles are 3 by 64 by 64; the cracked tile's optical maximum is clipped at 1.00 while the clean one stays near 0.75.terminalactual outputone tile: (3, 64, 64), label 0 defect rate in 200 tiles: 34% optical channel: clean tile max 0.75, cracked tile max 1.00 -
Chunk 2 — the network: two convolution blocks and a small head
With tiles in hand we need something that reads them. Each block slides 3 by 3 windows over the tile (convolution), rescales the result (BatchNorm), keeps positive values (ReLU) and halves the size (pooling). A small head then turns what is left into two scores: clean or defective.
Step-by-step: what chunk 2 does, in plain English
- Block 1: 16 learned 3-by-3 windows over the 3 channels, BatchNorm, ReLU, then pool 64 by 64 down to 32 by 32.
- Block 2: 32 windows over the 16 maps, BatchNorm, ReLU, pool down to 16 by 16.
- Flatten 32 maps of 16 by 16 into one list of 8,192 numbers.
- Dropout randomly hides 30% of them during training so the head cannot memorise.
- Two linear layers shrink 8,192 to 64 to 2 scores.
chipguard_cnn.py — chunk 2runs offlineclass ChipGuardCNN(nn.Module): """Two conv blocks + a small head, sized for sub-16ms CPU inference.""" def __init__(self, num_classes=2): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, padding=1), # 64x64 stays 64x64 nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(2), # -> 32x32 nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2), # -> 16x16 ) self.head = nn.Sequential( nn.Flatten(), # 32*16*16 = 8192 nn.Dropout(0.3), # fight the fc-layer overfit nn.Linear(32 * 16 * 16, 64), nn.ReLU(), nn.Linear(64, num_classes), ) def forward(self, x): return self.head(self.features(x))nn.Module— a class that owns learnable weights and definesforward.nn.Sequential— runs layers in order.Run
python3 chunk2_model.py. A batch of 32 tiles goes in; 32 pairs of scores come out; 529,666 parameters.terminalactual outputinput : (32, 3, 64, 64) output: (32, 2) parameters: 529,666 -
Chunk 3 — the training loop (not run here)
The network starts with random weights and knows nothing. Training shows it batches of labelled tiles, measures how wrong it was, and nudges every weight. The five lines inside the batch loop are the XOR code from section 03, handled by PyTorch.
Step-by-step: what chunk 3 does, in plain English
- Build a training loader (1,200 tiles) and a validation loader (300 tiles from a different seed).
- For each epoch, switch to training mode and go through the batches.
- Each batch: clear old gradients, forward, loss, backward, step.
- After the epoch, switch to evaluation mode and score the validation tiles without updating anything.
- Print loss and accuracy for that epoch.
chipguard_cnn.py — chunk 3not run here: ~1 min CPU trainingdef train(model, device, epochs=5): train_loader = DataLoader(SyntheticWaferDataset(1200, seed=42), batch_size=32, shuffle=True) val_loader = DataLoader(SyntheticWaferDataset(300, seed=101), batch_size=32) criterion = nn.CrossEntropyLoss() opt = torch.optim.AdamW(model.parameters(), lr=1e-3) for epoch in range(1, epochs + 1): model.train() # dropout on, batchnorm uses batch stats running, correct, seen = 0.0, 0, 0 for x, y in train_loader: x, y = x.to(device), y.to(device) opt.zero_grad() logits = model(x) loss = criterion(logits, y) loss.backward() # backprop — your XOR code, industrialized opt.step() running += loss.item() * y.size(0) correct += (logits.argmax(1) == y).sum().item() seen += y.size(0) model.eval() # dropout off, batchnorm uses running stats v_correct, v_seen = 0, 0 with torch.inference_mode(): for x, y in val_loader: x, y = x.to(device), y.to(device) v_correct += (model(x).argmax(1) == y).sum().item() v_seen += y.size(0) print(f"epoch {epoch}/{epochs} | loss {running / seen:.4f} " f"| train acc {correct / seen:.2%} | val acc {v_correct / v_seen:.2%}")DataLoader— batches and shuffles a Dataset.model.train()/model.eval()— turn dropout and BatchNorm training behaviour on and off.Not run here: a full run trains for about a minute on a CPU, so this rung shows the form of the output only. Run
python3 chipguard_cnn.pyyourself to see one line per epoch in the form below.terminalformat only, not runepoch 1/5 | loss ... | train acc ... | val acc ... ... epoch 5/5 | loss ... | train acc ... | val acc ... (format only: this chunk was not run to completion here) -
Chunk 4 — time one frame honestly, then run the whole thing
The factory cares about speed as much as accuracy: 60 frames a second leaves 16.6 ms per wafer. The benchmark warms up first, then times 200 single-frame predictions. The main block ties it together: build, train, benchmark.
Step-by-step: what chunk 4 does, in plain English
- Switch to evaluation mode and make one random frame.
- Run 20 warm-up predictions that are not timed, since the first calls pay one-off setup costs.
- If a GPU is present, wait for it to finish queued work before starting and stopping the clock.
- Time 200 predictions, divide to get milliseconds per frame, and compare with 16.6 ms.
chipguard_cnn.py — chunk 4runs offlinedef benchmark(model, device, frames=200): """Honest single-frame latency: warm up first; sync the GPU if present.""" model.eval() frame = torch.randn(1, 3, 64, 64, device=device) with torch.inference_mode(): for _ in range(20): # warmup: allocator, kernel selection, caches model(frame) if device.type == "cuda": torch.cuda.synchronize() t0 = time.perf_counter() for _ in range(frames): model(frame).softmax(1).argmax(1) if device.type == "cuda": torch.cuda.synchronize() ms = (time.perf_counter() - t0) / frames * 1000 verdict = "PASS — 60 FPS ready" if ms < 16.6 else "FAIL — SLA violated" print(f"\nlatency {ms:.2f} ms/frame | throughput {1000 / ms:.0f} FPS | {verdict}") if __name__ == "__main__": device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"device: {device}") model = ChipGuardCNN().to(device) train(model, device) benchmark(model, device)torch.inference_mode()— skips gradient bookkeeping for speed.time.perf_counter()— a high-resolution clock.Run
python3 chunk4_benchmark.py. This file trains nothing (epochs=0), so the timing is for an untrained network; speed does not depend on the weights. Your number depends on your hardware (this run used a GPU, so your CPU number will be larger).terminalactual output (untrained net)device: cuda latency 0.41 ms/frame | throughput 2465 FPS | PASS — 60 FPS ready
The whole program
The file below is the finished program. Its chunk comments mark where each rung landed: lines 7–43 are chunk 1; lines 44–71 are chunk 2; lines 72–104 are chunk 3; lines 105–130 are chunk 4.
Step-by-step: what chipguard_cnn.py does, in plain English
- Bring in
timefor the benchmark,numpyto generate data,torchandtorch.nnfor the model, andDataLoaderandDatasetfor batching. - Define
SyntheticWaferDataset. For each sample, draw a 3-by-64-by-64 block of noise around 0.5: three channels standing in for optical, infrared and x-ray. With probability 0.4, mark it defective. Then paint a bright two-pixel-high line at a random row and column span on the optical channel, plus a fainter, wider halo on the infrared channel. Clip every value to the range 0 to 1. __len__and__getitem__are the two methods a DataLoader needs: how many samples there are, and sample numberidxas a pair of tensors (image, label).- Define
ChipGuardCNN.features: two blocks of convolution, BatchNorm, ReLU and max-pool. The first convolution keeps 64×64 and produces 16 feature maps; the pool halves that to 32×32; the second block produces 32 maps at 16×16. - Define
ChipGuardCNN.head. It flattens the 32×16×16 maps into 8,192 numbers and drops 30% of them at random during training. Then a dense layer down to 64, ReLU, and a dense layer to 2 raw class scores (logits). forwardruns the features and then the head.train(): build a training loader (1,200 images, shuffled batches of 32) and a validation loader (300 images from a different seed, so nothing overlaps). The loss is cross-entropy; the optimizer is AdamW at learning rate 1e-3.- Each epoch,
model.train()turns dropout on and makes BatchNorm use batch statistics. For every batch: move it to the device, clear the old gradients, run forward, compute the loss, run backward, step. Keep a running loss and a count of correct predictions. - Then
model.eval()andtorch.inference_mode(): dropout off, BatchNorm on its running averages, no gradient recording. Count correct predictions on the validation set and print both accuracies. benchmark(): make one fake frame. Run it 20 times as a warm-up, so first-call costs are paid before the clock starts. If on a GPU, synchronize so queued work has finished. Time 200 single-frame predictions, convert to milliseconds per frame, and compare with the 16.6 ms budget.- When run as a script: pick
cudaif available, elsecpu; build the model; train five epochs; benchmark.
# pip install "torch>=2.4" "numpy>=2.1"
"""ChipGuard defect detector: synthetic wafer tensors -> CNN -> latency check.
Fully offline; trains on CPU in about a minute at these sizes. A GPU is a
bonus, not a requirement.
"""
# ── chunk 1: the fake wafer scanner (Dataset) ──
import time
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
class SyntheticWaferDataset(Dataset):
"""Synthetic wafer surface scans, 3 channels:
[0] optical surface [1] infrared heatmap [2] x-ray reflectance
A defect is a bright micro-crack line plus a thermal halo around it.
"""
def __init__(self, num_samples=1000, img_size=64, seed=42):
rng = np.random.default_rng(seed)
self.images, self.labels = [], []
for _ in range(num_samples):
base = rng.normal(0.5, 0.08, (3, img_size, img_size)).astype(np.float32)
label = int(rng.random() > 0.6) # ~40% defect rate
if label:
row = int(rng.integers(10, img_size - 10))
c0 = int(rng.integers(5, img_size - 25))
c1 = c0 + int(rng.integers(10, 20))
base[0, row:row + 2, c0:c1] += 0.45 # optical crack line
base[1, row - 1:row + 3, c0 - 2:c1 + 2] += 0.30 # thermal halo
self.images.append(np.clip(base, 0.0, 1.0))
self.labels.append(label)
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
return torch.from_numpy(self.images[idx]), torch.tensor(self.labels[idx])
# ── chunk 2: the network ──
class ChipGuardCNN(nn.Module):
"""Two conv blocks + a small head, sized for sub-16ms CPU inference."""
def __init__(self, num_classes=2):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, padding=1), # 64x64 stays 64x64
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(2), # -> 32x32
nn.Conv2d(16, 32, kernel_size=3, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2), # -> 16x16
)
self.head = nn.Sequential(
nn.Flatten(), # 32*16*16 = 8192
nn.Dropout(0.3), # fight the fc-layer overfit
nn.Linear(32 * 16 * 16, 64),
nn.ReLU(),
nn.Linear(64, num_classes),
)
def forward(self, x):
return self.head(self.features(x))
# ── chunk 3: the training loop ──
def train(model, device, epochs=5):
train_loader = DataLoader(SyntheticWaferDataset(1200, seed=42),
batch_size=32, shuffle=True)
val_loader = DataLoader(SyntheticWaferDataset(300, seed=101), batch_size=32)
criterion = nn.CrossEntropyLoss()
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
for epoch in range(1, epochs + 1):
model.train() # dropout on, batchnorm uses batch stats
running, correct, seen = 0.0, 0, 0
for x, y in train_loader:
x, y = x.to(device), y.to(device)
opt.zero_grad()
logits = model(x)
loss = criterion(logits, y)
loss.backward() # backprop — your XOR code, industrialized
opt.step()
running += loss.item() * y.size(0)
correct += (logits.argmax(1) == y).sum().item()
seen += y.size(0)
model.eval() # dropout off, batchnorm uses running stats
v_correct, v_seen = 0, 0
with torch.inference_mode():
for x, y in val_loader:
x, y = x.to(device), y.to(device)
v_correct += (model(x).argmax(1) == y).sum().item()
v_seen += y.size(0)
print(f"epoch {epoch}/{epochs} | loss {running / seen:.4f} "
f"| train acc {correct / seen:.2%} | val acc {v_correct / v_seen:.2%}")
# ── chunk 4: the latency benchmark and the main block ──
def benchmark(model, device, frames=200):
"""Honest single-frame latency: warm up first; sync the GPU if present."""
model.eval()
frame = torch.randn(1, 3, 64, 64, device=device)
with torch.inference_mode():
for _ in range(20): # warmup: allocator, kernel selection, caches
model(frame)
if device.type == "cuda":
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(frames):
model(frame).softmax(1).argmax(1)
if device.type == "cuda":
torch.cuda.synchronize()
ms = (time.perf_counter() - t0) / frames * 1000
verdict = "PASS — 60 FPS ready" if ms < 16.6 else "FAIL — SLA violated"
print(f"\nlatency {ms:.2f} ms/frame | throughput {1000 / ms:.0f} FPS | {verdict}")
if __name__ == "__main__":
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"device: {device}")
model = ChipGuardCNN().to(device)
train(model, device)
benchmark(model, device)
opt.zero_grad()1
logits = model(x)2
loss = criterion(logits, y)3
loss.backward()4
opt.step()5
- Clear the old gradients. PyTorch adds each new gradient onto whatever is already stored in a parameter's
.grad, because some training schemes accumulate over several batches on purpose. Forget this line and every step uses this batch's gradient plus every earlier one, and training wanders. It must run beforebackward(), not after. - The forward pass. Calling the model runs
forward(), and autograd records every operation into a graph as it goes. The output is raw scores, one per class, called logits. The common mistake is running this withmodel.eval()still set from the last validation pass, so dropout stays off and BatchNorm stops updating its statistics. - The loss.
nn.CrossEntropyLossexpects raw logits and applies softmax and the log itself. Feeding it probabilities you already passed through softmax is the classic error: nothing crashes, the loss is still a number, and the gradient is quietly muted. - The backward pass. Walks the recorded graph in reverse and fills in
.gradfor every parameter that requires it. This is the sevend-lines ofxor_backprop.py, for a network with half a million parameters. It works only on a single number, and the graph is freed afterwards, so calling it twice on one forward pass raises an error. - The step. The optimizer reads each parameter's
.gradand updates the parameter; AdamW also scales the stride per parameter and applies weight decay. It touches only the parameters it was built with. The classic phase-two mistake infinetune_timm.py: unfreeze the last backbone block but keep the optimizer built over the head alone. Those layers now compute gradients and never move.
Three details worth pausing on.
nn.BatchNorm2d normalizes each channel's activations to mean 0
and variance 1 across the batch, then rescales with two learned parameters. It keeps every layer
in the healthy activation range that Section 04 showed you matters, and it lets you train with
higher learning rates.
model.train() versus model.eval() is not
decoration. Dropout and BatchNorm behave differently in each mode — BatchNorm switches from
batch statistics to running averages at inference — and forgetting eval() is a
classic silent accuracy bug.
The benchmark does two things naive benchmarks skip. It runs warmup
iterations, because the first calls pay one-time allocator and kernel-selection costs. And it
calls cuda.synchronize(), because GPU calls are asynchronous — without a sync you
are timing the queueing of work, not the work.
| Stage | Output shape | Parameters |
|---|---|---|
| input | [32, 3, 64, 64] | — |
| Conv2d 3→16, 3×3 + BatchNorm | [32, 16, 64, 64] | 448 + 32 |
| MaxPool 2×2 | [32, 16, 32, 32] | 0 |
| Conv2d 16→32, 3×3 + BatchNorm | [32, 32, 32, 32] | 4,640 + 64 |
| MaxPool 2×2 | [32, 32, 16, 16] | 0 |
| Flatten → Linear 8192→64 | [32, 64] | 524,352 |
| Linear 64→2 | [32, 2] | 130 |
| Total | — | ≈ 529,666 |
Read the parameter column, which is marker 3 of Fig. 4.4g drawn as numbers: the two conv layers — which do nearly all the visual work — hold under 1% of the parameters. The dense layer bridging to the head holds 99%. That's weight sharing in action, and it's also why the dropout sits where it does: the fully-connected bridge is where CNNs overfit.
Questions you might be asking now
Fig. 4.4g and the shape table say where the numbers go. The questions below follow the numbers themselves: one tile through every layer, the loop's three counting words, BatchNorm, and the two scores at the end. PyTorch hides those values, so every answer uses a numpy copy of ChipGuardCNN trained on the same data, and the four tiles below.
| Tile | Label | Crack painted on | Brightest optical pixel | Average optical pixel |
|---|---|---|---|---|
| 0 | clean | none | 0.75 | 0.498 |
| 1 | clean | none | 0.76 | 0.501 |
| 10 | cracked | rows 25–26, columns 29–38 | 1.00 | 0.502 |
| 16 | cracked | rows 24–25, columns 14–30 | 1.00 | 0.503 |
Walk one wafer tile through ChipGuardCNN. What happens to the numbers at each layer, not just the shapes?
Tile 10 goes in as 12,288 numbers, with a crack pixel of 0.921 on a background near 0.499. It comes out as two scores, −4.5654 for clean and +0.8287 for defect: 99.55% defect. On the way, BatchNorm lifts the crack pixel to 8.793 and then 14.170, and half of every map is set to zero. Two thirds of the 7,012,480 multiplies happen in the second convolution.
chipguard_numpy.py rebuilds ChipGuardCNN in plain numpy, so that every intermediate number can be printed. It uses the same generator and seed, the same layers, the same batch size, the same AdamW settings and the same five epochs. Then it runs one tile in eval mode, as benchmark() does. Its random starting weights differ from PyTorch's, so your PyTorch run agrees in shapes and counts, not in the decimals.
The tile is tile 10 from the table above. Follow one pixel on the crack: row 25, column 34. At each layer the script also reports the middle value (the median) of the same map, which stands for "a typical background number". Fig. 4.4k is the whole walk, one row per station.
- The crack stands out in units of spread. The crack pixel is 0.921 against a typical 0.499 at the input, and 1.479 against 0.807 in conv1's map 10: a small gap. BatchNorm subtracts the map's stored average and divides by its stored spread, which puts the background at 0.022 and the crack at 8.793.
- Most numbers are thrown away. ReLU sets every negative number to 0: 49% of them after the first block, 50% after the second. Each pool keeps one number in four. The crack pixel survives both, because it is the largest in its 2×2 patch.
- Where the work is. The second convolution does 32 × 32 positions × 32 kernels × 144 multiplies = 4,718,592, which is 67.3% of the tile's arithmetic. The dense layer holds 99% of the weights but does 7.5% of the multiplies.
- Two scores, one verdict. The last layer turns 64 numbers into two logits, −4.5654 for clean and +0.8287 for defect. Softmax makes them 0.0045 and 0.9955, and argmax says defect. The last question in this block does that step by hand.
Read the bars against Fig. 4.4g, marker 3. The dense layer holds 524,352 of the 529,666 parameters and uses each one once: 524,288 multiplies. The second convolution reuses its 4,640 weights at all 1,024 positions. That reuse is weight sharing, seen from the compute side.
The honest limit: counting multiplies estimates latency; it does not measure it. Moving 65,536 numbers through memory costs time too, which is why benchmark() times the real forward pass against the 16.6 ms budget. The map numbers are also this run's; another seed trains different maps with the same shapes and counts.
BatchNorm makes the crack stand out, ReLU and pooling discard most numbers, and the second convolution does two thirds of the work.
Is an epoch the same as a batch or a step?
No. A batch is the group of tiles read together: 32. A step is one weight update, made from one batch. An epoch is one full pass over all 1,200 training tiles. chipguard_cnn.py makes 38 steps per epoch, the last one on a batch of 16, so its 5 epochs are 190 steps.
The three words count different things in the same two loops. In chipguard_cnn.py the outer loop is for epoch in range(1, epochs + 1) and the inner one is for x, y in train_loader. Each pass through the inner loop takes one batch and makes one step.
| Word | What it is | Set by | In chipguard_cnn.py | In xor_backprop.py |
|---|---|---|---|---|
| Batch | The examples pushed through together before one update | batch_size in the DataLoader | 32 tiles; the last batch of each epoch has 16 | All 4 examples at once |
| Step | One zero_grad, forward, loss, backward and step | How many batches the loader hands out | 38 per epoch, 190 in total | 5,001 in total |
| Epoch | Every training example read once | The outer loop | 5 | 5,001, because every step reads the whole dataset |
| How often the weights move | Once per step | — | 190 times | 5,001 times |
- Count the tiles in one epoch. SyntheticWaferDataset(1200) holds 1,200 tiles. shuffle=True deals them in a new order every epoch.
- Divide by the batch size. 1,200 ÷ 32 = 37.5.
- Keep the leftovers. The DataLoader's default, drop_last=False, keeps them. 37 full batches hold 37 × 32 = 1,184 tiles, and the other 1,200 − 1,184 = 16 make a 38th batch. That is 38 steps per epoch.
- Multiply by the epochs. 38 × 5 = 190 steps. This is the 190 in the last key of Fig. 4.4c.
- Count the tile visits. 1,200 × 5 = 6,000. Every tile is read five times, each time inside a freshly shuffled batch.
Check it on the four tiles above, treated as a whole training set. With a batch size of 2, one epoch is 2 steps. With a batch size of 3 it is still 2 steps: 3 tiles, then the 1 left over. With a batch size of 4 it is 1 step, and then an epoch and a step are the same thing. That is exactly how xor_backprop.py trains.
Why the printed loss looks smoother than training is
chipguard_cnn.py prints one loss per epoch: running / seen. It adds every step's loss times its batch size and divides by 1,200. So it averages 38 different versions of the model, because the weights moved after every one of those steps.
The numpy copy also prints every step's own loss. Epoch 1 starts at 0.6716, jumps to 2.8856 on step 2, and ends at 0.1126, while the epoch line prints 0.5200. Epoch 5 prints 0.0057, a little above epoch 4's 0.0053, although nothing went wrong: an average of noisy steps wobbles.
- One epoch, cut into batches. The strip is all 1,200 tiles in a fresh shuffled order. Every 32 tiles form a batch, and each batch goes through one full training step. The weights move once per batch, never once per tile.
- The leftover batch. 37 batches of 32 use 1,184 tiles, so the 38th holds 16. It is still a full step, so an epoch is 38 steps. With drop_last=True those 16 would be skipped: 37 steps per epoch, 185 in total.
- The jagged line is the steps. Each point is one step's loss on its own batch, just after the weights moved. Step 1 is 0.6716 and step 2 jumps to 2.8856. In the last epoch single steps range from 0.0004 to 0.0370, because every batch is a different sample of tiles.
- The flat segments are what gets printed. Each is the epoch's batch-weighted average of 38 step losses. Averages of noisy steps wobble, so epoch 5 reads 0.0057, above epoch 4's 0.0053. The validation row dips to 44.00% in epoch 2; the next question explains why.
The honest limit: the words are conventions. Some code says "iteration" for a step, and very large runs may never finish an epoch, so they count steps alone. Gradient accumulation, the reason key 1 of the training-step anatomy says PyTorch adds gradients, builds one step out of several batches. Check what the loader and the optimizer actually did.
A batch is what one step reads, a step is one weight update, and an epoch reads every tile once: 38 steps here.
Why normalise between layers at all? Is BatchNorm the same thing as the feature scaling in Module 02?
The arithmetic is the same: subtract an average, divide by a spread. The job differs. StandardScaler rescales the input columns once, from the training rows. BatchNorm rescales every channel of a layer's output on every training step, from that batch, then applies a learned scale and shift. Across 40 ReLU layers the activations shrink to a spread of 0.000000176 without it and stay near 0.58 with it.
Module 02's canyon was about input columns. Two columns with very different scales stretched the loss bowl, and one learning rate could not walk it. Inside a network, every layer's input is the previous layer's output. conv2 reads the 16 maps that conv1 writes, so those 16 maps are conv2's input columns.
They are untidy columns. On the four tiles above, conv1's 16 maps have averages from −0.1764 to +0.9960 and spreads from 0.0458 to 0.0945. A map that averages about 1.0 with a spread under 0.1 hands conv2 mostly a constant. And unlike input columns, they move: every step changes conv1's weights, so conv2's inputs shift under it.
BatchNorm by hand, on one channel
Take map 10 of conv1, the map that reacts to cracks in the walk-through above, and treat the four tiles as one training batch.
- Gather the channel. Map 10 for all four tiles is 4 × 64 × 64 = 16,384 numbers. BatchNorm2d pools every position of every tile in the batch, one channel at a time.
- Find the average and the spread. The code does the adding: mean 0.8024, variance 0.006673. Module 02's follow-up on the standard deviation does the same steps by hand on three numbers.
- Normalise one value. Tile 10's crack pixel reads 1.4786. 1.4786 − 0.8024 = 0.6762, and √(0.006673 + 0.00001) = 0.08175, so 0.6762 ÷ 0.08175 = 8.272. The 0.00001 is ε (epsilon), a tiny number that prevents dividing by zero when a channel is flat.
- Apply the learned scale and shift. γ (gamma) = 1.0329 and β (beta) = −0.0569 are learned by the optimizer like any weight: 1.0329 × 8.272 − 0.0569 = 8.487. They let the network undo some of the normalising where that lowers the loss.
- At inference, use the stored averages. model.eval() swaps in running averages kept during training: mean 0.8006, variance 0.006250. That gives 0.6780 ÷ 0.07912 = 8.569, then 1.0329 × 8.569 − 0.0569 = 8.794. It is the 8.793 at the BatchNorm station of the walk-through, give or take rounding.
| StandardScaler (Module 02) | BatchNorm2d (this module) | |
|---|---|---|
| What it rescales | Each input column, such as page views or cart value | Each channel of a layer's output, such as conv1's 16 maps |
| Where it runs | Once, before the model | Inside the model, after conv1 and after conv2 |
| Where its average and spread come from | The training rows, once, in fit() | In training, the current batch on every step: 16,384 values per channel for the four tiles |
| Learned numbers | None | A scale γ and a shift β per channel: 32 in bn1, 64 in bn2 |
| Stored for serving | A mean and a spread per column | A running mean and running variance per channel, plus γ and β |
| Training and serving | Identical arithmetic | Different: batch statistics in model.train(), running averages in model.eval() |
| Does one example's result depend on the others? | No | In training, yes: tile 10's crack pixel normalises to 8.2709 in the batch of four above, and to 7.5348 in a batch of four cracked tiles |
What it buys, measured
batchnorm_depth.py reuses the deep stack of vanishing_gradient.py: width 64, starting weights with spread 1/√64, one layer after another. It feeds a batch of 32 rows, because a batch average needs a batch, and runs the same weights with and without BatchNorm after every layer.
- The forward spread. Without BatchNorm the spread of the activations falls at every layer: 0.588 at layer 1, 0.0214 at layer 10, 0.000000176 at layer 40. With BatchNorm each layer rescales its outputs, so the spread stays between 0.580 and 0.593.
- The backward signal. The dashed line marks 1, about the size of the gradient leaving the output; each tick is ten orders of magnitude. Forty sigmoid layers pass back 3.48e-26 of it, or 0.644 with BatchNorm. ReLU alone passes back 3.37e-07.
- BatchNorm is not free depth. With ReLU, 40 BatchNorm layers pass back 2.49e+03: the gradient grows about 1.24 times per extra layer. Very deep networks such as ResNets add skip connections that carry the signal around each block. ChipGuardCNN has two convolutions, so this does not bite.
- Two modes, two answers. Solid: each validation batch's own statistics. Dashed: the running averages, as in model.eval(). In epoch 2 the same weights read 99.33% and 44.00%, because they had moved faster than the running averages could follow. By epoch 3 both are near 100%.
Marker 1 of Fig. 4.4m is the forward half of section 04's failure: without BatchNorm the activations fade on the way forward, as the gradient faded on the way back. BatchNorm fixes the forward half, and with sigmoid it restores the backward half too: 0.644 at depth 40 instead of 3.48e-26.
The honest limits are markers 3 and 4. With ReLU at depth 40 BatchNorm overshoots, which is why very deep networks add skip connections. And training and serving compute different things, which is why model.eval() matters and why BatchNorm misbehaves at a batch size of 1.
BatchNorm is feature scaling moved inside the network: every channel, every training step, statistics from the batch, a learned scale and shift, and running averages for serving.
What is a logit, and how do the model's two scores become "defect, 99.55%"? And why must I not apply softmax before CrossEntropyLoss?
A logit is a raw score, one per class, and it can be any number. Softmax turns the pair into two probabilities that add up to 1, and only the gap between the scores matters. Tile 10 scores −4.5654 for clean and +0.8287 for defect, a gap of 5.3941, which is 99.55% defect. Applying softmax yourself before the loss makes the push on a confident mistake about 100 times weaker.
The last layer of ChipGuardCNN is nn.Linear(64, 2). For each tile it outputs two numbers, one for "clean" and one for "defect". Nothing forces them between 0 and 1, and nothing makes them add up to 1. Those raw outputs are the logits.
- Raise e to each logit. e is about 2.718. e^−4.5654 = 0.0104 and e^0.8287 = 2.2903. This makes both numbers positive and keeps their order.
- Add them. 0.0104 + 2.2903 = 2.3007.
- Divide each by the total. Clean: 0.0104 ÷ 2.3007 = 0.0045. Defect: 2.2903 ÷ 2.3007 = 0.9955. The two now add up to 1, so they can be read as probabilities.
- Pick the verdict. argmax takes the larger one: defect. This is the .softmax(1).argmax(1) at the end of benchmark().
- Score it during training. The label says cracked, so the loss is −log of the defect probability: −log(0.9955) = 0.0045. This is the cross-entropy of section 06, with log meaning the natural log.
Only the gap matters. Add 10 to both logits and both e-powers are multiplied by the same e^10, which cancels in step C. For two classes the whole recipe collapses to P(defect) = sigmoid(defect logit − clean logit). For tile 10 that is sigmoid(5.3941) = 0.9955, the same sigmoid as section 03's single neuron and Module 02's logistic regression.
| Tile | Label | Clean logit | Defect logit | Gap | P(defect) | Loss |
|---|---|---|---|---|---|---|
| 0 | clean | +3.1272 | −5.4968 | −8.6240 | 0.0002 | 0.0002 |
| 1 | clean | +1.2284 | −3.8430 | −5.0713 | 0.0062 | 0.0063 |
| 10 | cracked | −4.5654 | +0.8287 | +5.3941 | 0.9955 | 0.0045 |
| 16 | cracked | −6.7215 | +2.1823 | +8.9038 | 0.9999 | 0.0001 |
The softmax-twice mistake
nn.CrossEntropyLoss applies softmax and the log itself, which is why the anatomy after chipguard_cnn.py warns against feeding it probabilities. If you pass it numbers you already softmaxed, it applies softmax a second time, to inputs stuck between 0 and 1. Nothing crashes. The script works out what changes, for a tile whose label is cracked:
| Logits | What the model believes | Correct: loss, push | Softmax twice: loss, push |
|---|---|---|---|
| +4.0, −1.0 | Sure it is clean: confidently wrong | 5.0067, −0.9933 | 1.3035, −0.0097 |
| 0.0, 0.0 | Unsure | 0.6931, −0.5000 | 0.6931, −0.2500 |
| −4.0, +4.0 | Sure it is cracked: right | 0.0003, −0.0003 | 0.3134, −0.0002 |
- Two scores, two probabilities. The dots are the raw logits. Raised to powers of e they become 0.0104 and 2.2903, so the defect score is already 220 times the clean one. Divided by their total they become 0.0045 and 0.9955. The bars are to scale.
- Only the gap matters. The curve is the sigmoid of the gap between the two logits. Tile 10's +5.39 sits high on the right at 0.9955; the clean tiles sit bottom left at 0.0002 and 0.0062. Beyond a gap of about 5 the curve is nearly flat.
- Softmax twice. The model is sure a cracked tile is clean. The correct loss pushes the defect logit with −0.9933; softmax applied twice pushes with −0.0097. The doubled loss also cannot fall below 0.3133, so training looks stalled.
Read the first row of the table with marker 3 of Fig. 4.4n. A confident mistake is exactly when the model most needs correcting, and the doubled softmax weakens the push 0.9933 ÷ 0.0097 = 102 times. The last row is the other symptom: a perfect answer still scores 0.3134.
The honest limit: softmax outputs add up to 1, but they are not measured frequencies. Whether 0.9955 means "right 99.55 times in 100" can only be checked on held-out tiles. On synthetic cracks this clean every score sits at the flat ends of the curve; real wafers put many tiles near the middle.
Logits are raw scores; softmax turns their gap into probabilities; CrossEntropyLoss wants the raw logits, because it applies softmax itself.
Tier 2: fine-tune a pretrained backbone (the 2026 default move)
Tier 1 gave ChipGuard a working detector with 529,666 parameters, trained from scratch on 1,200 tiles. A real factory has a few thousand labelled tiles, not half a million, and a deadline this quarter. Tier 2 is what a professional reaches for first: keep somebody else's visual system, trained on 1.2 million photographs, and teach only a small head about wafers. It is Fig. 4.4 turned into twenty lines of code, and it is where the two learning rates in Fig. 4.4f, marker 2, come from.
In practice, almost nobody at a company starts from ChipGuardCNN. The default
professional move is Fig. 4.4 as code: pull an ImageNet-pretrained backbone from
timm (the de facto model zoo — 1,000+ architectures behind one function),
freeze it, and train a fresh head. Note the two-phase recipe in the comments: head-only first,
then optionally unfreeze the last block at a 10× lower learning rate.
finetune_timm.py. Shaded blocks are frozen: requires_grad = False, no gradients computed, no weights moved. The learning rates are the ones in the script and its closing comment.- Phase 1: only the head learns. Every pretrained weight is switched off for training, so the backbone behaves as a fixed feature extractor: the same tile always produces the same 1,024-odd numbers. The head, a single fresh layer to two classes, learns at the ordinary rate of 1e-3. This phase is fast because the backward pass stops at the head.
- Phase 2: the last block joins, slowly. The final block holds the most task-specific features, so it is the first one worth adapting. It trains at 1e-4, a tenth of the head's rate, because the pretrained weights are the whole reason for borrowing this network. Move them at full speed and you overwrite what you came for.
- The failure to watch for. The optimizer only touches the parameters it was constructed with. Unfreezing a block does not enrol it. If you flip
requires_gradback on and reuse the old optimizer, those layers spend time computing gradients that are never applied — the exact mistake named in key 5 of the training-step anatomy.
Step-by-step: what finetune_timm.py does, in plain English
- Bring in
torch,F(functional operations: the resize and the loss),DataLoader,timm, and the wafer dataset fromchipguard_cnn.py. - Pick the device:
cudaif available, elsecpu. timm.create_model("mobilenetv3_small_100", pretrained=True, num_classes=2): download a small ImageNet-trained backbone and replace its final layer with a fresh 2-class head.- Phase 1 freeze: set
requires_grad = Falseon every parameter, then back toTrueon the classifier's parameters only. Autograd will now compute gradients for the head and nothing else. - Move the model to the device and wrap it in
torch.compile, which fuses operations for speed. - Build AdamW over only the parameters that still require gradients, at learning rate 1e-3.
- Build the same two loaders as before: 1,200 training tiles, 300 validation tiles.
resize: the backbone expects 224×224 inputs, so scale each 64×64 tile up with bilinear interpolation, with anti-aliasing on.- Three epochs of the same loop: training mode, resize the batch, clear gradients, forward and cross-entropy in one line, backward, step.
- Each epoch, evaluate under
inference_modeand print the validation accuracy. - Phase 2 is described in the closing comment and not run. It unfreezes the final backbone block and continues at 1e-4, ten times slower, so the pretrained weights move gently.
# pip install "torch>=2.4" "timm>=1.0"
"""Fine-tune a pretrained backbone on ChipGuard wafers — the 2026 default move."""
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
import timm
from chipguard_cnn import SyntheticWaferDataset # reuse the wafer generator
device = "cuda" if torch.cuda.is_available() else "cpu"
# ImageNet-pretrained backbone with a fresh 2-class head. Swapping to
# efficientnet_b0 or a ViT is literally a string change.
model = timm.create_model("mobilenetv3_small_100", pretrained=True, num_classes=2)
# Phase 1: freeze the backbone — it already knows edges, textures, gradients.
for p in model.parameters():
p.requires_grad = False
for p in model.get_classifier().parameters():
p.requires_grad = True
model = model.to(device)
model = torch.compile(model) # PyTorch 2.x: kernel fusion — a near-free speedup
opt = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=1e-3)
train_loader = DataLoader(SyntheticWaferDataset(1200, seed=42), batch_size=32, shuffle=True)
val_loader = DataLoader(SyntheticWaferDataset(300, seed=101), batch_size=32)
def resize(x): # backbone expects 224x224; our wafer tiles are 64x64
return F.interpolate(x, size=224, mode="bilinear", antialias=True)
for epoch in range(3):
model.train()
for x, y in train_loader:
x, y = resize(x.to(device)), y.to(device)
opt.zero_grad()
loss = F.cross_entropy(model(x), y)
loss.backward()
opt.step()
model.eval()
correct = total = 0
with torch.inference_mode():
for x, y in val_loader:
x, y = resize(x.to(device)), y.to(device)
correct += (model(x).argmax(1) == y).sum().item()
total += y.size(0)
print(f"epoch {epoch + 1} | val acc {correct / total:.2%}")
# Phase 2 (optional, squeezes out the last point of accuracy): unfreeze the
# final backbone block and continue at lr=1e-4 — pretrained weights should
# move slowly or you erase what made them valuable.
Deprecation radar: older tutorials load torchvision models with
pretrained=True — that boolean has been deprecated in torchvision since 0.13 in
favor of weights=ResNet18_Weights.DEFAULT-style enums. timm's
pretrained=True kwarg, confusingly, remains current. When you see the torchvision
boolean in a codebase, that's a sign the vision stack hasn't been touched in years.
CNN or vision transformer? ViTs treat an image as a sequence of patches and apply the attention machinery you'll meet in Module 05.
The practical rule as of Aug 2026: with large-scale pretraining, ViT-family backbones (DINOv2-style) win on rich natural imagery and anything needing global context; CNNs' built-in spatial bias still wins on small datasets, tight latency budgets, and edge hardware.
Since timm serves both behind the same API, the honest answer is: benchmark both, it's a one-string change. But the bigger 2026 truth is one level up: most applied vision work is now either fine-tuning a pretrained backbone or calling a multimodal LLM API. Training bespoke architectures from scratch is a specialty, not the default.
Tier 3: skip training entirely — call a vision LLM
ChipGuard has a second inspection flow that never appears in the memo's headline numbers: returned units and audit samples, a couple of hundred a day, where today a person writes a note explaining each verdict. There is no 16.6 ms budget on that desk and no training set either. For that flow the cheapest engineering is to train nothing at all and ask a model that already knows what a crack looks like. Most vision projects in 2026 should start here and only leave when the volume forces them out.
Multimodal LLMs read images natively, and for low-volume, judgment-heavy inspection they change the economics completely: zero training data, zero training time, and the model can explain its verdict. Here's the ChipGuard task as one API call, with a Pydantic schema so the answer comes back as validated structured data instead of prose.
Step-by-step: what vision_llm.py does, in plain English
- Bring in
base64to encode the image, theanthropicclient, and pydantic'sBaseModelfor the answer schema. - Define
Inspection, the shape the answer must take:defect_found(true or false),confidence(the model's own 0 to 1 guess, not a calibrated probability),location_hint(where to look), andreasoning. - Create the client. It reads
ANTHROPIC_API_KEYfrom the environment. - Read the PNG bytes and base64-encode them into text, which is how an image travels inside a JSON request.
client.messages.parse(...): one call. The user message holds two content blocks, the image and an instruction describing what a micro-crack looks like.output_format=Inspectionasks the SDK to make the model answer in that schema and to validate the reply against it.response.parsed_outputis anInspectioninstance. Print the verdict, the location hint, and the reasoning.
# pip install "anthropic>=0.70" "pydantic>=2"
"""When you have 50 images a day instead of 5M frames: just ask a vision LLM."""
import base64
import anthropic
from pydantic import BaseModel
class Inspection(BaseModel):
defect_found: bool
confidence: float # the model's own 0-1 estimate — NOT calibrated
location_hint: str # e.g. "upper-left quadrant, diagonal line"
reasoning: str
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
with open("wafer_tile_0042.png", "rb") as f:
image_b64 = base64.standard_b64encode(f.read()).decode()
response = client.messages.parse(
model="claude-opus-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "image",
"source": {"type": "base64", "media_type": "image/png",
"data": image_b64}},
{"type": "text",
"text": "You are a semiconductor QA inspector. Examine this wafer "
"tile for micro-cracks: thin bright lines cutting across "
"the surface grain, often with a diffuse halo. "
"Report your finding."},
],
}],
output_format=Inspection,
)
report = response.parsed_output # a validated Inspection instance
print(f"defect={report.defect_found} where={report.location_hint}")
print(report.reasoning)
Cost math, date-stamped Aug 2026: claude-opus-5 runs $5 per million input
tokens and $25 per million output tokens; a full-detail image plus this prompt is roughly
1,500–2,000 tokens, so an inspection lands around a cent. Latency is a second or two — three
orders of magnitude over the 16.6 ms line SLA, which is exactly why this tier serves the
offline inspection flows (returned units, audit sampling, triaging the CNN's uncertain
cases), not the conveyor.
- Both axes are logarithmic. Volume runs from a hundred images a day to ten million, and cost from a hundred dollars a year to a hundred million, so each step is ten times the last. A straight rising line on this chart is a cost that grows in direct proportion to volume, which is exactly what per-call pricing is.
- The crossing point is the whole decision. Left of about 55,000 images a day, renting a model costs less than building one and nobody should write training code. Right of it, the rental bill passes the build cost and keeps going, every year. ChipGuard's conveyor sits far to the right at 5 million frames a day, $18.25M a year; its returns desk sits far to the left at $730 a year. The same company needs both answers.
- Cost is not the only ruler. Even if the API were free, the lower ruler rules it out for the conveyor: one call takes about 1,500 ms and the line delivers a frame every 16.6 ms, so ninety wafers pass while one verdict is in flight. Latency, volume and whether the images may leave the building are three independent vetoes, and any one of them settles the question on its own.
| Option | Choose when | Avoid when | Typical cost |
|---|---|---|---|
| Custom CNN, trained from scratch | Hard latency floor (<10 ms), edge/embedded deployment, unusual inputs (our 3-channel optical/IR/x-ray stack), 50K+ labeled images | You have <10K labels, or a pretrained backbone covers the domain | Weeks of engineering + GPU time; cheapest per-inference once deployed |
| Fine-tuned pretrained backbone (the default) | 500–50K labeled images, roughly natural-image-like inputs, need <50 ms latency or on-prem inference | Nearly zero labels, or the task needs open-world reasoning and explanation | Hours to days; compute nearly free; per-inference cost ≈ electricity |
| Multimodal LLM API | Low volume, zero training data, criteria change often, verdicts need explanations, shipping this week matters | Sub-second latency SLA, millions of images/day, or data that cannot leave the premises | ~$0.01/image, zero build cost; grows linearly with volume forever |
The stack, and why
Before the lab, here is every tool this module leaned on for ChipGuard's inspector, what Dr. Thorne could have chosen instead, and the point at which each switch becomes worth it.
The stack, and why
The one question that decides it: how many labelled images do you have, and how fast must each one be answered?
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Framework | PyTorch 2.12 | JAX / Flax, TensorFlow / Keras | Runs line by line, so you can print and debug anything, and almost every pretrained model ships for it. Weakness: speed needs extra steps (torch.compile, export). | Your team already runs on TPUs or already writes JAX (JAX), or you must ship to phones inside an existing TensorFlow Lite pipeline. |
| Learning the mechanism | Hand-written NumPy (XOR, a tiny CNN) | Going straight to PyTorch | You see every derivative once, so autograd stops being magic. Weakness: far too slow for real images. | Move on the moment you can explain forward, loss, backward, step. Anything over ~1,000 images belongs in PyTorch. |
| Data feeding | Dataset + DataLoader | WebDataset, NVIDIA DALI, tf.data | Built in and simple; the same two methods work for any data. Weakness: Python workers can starve a fast GPU. | The images no longer fit on one disk or the GPU sits idle waiting for data: roughly 1 million images and up. |
| Model source | A small CNN from scratch (ChipGuardCNN) | Fine-tuned pretrained backbones, a hosted vision API | Tiny (529,666 parameters), fast, and fits an odd 3-channel optical/infrared/x-ray input. Weakness: needs plenty of labelled tiles. | Fewer than ~10,000 labels: fine-tune a backbone. No labels at all, or a few hundred images a day: call an API. |
| Pretrained backbones | timm 1.0 (mobilenetv3_small_100) | torchvision models, Hugging Face Transformers | Hundreds of image models behind one create_model call, with weights. Weakness: one more dependency, and many weights are for 224-pixel RGB photos. | You only need a classic ResNet and want fewer dependencies (torchvision), or the model must also read text (Transformers). |
| Hosted vision API | Claude, through the Messages API (claude-opus-5) | GPT or Gemini vision models, a self-hosted vision-language model | Handles any image with no training and returns structured output. Weakness: hundreds of milliseconds per call, and an image leaves your network. | You need under ~50 ms per image, millions of images a day, or the images may not leave the building. |
| Latency and deployment | Eager PyTorch with a warm-up benchmark | torch.compile, ONNX Runtime, TensorRT, OpenVINO | Measure first with no extra tooling. Weakness: Python overhead, and the TorchScript route is deprecated in favour of torch.export. | The benchmark misses the 16.6 ms budget, or you deploy on a CPU-only edge box: export to ONNX and use ONNX Runtime or OpenVINO. |
With a few thousand labels and a 16.6 ms budget, PyTorch with a small custom CNN is right; with fewer than ~10,000 labels start from a timm backbone, and with none, start from an API.
06 · Under the hoodThe Math, If You Want It
Everything Dr. Thorne needs has been built: a detector, a fine-tune, and a rented
verdict for the returns desk. What follows is the arithmetic underneath those three, for the reader who
would rather not take a claim on trust. Why does dz2 = a2 − y collapse to something that
simple? Where does the 448 come from? Why does cross-entropy scream at a confident mistake? None of it is
required to ship the inspector; open a block when an earlier claim felt like a rule you were asked to
memorise.
Backpropagation — the chain rule, spelled out
For our 2-layer network the gradient of the loss L with respect to a first-layer weight w₁ is a product of local derivatives along the path from that weight to the loss:
∂L/∂w₁ = ∂L/∂ŷ · ∂ŷ/∂z₂ · ∂z₂/∂a₁ · ∂a₁/∂z₁ · ∂z₁/∂w₁
Read right to left: how the weight moves its pre-activation z₁, how
z₁ moves the activation a₁ (the activation function's derivative —
the term that vanishes with deep sigmoids), how a₁ moves the next layer's
z₂ (just the weight w₂), and so on up to the loss. Backprop is the
observation that these products share prefixes: compute ∂L/∂z₂ once and every
weight below reuses it. That sharing turns an exponential computation into one backward
sweep — the same trick memoization plays in dynamic programming.
Why did our code get away with dz2 = a2 − y? Because sigmoid and
cross-entropy are made for each other: the loss derivative contributes a factor
1/(ŷ(1−ŷ)) and the sigmoid derivative contributes ŷ(1−ŷ) — they cancel, leaving the
beautifully simple "prediction minus truth". This pairing (softmax + cross-entropy in the
multiclass case) is standard precisely because of this clean, well-scaled gradient.
Convolution arithmetic — the formula and the shapes
A convolution is an element-wise multiply-and-sum between an image patch I and a kernel K, repeated at every position (i, j):
S(i,j) = (I ⊛ K)(i,j) = Σₘ Σₙ I(i+m, j+n) · K(m,n)
Here m, n index the kernel's rows and columns. Physically, the kernel is a pattern template: when the pixels under it match the kernel's weights, the dot product is large and positive — the feature "fires". A vertical-edge kernel (the 1/0/−1 columns in Fig. 4.2) fires exactly where bright pixels sit left of dark ones.
Output size, the formula you will use weekly: for input width n, kernel k, padding p, stride s:
out = ⌊(n + 2p − k) / s⌋ + 1
Check it against the code: 64 input, k=3, p=1, s=1 → ⌊(64+2−3)/1⌋+1 = 64 (padding
"same" preserves size); the 2×2 pool with stride 2 → ⌊(64−2)/2⌋+1 = 32. And parameter
count: a conv layer costs k² · C_in · C_out + C_out weights — note the image
size appears nowhere. That independence is weight sharing, and it's why the conv
layers in our shape table are so absurdly cheap next to the dense layer.
Cross-entropy — punishing confident mistakes
For a binary defect classifier with true label y ∈ {0,1} and predicted probability ŷ:
Loss = −( y·log(ŷ) + (1−y)·log(1−ŷ) )
The log is the point. If the true label is 1 (defect) and the model says ŷ = 0.99, the loss is −log(0.99) ≈ 0.01 — a whisper.
If the model confidently says ŷ = 0.01 for that same defect, the loss is −log(0.01) ≈ 4.6 — a scream, 460× louder. Cross-entropy punishes confident wrongness superlinearly, which is exactly the incentive you want for a defect detector. Why not mean squared error?
With a sigmoid output, MSE's gradient carries a σ′ factor that shrinks to zero precisely when the model is confidently wrong — the worst possible time to whisper. Cross-entropy's gradient stays proportional to the error (ŷ − y), so the most wrong predictions learn the fastest.
- Read the curve from right to left. At the right the model said 0.99 for the correct class and pays almost nothing, 0.0101. Walk left and the cost rises gently through the shrug at 0.5200, then turns almost vertical near the left edge. Confidence in the wrong answer is not penalised a bit more; it is penalised without limit, because −log(ŷ) goes to infinity as ŷ goes to 0.
- Why not squared error. For a sigmoid output, the gradient of squared error carries an extra factor ŷ(1−ŷ), which at ŷ = 0.01 is 0.0099. The two bars compare what each loss sends backwards at that point: 0.99 against 0.0098. Squared error is at its quietest precisely when the model is most wrong, which is the opposite of what a defect detector needs.
- The number to remember. A confident mistake costs 456 times a confident hit. That ratio is why a defect detector trained with cross-entropy will not settle for being sure and wrong about a micro-crack: the loss makes that the most expensive thing it can do.
There are no dumb questions
- Do I need a GPU for this module?
- No. Every code block here trains on CPU in minutes at these image sizes — that's deliberate. A free Colab T4 will speed up the lab's fine-tune, but the mechanism you're learning is identical. What changes with a GPU is scale, not concepts. Do note that your latency benchmark numbers are hardware-specific: report them with the hardware.
- Is anyone still training CNNs from scratch in 2026?
- Yes, but it's a niche: embedded/edge deployments with brutal latency and memory floors, unusual sensor stacks (multispectral, radar, our optical/IR/x-ray channels), and organizations with millions of proprietary labeled images. For everyone else the ladder is: try the API, then fine-tune a backbone, and only then consider bespoke training. Knowing the internals still matters — it's how you debug the first two rungs.
- Did vision transformers make CNNs obsolete?
- No — they redrew the map. ViTs need large-scale pretraining to beat CNNs' built-in spatial assumptions, and once pretrained they're excellent general backbones. CNNs remain the better small-data and edge answer. Since timm exposes both identically, treat it as an empirical question per project, not an ideology.
- Why synthetic data instead of real wafer images?
- Determinism and offline reproducibility — your results match the module's. In real projects, acquiring and labeling images is usually the bottleneck and the budget line, not the model (the Module 02 lesson again: data quality beats model choice). Augmentation is how you stretch a small real dataset; synthetic generation is how you bootstrap before you have one.
- My validation accuracy is higher than training accuracy. Bug?
- Usually not. Dropout is active during training (crippling the network on purpose) and off during eval; BatchNorm uses noisier batch statistics in training mode; and if you augment the training set, training examples are literally harder. A small val > train gap is normal. A huge one means your val set leaked or is too easy.
Defect detection is a scrap-cost arbitrage, and the ROI is one line of arithmetic: savings ≈ cost of escaped defects × catch-rate improvement.
ChipGuard loses $3.2M/year at a 12.4% human miss rate; a fine-tuned model holding a 0.8% miss rate recovers roughly $2.9M/year, against a build cost of about one engineer-month and under $1K of compute — payback measured in days of deployment.
Elevator version: "We can cut escaped-defect losses ~90% with a model that runs on a $300 GPU bolted to the conveyor." But carry the counter-pitch in the same pocket: when a $0.01 API call beats a $200K CV project.
If the workload is 200 returned units a day rather than 5M frames, a multimodal API costs ~$730/year, needs no ML team, and ships this week — the $200K custom build can never pay itself back.
The executive question is never "which architecture"; it's volume × latency. High volume + hard latency → own a model. Low volume + human timescales → rent one.
07 · The labBuild the Real Thing
Dr. Thorne's wafers are finished. The lab hands you the same problem with different pictures — three shapes instead of two verdicts — so that you write the transfer-learning loop instead of reading it. Everything ChipGuard was graded on is graded here too: accuracy on images the model has never seen, latency with the hardware named, and an honest list of what it still gets wrong. That list is the part a hiring manager reads.
Mission: fine-tune a small pretrained backbone on a shapes dataset you
generate locally with PIL (fully offline — no downloads except the backbone weights), then
report accuracy and latency like a production engineer would. The generator below
is your given 80% — it writes an ImageFolder-compatible directory tree. Your
20%: the fine-tune (adapt finetune_timm.py — you'll need
torchvision.datasets.ImageFolder plus a ToTensor transform
instead of the wafer dataset), the evaluation, and the write-up.
Step-by-step: what shapes_dataset.py does, in plain English
- Bring in
random(seedable, so the dataset is reproducible),Path, and PIL'sImageandImageDraw. - Fix the three class names and a 96-pixel square canvas.
draw_sample(cls, rng): pick a random light background and a random dark shape colour, so colour carries no information about the class. Pick a random radius and a centre kept fully inside the frame. Draw a circle, a square or a triangle, depending oncls.build_split(split, n_per_class, seed): for each class, create the foldershapes/<split>/<class>/and saven_per_classimages named by class and index. This layout, one folder per label, is exactly whatImageFolderreads.- When run as a script: 400 images per class for training with seed 0, 100 per class for validation with seed 1, 1,500 images in total.
# pip install "pillow>=10"
"""Generate a 3-class shapes dataset on disk — deterministic, fully offline."""
import random
from pathlib import Path
from PIL import Image, ImageDraw
CLASSES = ("circle", "square", "triangle")
SIZE = 96
def draw_sample(cls, rng):
# Random light background + random dark shape colour: forces the model
# to learn SHAPE, not colour statistics.
bg = tuple(rng.randint(190, 255) for _ in range(3))
fg = tuple(rng.randint(0, 120) for _ in range(3))
img = Image.new("RGB", (SIZE, SIZE), bg)
d = ImageDraw.Draw(img)
r = rng.randint(14, 34) # shape "radius"
cx = rng.randint(r + 4, SIZE - r - 4) # keep it fully in frame
cy = rng.randint(r + 4, SIZE - r - 4)
if cls == "circle":
d.ellipse((cx - r, cy - r, cx + r, cy + r), fill=fg)
elif cls == "square":
d.rectangle((cx - r, cy - r, cx + r, cy + r), fill=fg)
else: # triangle
d.polygon([(cx, cy - r), (cx - r, cy + r), (cx + r, cy + r)], fill=fg)
return img
def build_split(split, n_per_class, seed):
rng = random.Random(seed)
for cls in CLASSES:
out = Path("shapes") / split / cls
out.mkdir(parents=True, exist_ok=True)
for i in range(n_per_class):
draw_sample(cls, rng).save(out / f"{cls}_{i:04d}.png")
if __name__ == "__main__":
build_split("train", 400, seed=0)
build_split("val", 100, seed=1)
print("wrote 1500 images under ./shapes/")
- Fine-tune
mobilenetv3_small_100(frozen backbone, new 3-class head) on the generated train split — reach ≥ 97% accuracy on the untouched val split - Report single-image latency with warmup: p50 and p95 over ≥ 200 inferences, hardware named — state whether it clears a 30 ms budget
- Print a 3×3 confusion matrix and inspect at least 5 misclassified images — say why they fooled the model
- Ablation: repeat with the backbone unfrozen from the start at lr=1e-3 and report what happens to val accuracy (you should see why frozen-first matters)
- README documents: metrics, the 3 failure modes you found (hint: small thin triangles), and one fix iteration with before/after numbers
Stretch goal: export the model to ONNX (torch.onnx.export),
run it under onnxruntime, and compare p95 latency against PyTorch eager and
torch.compile — three numbers, one table, instant portfolio material.
08 · Interview radarHow This Shows Up in Interviews
Even in 2026, with most applied vision work living in fine-tunes and API calls, interviewers still probe these fundamentals — they're the fastest test of whether you understand models or just call them. Staff-level postings (e.g. XPENG's "strong understanding of model internals and inference") make the deep version explicit.
"Why CNNs over MLPs for images?"
Strong answer Name the three structural priors a convolution bakes in that a dense layer would have to learn from scratch:
- Local receptive fields — nearby pixels relate, so each unit looks at a small neighborhood instead of the whole image
- Weight sharing — the same detector is reused at every position, collapsing billions of parameters to thousands
- Translation equivariance — a shifted input yields a shifted feature map, so a cat in the corner is still a cat
Land it Quantify the gap: the first dense layer on a 1024² RGB image needs roughly 3.2B weights, while a 3×3 conv layer needs about 448.
"What does batch normalization actually do?"
Strong answer Mechanism first: it normalizes each channel's activations to mean 0 and variance 1 over the batch, then applies a learned scale and shift so the network keeps its expressive power. That buys four things at once: activations stay out of saturated regions, the loss landscape gets smoother, you can run higher learning rates, and you pick up a mild regularization effect for free.
Land it The bonus point is inference
behavior: at inference it switches to running statistics — which is why
model.eval() matters, and why training at batch size 1 breaks it.
"Transfer learning — when do you freeze vs fine-tune everything?"
Strong answer Frame it as a 2×2 of dataset size times domain gap, then read off the cells:
- Small data, similar domain — freeze the backbone and train only the new head
- Small data, far domain — freeze the early layers only, because edges transfer but semantics don't
- Large data — unfreeze progressively, keeping a 10× lower learning rate on the pretrained layers
Land it Say why the low rate matters: the pretrained features are the whole reason you're transferring, and a hot learning rate will catastrophically forget them.
"Your model overfits. Walk me through countermeasures, in order."
Strong answer Order the interventions by leverage:
- More or augmented data — the highest-leverage fix, because it attacks the cause instead of the symptom
- Transfer learning — effectively borrowing someone else's data through pretrained features
- Architectural constraints — a smaller head, weight sharing
- Weight decay and dropout — the classic regularizers
- Early stopping — driven by the validation curve
Land it Always name the diagnostic before any cure: the train/val gap is what tells you it's overfitting in the first place.
"Design ChipGuard's 60 FPS inspection service — and when would you NOT use a multimodal LLM API for vision?"
The real test Two rounds in one — system design plus vendor judgment — so answer the architecture first, then the buy-vs-build call.
Strong answer For the design: an edge GPU at the conveyor for batch-size-1 latency, uncertain predictions routed to a human review queue, model versioning with shadow deployment, and drift monitoring on the input distribution. For the judgment: skip the API when latency must be sub-second, when volume makes per-call pricing explode — 5M frames a day at a cent each is roughly $50K a day — or when images can't leave the premises. Go API-first when volume is low, criteria keep evolving, and explanations matter.
Land it Showing the cost crossover math is what separates senior answers from junior ones.
Quick reference — Deep learning and vision
- representation learning
- You stop hand-designing features; the network learns its own from raw input. That is the whole reason deep learning displaced feature engineering.
- ReLU
- The activation function that lets networks go deep: pass positives through, zero out negatives. Simple, and it fixed the vanishing-gradient problem.
- backpropagation
- Working out how much each weight contributed to the error, from the output backwards. It is the chain rule applied at scale.
- Why not a plain network on images
- A modest image through a fully connected layer needs billions of weights. Convolution fixes this with weight sharing — one small filter slid across the whole image.
- pooling
- Shrinks the picture while keeping what matters, so later layers see more of the image at once.
- data augmentation
- Rotate, crop and flip your training images to manufacture variety. The cheapest fix for overfitting in vision.
- model.train() vs model.eval()
- Dropout and batch normalisation behave differently in the two modes. Forgetting to switch is a classic silent bug — the model quietly scores worse and nothing errors.
- padding
- A frame of zeros drawn around the image before the kernel slides, so the output keeps the input's size. The price is a weak fake edge along the border.
- logit
- A raw score from the last layer, one per class, positive or negative. Softmax turns a pair of logits into probabilities, and CrossEntropyLoss wants the logits, not the probabilities.
- epoch, batch, step
- A batch is what one update reads (32 tiles), a step is one update, and an epoch is enough steps to read every training tile once — 38 steps here, 190 in five epochs.
- stack decision
- Count your labels first: none means an API, under ~10,000 means a fine-tuned backbone, plenty plus a tight latency budget means a small custom CNN.
09 · RecapWhat You Can Do Now
- You can explain why convolution beats dense layers for images — with parameter counts, locality, and translation equivariance, not hand-waving
- You can implement forward and backward passes by hand for a 2-layer network and account for every line of the gradient computation
- You can diagnose vanishing gradients from symptoms (early layers frozen, activations saturated) and prescribe the fixes: ReLU, He init, BatchNorm
- You can build, train, and honestly benchmark a PyTorch CNN against a hard latency SLA — warmup, sync, p95, hardware named
- You can fine-tune a timm backbone with a frozen-then-unfrozen schedule and torch.compile, and say why the freeze order matters
- You can choose between custom CNN, fine-tuned backbone, and multimodal API using volume × latency × data-governance math — and defend the choice
- You can pitch a defect-detection project to a VP as scrap-cost arbitrage, and equally pitch against one when an API call wins
- You can walk one tile through a CNN and say what each layer did to the numbers — the shapes, how many are zeroed, and where the multiplies go
- You can tell an epoch from a batch from a step, and work out how many weight updates a training run will make
From this module: from memory, sketch Fig. 4.2's three grids, then compute: a 64×64 input, 5×5 kernel, stride 2, padding 2 — what's the output size? (Use out = ⌊(n + 2p − k)/s⌋ + 1; you should get 32×32.)
Reaching back to Module 03: XGBoost also "follows gradients" — so what's different about what the gradient updates in gradient boosting versus in SGD here?
(Hint: boosting fits a whole new tree to the negative gradient — it descends in function space; SGD nudges a fixed set of weights — parameter space. And recall why tabular data stayed with the trees while pixels came here.)