Basics of Neural Networks

AlexNet holds 61 million weights but does 724 million multiply-adds, and the two live in different layers. Know where each cost lives, and you know what to shrink.

Learn the parts of a neural network, four classic designs, and the metrics that tell you whether one is small, fast and green.

Switch between weights, work and memory, then slide the bit width. Watch which layers carry each cost.

You need multiplication and addition and a little Python. We build the rest from zero.

Based on Lecture 2 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture slides. Every idea is re-taught here in our own words and devices. Previous: Lecture 1. Next: Lecture 3.

Find where AlexNet's cost lives

32 bits

We derive the numbers from AlexNet's layer shapes in the lecture (batch size 1, bias ignored, groups as in the 2012 design). Pooling layers have no weights and no MACs here. Model size is parameters times bit width.

Chapter 0

Why Models Outgrow the Machines That Run Them

See the gap between how fast models grow and how fast memory grows, and learn why we must measure a network before we shrink it

You have a model that works on your laptop. Your boss says: put it on a phone, or on a chip in a doorbell. You copy the file over, and it does not fit.

Three charts, one gap

Lecture slides 2 to 4 show the problem. We count model size in parameters: the numbers a network learns, like dial settings.

Curve on the slideFirst pointLast pointGrowth
Model sizeTransformer (2017), 0.05 billion parametersGrok-3, 2,700 billion54,000 times
Best GPU memoryP100, 16 GBR200, 288 GB18 times

Slide 3 names the two rates. Moore's Law: hardware doubles every 2 years. Deep learning models: 4 times every 2 years. Slide 4 adds that model compression bridges the gap.

How fast does the gap open? Call the number of years from now y. Demand from models multiplies by 4 for every 2 years. Supply from hardware multiplies by 2 for every 2 years. The gap is demand divided by supply.

Say it aloud

Gap of y equals 4 to the y over 2, over 2 to the y over 2. That is 2 to the y over 2.

gap(y)
gap of y how many times demand has outrun supply after y years.
4y/2
4 to the y over 2 demand: 4 multiplied by itself once for each 2-year period.
2y/2
2 to the y over 2 supply: 2 multiplied by itself once for each 2-year period.
In plain words

Count the 2-year periods in y. Raise 4 and 2 to that count, then divide. The gap doubles every period.

With numbers

With y = 8 years there are 4 periods. Demand is 44 = 256 and supply is 24 = 16, so the gap is 256 / 16 = 16. Twelve years give 64.

Widen the gap

Both lines start at 1 today. Warm is demand from models, and blue is hardware supply. On the log scale, equal steps up are equal multiples.

8 years

Illustrative: the two growth rates (4 times and 2 times every 2 years) are the ones printed on lecture slide 3, applied as smooth curves. Real models and chips grow in jumps.

What this lecture does about it

Each compression method attacks one cost. Pruning removes weights. Quantization cuts the bits per weight. Other tricks cut the work, or the memory while running. So first we need a ruler. The lecture has five parts:

  1. The words: neuron, synapse, activation, feature, weight, parameter.
  2. The building blocks: Linear, convolution, grouped and depthwise convolution, pooling, normalization, the Transformer.
  3. Four classic networks built from those blocks: AlexNet, VGG-16, ResNet-50, MobileNetV2.
  4. The efficiency metrics: parameters, model size, peak activations, MACs, FLOPs, FLOPS, OPs, OPS, latency, throughput.
  5. Lab 0, a PyTorch tutorial with exercises. The course site has the details.
  1. Neurons and synapses: one neuron as a weighted sum, and the words for its parts.
  2. The Linear layer: tensor shapes, batch size and the MLP.
  3. The convolution layer: the receptive field, weight sharing and the output size.
  4. Padding, stride and reach: keeping size, shrinking it, and seeing the whole image.
  5. Grouped and depthwise convolution: narrower filters, far fewer weights.
  6. Pooling, normalization, activations, Transformer: the rest of the toolbox.
  7. Four classic networks: AlexNet, VGG-16, ResNet-50, MobileNetV2.
  8. Smaller, faster, greener: latency, throughput and energy.
  9. Memory: parameters, model size and activations.
  10. Work: MACs, FLOPs and OPs.
  11. The field guide: numbers, code and where to go next.
Model size grows 4 times every 2 years and hardware grows 2 times every 2 years. After 6 years, how many times has demand outrun supply?

Chapter 1

A Neuron Is a Weighted Sum, and a Network Is Many of Them

Build one artificial neuron from a vote, then learn which words name the lines and which name the circles

You decide whether to go for a run. Sun pushes you a lot, a friend coming pushes some, and tiredness pushes against. You add the pushes. If the total clears a bar, you go.

Slide 6 puts a nerve cell next to its copy in numbers. A real neuron gets signals through synapses of different strengths. It fires down its axon, the output line, if their sum is large.

In the copy, call each input xi. Each synapse becomes a weight wi, a strength that scales its input. A bias b is a fixed offset added to the sum. An activation function f bends the total into the output yj.

Say it aloud

Y-j equals f of the sum over i of w-i times x-i, plus b.

yj
y-j the output of neuron j, called its activation.
∑i wi xi
the sum over i of w-i x-i multiply each input by its weight and add the products: the vote count.
b
b the bias: it lets the neuron speak when every input is 0.
f
f the activation function. The common one, ReLU, keeps positive sums and turns negative sums into 0.
In plain words

Multiply each input x-i by its weight w-i. Add the products and the bias b. Pass the total through f to get y-j.

With numbers

Made-up inputs 2, −1 and 3, weights 1, 0.5 and −0.5, and b = 1: 2 − 0.5 − 1.5 + 1 = 1, so y-j = 1. With b = −1 the sum is −1, and ReLU gives 0.

Vote with the weights

Lines carry each input to the circle. A thick line is a large weight. Warm means positive and blue means negative. Switch ReLU off to see the raw sum.

1.0
0.5
-0.5
0.0

Illustrative inputs: 2, −1 and 3. The formula is from lecture slide 6.

Stack them: layers, width and the two kinds of numbers

A network wires neurons in layers. Layers between the input and the output are hidden layers, and the number of neurons in one is the width of the model. Slide 7 gives each part two names:

In the pictureOther namesWhat it is
The lines (synapses)weights, parametersNumbers the network learns. They stay fixed while the network runs.
The circles (neurons)features, activationsNumbers that appear while the network runs. They change with every input.

Parameters are what you store on disk. Activations are what you hold in memory while the network runs. They grow at different rates.

Count lines and circles

The network has 5 inputs, two hidden layers of width h, and 2 outputs. Drag h and see how the lines (parameters) and the circles (activations) count up.

4

Toy network made up for this lesson. Parameters include one bias per neuron: 5h + h, then h² + h, then 2h + 2, which sums to h² + 9h + 2.

Double the width from 4 to 8. The circles go from 15 to 23, up 53 percent. The lines go from 54 to 138, up 156 percent, because the weights between two hidden layers multiply width by width.

pythonimport numpy as np

def neuron(x, w, b):                  # x (3,), w (3,), b scalar
    s = (w * x).sum() + b            # weighted sum, one number
    return max(0.0, s)               # ReLU keeps positive sums

x = np.array([2.0, -1.0, 3.0])
print(neuron(x, np.array([1.0, 0.5, -0.5]), 1.0))   # 1.0

The failure: mixing the two bills

Symptom: a teammate says "it has only 15 features, so it is small", and the chip runs out of storage. Measure: at h = 100 the toy network has 207 activations but 10,902 parameters. Fix: ask which number someone means.

A network has two hidden layers. You double the width of both. Which number grows the most?

Chapter 2

The Linear Layer Is One Matrix Multiplication

Turn a whole layer of neurons into a single table of weights, and learn to read its tensor shapes

A teacher has 5 test scores for each of 32 students. She wants 3 grades each, every grade a different weighted mix of the 5 scores. Her table of 3 rows by 5 columns is a Linear layer, or fully-connected layer: every output connects to every input.

The shapes, one by one

Slides 9 and 10 name four tensors, blocks of numbers with a fixed shape:

  1. Input features X has shape (n, ci). Here n is the batch size: how many examples we process together. And ci is the number of input channels: the numbers that describe one example.
  2. Weights W has shape (co, ci). Here co is the number of output channels. Row j holds the weights of output neuron j.
  3. Bias b has shape (co,): one offset per output.
  4. Output features Y has shape (n, co): co numbers for each of the n examples.

Call output number i of one example yi, input number j xj, and the weight that links them wij. For a whole batch, the slide writes the same sum as a matrix product with W transposed: rows and columns swapped.

Say it aloud

Y-i equals the sum over j of w-i-j times x-j, plus b-i. As matrices, Y equals X times W-transpose, plus b.

yi
y-i output number i for one example.
∑j wij xj
the sum over j of w-i-j x-j the weighted sum of all ci inputs, using row i of W.
bi
b-i the bias for output i.
WT
W-transpose W with rows and columns swapped, shape (ci, co). Then (n, ci) times (ci, co) gives (n, co).
In plain words

For output i, walk along row i of W. Multiply each weight w-i-j by its input x-j, add the products, then add b-i. Do it for every output of every example.

With numbers

Made-up numbers: X rows (1, 2, 3) and (0, −1, 1), W rows (1, 0, −1) and (2, 1, 0), b = (0.5, −1). Example 1, output 0: 1 + 0 − 3 + 0.5 = −1.5. All four outputs give Y = ((−1.5, 3), (−0.5, −2)), from 2 × 3 × 2 = 12 multiply-adds.

Fit the boxes

The box widths and heights follow the shapes, shrunk to fit. The shared size ci (teal) must match on both sides of the times sign.

1
768
3,072

The default 768 to 3,072 is one feed-forward layer of a BERT-base style Transformer. The counts ignore bias, as the slides do.

At n = 1 the layer does one multiply-add per weight. At n = 32 the weight count stays the same and the work grows 32 times. Batching reuses weights that are expensive to fetch.

Stack them: the MLP

Slide 11 stacks a second layer on top. Linear layers stacked with an activation between each pair form a multilayer perceptron, or MLP. Without the activation, two Linear layers collapse into one, because the product of two tables is another table.

pythonimport torch, torch.nn as nn

fc = nn.Linear(3, 2)                    # c_i = 3, c_o = 2
print(fc.weight.shape, fc.bias.shape)    # (2, 3)  (2,)  -> W is (c_o, c_i)
X = torch.randn(2, 3)                     # batch n = 2
Y = fc(X)                               # X @ W.T + b
print(Y.shape)                         # (2, 2)
mlp = nn.Sequential(nn.Linear(3, 4), nn.ReLU(), nn.Linear(4, 2))

PyTorch stores W as (co, ci), as the slide does, and multiplies by its transpose inside the layer. So the printed weight shape looks backwards.

The failure: a shape mismatch

Symptom: PyTorch says the matrices cannot be multiplied. Measure: X is (2, 3) and W is (2, 3), so the inner sizes are 3 and 2. Fix: use WT, shape (3, 2). The output is then (2, 2).

A Linear layer maps 2,048 inputs to 1,000 outputs. Ignoring bias, how many weights does it have, and how many multiply-adds does it do for a batch of 1?

Chapter 3

A Convolution Slides One Small Filter Across the Whole Image

See why a picture needs fewer weights than a Linear layer, and follow every number through a 3 by 3 filter

One small pattern, dark on the left and bright on the right, finds a vertical edge anywhere in a photo. A Linear layer cannot reuse it. On a 224 by 224 photo, each output neuron carries 50,176 private weights.

The convolution layer makes two changes. Each output looks only at a small patch, its receptive field. And every output uses the same weights: weight sharing. The shared weights form a small grid, the filter or kernel. The grid of outputs is a feature map.

The shapes

  1. A 1D convolution slides along one direction, such as time in audio. Input (n, ci, wi), output (n, co, wo), weights (co, ci, kw). Here wi is the input width and kw the kernel width.
  2. A 2D convolution slides along two directions, height and width, as in a photo. Input (n, ci, hi, wi), output (n, co, ho, wo), weights (co, ci, kh, kw).
  3. The bias stays (co,). Compare with the Linear layer: the weights gained kh and kw, and the features gained h and w, the spatial dimensions.

Call the input and output channel counts ci and co, and the kernel height and width kh and kw. Call the input and output heights hi and ho. One kernel spans every input channel, and each output channel has its own kernel.

Say it aloud

Weights equals c-o times c-i times k-h times k-w. And h-o equals h-i minus k-h, plus 1.

weights
weights how many numbers the layer learns, bias ignored.
co · ci
c-o times c-i one kernel slice for each pair of an input channel and an output channel.
kh · kw
k-h times k-w the patch each slice covers.
ho = hi − kh + 1
h-o equals h-i minus k-h plus 1 the kernel cannot hang over the edge, so it has this many places to sit. Width works the same way.
In plain words

Multiply the two channel counts and the two kernel sizes to get the weights. The picture size is not in it. For h-o, take the kernel height from the input height and add 1.

With numbers

From 64 to 128 channels with a 3 by 3 kernel: 128 × 64 × 3 × 3 = 73,728 weights. That holds on a 56 by 56 map and on a 224 by 224 map. On the 56 by 56 map, h-o = 56 − 3 + 1 = 54.

Slide the kernel

Left: the input, with the patch under the kernel outlined. Middle: the kernel. Right: the output, filled in up to the position you choose.

5 of 9

Illustrative 5 by 5 image: two columns of 0, then columns of 9. The edge kernel has columns (−1, 0, 1), and the average kernel holds 1/9 in every cell. Stride 1, no padding.

Pick the edge kernel at position 1. Each patch row is 0, 0, 9, so it gives 0 + 0 + 9 = 9, and three rows give 27. At position 3 the patch is all 9s, and each row gives −9 + 0 + 9 = 0. The filter speaks at the edge and is silent elsewhere.

On this 5 by 5 input, a Linear layer to 9 outputs needs 225 weights. The convolution needs 9. The weights do not know the picture size, but the work does. Chapter 10 counts it.

pythonimport torch, torch.nn as nn

conv = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, bias=False)
print(conv.weight.shape)               # (128, 64, 3, 3) = (c_o, c_i, k_h, k_w)
x = torch.randn(1, 64, 56, 56)          # (n, c_i, h_i, w_i)
print(conv(x).shape)                  # (1, 128, 54, 54): 56 - 3 + 1 = 54
print(conv.weight.numel())              # 73728, the same for any picture size

The failure: the map shrinks

Symptom: you stack ten 3 by 3 layers and the feature map is gone. Measure: each layer cuts 2 from the height. Slide 30 shows 4 − 3 + 1 = 2, and a 20 by 20 input is empty after ten layers. Fix: pad the input, as the next chapter shows.

A 3 by 3 Conv2d has 256 input and 256 output channels. You feed it a 13 by 13 map, then a 26 by 26 map. How do its weights change?

Chapter 4

Padding Keeps the Size, Stride Shrinks It, and Depth Widens the View

Control how big each feature map is, and count how much of the image one output number can see

You read a street map through a paper window 3 blocks wide. How many stops fit before the edge? How much street does one note cover? These are the output size and the receptive field.

Padding: keep the size

Each layer loses kh − 1 rows, so a deep stack makes the map vanish. Padding adds a border of extra cells before the kernel slides. Call the border width on each side p.

Say it aloud

H-o equals h-i plus 2p, minus k-h, plus 1.

ho
h-o the output height.
hi
h-i the input height.
2p
two p p rows of border on top and p rows below.
kh
k-h the kernel height.
In plain words

Add the 2p border rows to h-i. Take away k-h. Add 1 for the first stop.

With numbers

Slide 31: h-i = 5, k-h = 3, p = 1. Then h-o = 5 + 2 − 3 + 1 = 5, so the map keeps its size. For an odd kernel k, p = (k − 1) / 2 always does this.

Slide 31 lists four ways to fill the border:

  1. Zero padding fills with 0. It is the PyTorch default.
  2. Reflection padding mirrors the cells next to the edge.
  3. Replication padding copies the edge cell outward.
  4. Constant padding fills with a number you choose.

Stride: shrink on purpose

The stride s is how many cells the kernel jumps between stops. Stride 2 skips every other stop and about halves the map. The last jump may not fit, so the count rounds down.

Say it aloud

H-o equals the floor of h-i plus 2p minus k-h, all over s, plus 1.

ho
h-o the output height: a whole number of stops.
⌊ … ⌋
the floor of round down to a whole number, because a part stop does not count.
s
s the stride: cells jumped between stops.
In plain words

Add the border, take away the kernel, divide by s and round down. That counts the jumps. Add 1 for the first stop at the edge.

With numbers

AlexNet's first layer (slide 41): h-i = 224, p = 2, k-h = 11, s = 4. 224 + 4 − 11 = 217, and 217 / 4 = 54.25 rounds down to 54. Add 1: h-o = 55.

Reach: how much can one number see?

Slide 32: each extra layer adds k − 1 cells to the reach, so three 3 by 3 layers see 7. A large image would need too many layers, so the slide downsamples inside the network. After a stride 2 layer each cell stands for 2 input cells, so later kernels reach twice as far (slide 33).

Stack the layers

The top row is the input. Each row below is one layer's output. Change the kernel, padding and stride, and watch the row sizes and the teal reach.

3
3
1
1

Toy: one row of 24 input cells. The height and width of a photo follow the same formulas.

Set k = 3, p = 1 and s = 1: the rows stay at 24 and the reach grows 2 per layer. Set s = 2: the rows halve, and three layers see 15 cells.

pythondef trace(h, k, p, s, L):
    jump, rf, sizes = 1, 1, [h]
    for _ in range(L):
        h = (h + 2*p - k) // s + 1   # output size
        rf += (k - 1) * jump           # reach grows by (k-1) input steps
        jump *= s                    # each cell now spans s times more input
        sizes.append(h)
    return sizes, rf

print(trace(24, 3, 1, 2, 3))   # ([24, 12, 6, 3], 15)

The failure: a view too small, or a map that vanishes

Symptom: the network misses large objects. Measure: 5 layers of 3 by 3 at stride 1 see only 11 cells of a 224-pixel image. Fix: add stride or pooling. If PyTorch reports an output size of 0, the kernel is larger than the padded input.

A 13 by 13 map goes through a 3 by 3 max pool with stride 2 and no padding. What is the output size?

Chapter 5

Grouped and Depthwise Convolution Split the Channels to Save Weights

Cut the link between far-apart channels and see the weight count fall by 2, 4, or the whole channel count

A standard convolution links every input channel to every output channel: 128 by 128 links for 128 channels. Split the channels into 4 teams that link only inside the team, and the links drop to a quarter. The price: teams do not hear each other in this layer.

Grouped convolution: narrower filters

A grouped convolution splits the input and output channels into g equal groups. Group 1 reads only the first ci/g input channels and writes only the first co/g output channels. Slide 34 gives the weights as g copies of that narrower filter.

Say it aloud

Weights equals g times c-o over g, times c-i over g, times k-h k-w. That is c-o c-i k-h k-w, over g.

weights
weights the parameter count of the layer, bias ignored.
g
g the number of groups. With g = 1 you get a standard convolution.
(co/g) · (ci/g)
c-o over g, times c-i over g the output and input channels inside one group.
kh kw
k-h k-w the kernel height times its width.
In plain words

Count the weights of one narrow group, then multiply by the g groups. The result is the standard count divided by g. The work falls by g too.

With numbers

AlexNet's conv2 (slide 61): 96 to 256 channels, 5 by 5, g = 2. Standard: 256 × 96 × 25 = 614,400 weights. Grouped: 614,400 / 2 = 307,200.

Depthwise and pointwise

Set g = ci = co and each group has one channel in and one out. That is a depthwise convolution (slide 35), weight shape (c, kh, kw). It never mixes channels. A pointwise convolution, with a 1 by 1 kernel, mixes channels and does nothing spatial. The pair is the core of MobileNetV2 (Chapter 7).

  1. Standard: 128 · 128 · 9 = 147,456 weights.
  2. Depthwise: 128 · 9 = 1,152 weights.
  3. Pointwise 1 by 1: 128 · 128 = 16,384 weights.
  4. Depthwise plus pointwise: 1,152 + 16,384 = 17,536 weights, which is 8.4 times fewer than standard.

Group the channels

Pick the groups. Lines show which channels connect. Then turn on the 1 by 1 pointwise layer that mixes the channels again.

128

3 by 3 kernel, 56 by 56 output map, batch 1, bias ignored. The 8 drawn channels sketch the real count.

Pick Depthwise at 128 channels. The weights fall to 1,152 and the work to 3,612,672 multiply-adds, both 128 times below standard. Add the pointwise layer: 17,536 weights and 54,992,896 multiply-adds, and every channel hears every other again.

pythonimport torch.nn as nn

std  = nn.Conv2d(128, 128, 3, padding=1, bias=False)              # 147,456 weights
grp  = nn.Conv2d(128, 128, 3, padding=1, groups=4, bias=False)   # 36,864; weight (128, 32, 3, 3)
dw   = nn.Conv2d(128, 128, 3, padding=1, groups=128, bias=False) # 1,152; weight (128, 1, 3, 3)
pw   = nn.Conv2d(128, 128, 1, bias=False)                         # 16,384; weight (128, 128, 1, 1)

PyTorch stores a grouped weight as (co, ci/g, kh, kw): the same count as g narrow filters, in one tensor.

The failure: channels that never talk

Symptom: you swap every convolution for a depthwise one and accuracy collapses. Measure: each output now sees 1 of 128 input channels. Fix: follow each depthwise layer with a pointwise one. Also, depthwise layers do little work per byte moved, so fewer MACs need not mean less time (Chapter 8).

A 3 by 3 convolution has 64 input and 64 output channels. You set groups to 64. How many weights does it have, ignoring bias?

Chapter 6

Pooling, Normalization, Activations and the Transformer Fill the Toolbox

Meet the last four building blocks, and see which of them hold weights

Pooling: shrink without learning

A pooling layer shrinks a feature map. Each output takes a small window, as in a convolution, but with no weights and one channel at a time. The stride usually equals the window, so windows do not overlap.

Slide 36 pools a 4 by 4 map in 2 by 2 windows. Its rows are 5 0 1 7, 2 1 3 5, 0 2 3 1 and 2 8 1 3. Max pooling keeps each largest number: 5, 7, 8, 3. Average pooling keeps each mean: 2, 4, 3, 2.

Normalization: keep the numbers tame

Slide 37: normalizing the features makes optimization faster. Take a set S of numbers with mean μ and standard deviation σ. The layer rescales them, then learns a scale γ and a shift β per channel to win back a range it needs.

Say it aloud

X-hat equals x minus mu, over sigma. Then y equals gamma times x-hat, plus beta.

x
x one number in the set S.
μ
mu the mean of the set.
σ
sigma the standard deviation of the set, plus a tiny ε so it is never 0.
x̂
x-hat x after normalizing. The set now has mean 0 and spread 1.
γ
gamma a learned scale, one per channel.
β
beta a learned shift, one per channel.
y
y the output of the layer.
In plain words

Take the mean mu from each number x. Divide by sigma to get x-hat. Multiply by gamma and add beta to get y.

With numbers

Made-up set 2, 4, 6, 8: mu = 5 and sigma = √5 = 2.236. So x-hat = −1.342, −0.447, 0.447, 1.342. With gamma = 2 and beta = 1, y = −1.68, 0.11, 1.89, 3.68.

Batch Norm, Layer Norm, Instance Norm and Group Norm differ only in the set S.

Pick the set

Each cell is one channel of one example. Your pick is teal. Cells that share its mean and spread have a purple outline.

2
2

Toy tensor: 4 examples, 6 channels, and 2 groups of 3 for Group Norm. The sets follow lecture slide 37.

Batch Norm shares across the batch, so one example's output depends on the others. The other three use one example.

Activation functions: add the bend

Without a bend between them, stacked layers collapse into one linear map. Slide 38 shows six activation functions that add the bend:

FunctionFormulaWhat it does
Sigmoid1 / (1 + e−x)Squeezes any number into 0 to 1.
ReLUmax(0, x)Turns negatives into 0.
ReLU6min(max(0, x), 6)ReLU with a cap at 6.
Leaky ReLUmax(αx, x)Lets a small slope through for negatives.
Swishx / (1 + e−x)A smooth ReLU.
Hard Swish0 if x ≤ −3; x if x ≥ 3; else x(x + 3) / 6Swish from adds and multiplies, with no exponential.

Bend the numbers

Pick a function and slide the input. Watch where it is flat, straight or bent.

4.5

Formulas from lecture slide 38. Leaky ReLU uses an illustrative slope of 0.1. The slide also lists Tanh, GELU, ELU and Mish.

Set ReLU6 and slide x to 7: the output stays at 6, a range that fits in few bits.

The Transformer

Slide 39 shows the Transformer (Vaswani et al., NeurIPS 2017). Three Linear layers make queries, keys and values from n tokens. Queries times keys give an n by n score table, so the work grows with n squared. The Transformer lesson goes deeper.

pythonimport torch, torch.nn as nn

pool = nn.MaxPool2d(2)                         # k = s = 2, no weights
norm = nn.BatchNorm2d(6)                      # gamma, beta: 6 + 6 weights
act  = nn.ReLU6()
x = torch.randn(4, 6, 8, 8)                   # (n, c, h, w)
print(act(norm(pool(x))).shape)               # (4, 6, 4, 4)

The failure: Batch Norm at batch size 1

Symptom: outputs shift at test time when you feed one image. Measure: at batch 1 the batch mean is that image's own mean. Fix: call model.eval() so the layer uses stored averages, or use Layer or Group Norm.

Which normalization shares one mean and spread across all the examples in the batch, separately for each channel?

Chapter 7

Four Classic Networks Show How Blocks Become Architectures

Walk AlexNet, VGG-16, ResNet-50 and MobileNetV2 stage by stage, and watch the feature map trade height for depth

The lecture reads the plans of four image classifiers, in the order they appeared. Each takes a photo of 3 channels at 224 by 224 and returns 1,000 scores, one per ImageNet class. All follow one pattern: the map shrinks in height and width and grows in channels.

Early layers see a big map and look for edges and colours. Late layers see a 7 by 7 map with thousands of channels. Channels times height times width is the activation count, and it falls with depth. So early layers dominate memory and late layers dominate weights.

NetworkPaperDesign (slides 41 to 44)
AlexNetKrizhevsky et al., NeurIPS 20125 conv, 3 max pool and 3 Linear layers. An 11 by 11 kernel at stride 4 turns 224 into 55. Groups of 2 in conv 2, 4 and 5. The map ends at 256 × 6 × 6 = 9,216 numbers.
VGG-16Simonyan et al., ICLR 2015Only 3 by 3 convs with padding 1, each with BatchNorm and ReLU. A 2 by 2 max pool halves the map after each group. 13 conv layers in groups of 2, 2, 3, 3, 3 (64 to 512 channels) plus 3 Linear: 16.
ResNet-50He et al., CVPR 2016Bottleneck blocks with a residual connection. Stages of 3, 4, 6 and 3 blocks at 256, 512, 1,024 and 2,048 channels.
MobileNetV2Sandler et al., CVPR 2018Inverted bottleneck blocks: expand the channels 6 times, filter with a 3 by 3 depthwise conv, project back.

A residual connection adds a block's input x to its output, so the block learns only a correction. The ResNet bottleneck goes 1 by 1 down to N/4 channels, 3 by 3, then 1 by 1 back to N. MobileNetV2's inverted bottleneck runs 1 by 1 up to 6N, 3 by 3 depthwise, then 1 by 1 back to N.

Walk the stages

Tall and thin means a big picture with few channels. Short and wide means a small picture with many channels. The chosen stage has an outline.

2

Stages from lecture slides 41 to 44. Repeated blocks form one stage, shown at its output shape. Activations are channels times height times width.

ResNet-50, stage 2: the 7 by 7 stem at stride 2 gives 64 × 112 × 112 = 802,816 numbers. The last stage gives 2,048 × 7 × 7 = 100,352. The channels grew 32 times and the area fell 256 times, so the count fell 8 times.

Open up a block

Bars show the channel count after each step inside one block. The curved line is the shortcut that adds the input back at the end.

24
56 by 56

Weights ignore bias and BatchNorm. The block shapes and the factor 6 are from slides 43 and 44.

The inverted block at N = 24 on a 56 by 56 map holds 8,208 weights. Its middle tensor is 144 × 56 × 56 = 451,584 numbers, 6 times the 75,264 at its ends. Chapter 9 shows what that does on a small chip.

pythonimport torch, torch.nn as nn, torchvision

net = torchvision.models.resnet50()
x = torch.randn(1, 3, 224, 224)
for name, m in [("stem", nn.Sequential(net.conv1, net.bn1, net.relu)), ("pool", net.maxpool),
                 ("l1", net.layer1), ("l2", net.layer2), ("l3", net.layer3), ("l4", net.layer4)]:
    x = m(x); print(name, tuple(x.shape))   # (1,64,112,112) ... (1,2048,7,7)

The failure: depth that does not train

Symptom: a plain stack of 50 conv layers trains worse than a 20-layer stack. Measure: the learning signal shrinks across many layers, so early layers barely change. Fix: add the shortcut. A block that learns nothing still passes x through, so extra depth does no harm.

What does the inverted bottleneck in MobileNetV2 do first, compared with the ResNet bottleneck?

Chapter 8

Smaller, Faster, Greener: Latency, Throughput and Energy

Learn the three goals of efficiency, and see why a layer's time depends on its work and on the bytes it moves

A pizza shop can make 200 pizzas an hour and still keep you waiting 40 minutes. Slides 46 and 47 draw the goals of efficiency as a triangle: smaller, faster and greener.

FamilyMetricsFeeds
Memory-related#parameters, model size, total and peak #activationsSmaller (storage), and part of faster and greener
Computation-relatedMAC, FLOP, FLOPS, OP, OPSFaster and greener
The outcomesLatency, throughput, energyWhat the user feels or pays

Latency and throughput

MetricMeaningSlide example
LatencyThe delay for one task.Street segmentation on an Nvidia Jetson AGX Orin (TensorRT, fp16, batch 1). SegFormer: 638 ms at 82.4 mIoU. EfficientViT: 46 ms at 82.7 mIoU. mIoU scores how well the regions match the truth (slide 48).
ThroughputHow much data the system handles per second.6.1 against 77.4 videos per second (slide 49).

Slide 50 shows that the two differ. Design 1 answers in 50 ms and does 20 images per second. Design 2 answers in 100 ms and does 40.

Batch the images

The bar is the time one batch takes. Every image in it waits for the whole bar. The dots show how many images finish in that time.

1

Illustrative cost model: 20 ms of set-up plus 10 ms per image. Latency is the batch time, and throughput is images over that time.

At batch 1: 30 ms and 33 images per second. At batch 16: 180 ms and 89 per second, 2.7 times the throughput for 6 times the latency.

What sets the latency of one layer

Slide 51: loading, computing and storing overlap. Call the arithmetic time Tcomp: operations divided by operations per second. Call the data time Tmem: bytes of weights and activations divided by the memory bandwidth.

Say it aloud

Latency is about the max of T-comp and T-mem.

Latency
latency the time the layer takes.
max
the max of the larger of the two, because the overlapped jobs finish when the slower one does.
Tcomp
T-comp operations in the layer divided by the operations per second of the chip.
Tmem
T-mem bytes of weights, input and output divided by the memory bandwidth in bytes per second.
In plain words

Work out T-comp and T-mem. The layer takes about as long as the larger one. If T-mem wins, the layer is memory-bound. If T-comp wins, it is compute-bound.

With numbers

Take the device's Linear layer, 4,096 to 4,096 at 32 bits, on an illustrative chip with 1 TFLOPS and 25 GB/s. T-comp = 33.6 million operations / 1012 per second = 33.6 µs. T-mem = 67.1 MB / 25 GB/s = 2.69 ms. So latency is about 2.69 ms.

Energy: moving data costs far more than computing

Slide 52 (Horowitz, ISSCC 2014) gives the energy of 32-bit operations in a 45 nm chip at 0.9 V. A pJ is a trillionth of a joule.

OperationEnergy
Integer add0.1 pJ
Float add0.9 pJ
Register file read1 pJ
Integer multiply3.1 pJ
Float multiply3.7 pJ
SRAM cache read5 pJ
DRAM read640 pJ, about 200 times an integer multiply

Find the bottleneck

Warm is time computing. Yellow is time moving bytes. The taller bar is the latency. Red marks the limit when memory is the limit.

1 TFLOPS
25 GB/s

Illustrative chips. Batch 1, 32 bits, 56 by 56 maps. Energy: every byte from DRAM at 640 pJ per 32 bits, and every MAC 4.6 pJ, a float add plus a multiply (slide 52). Real chips cache, so true memory energy is lower.

Reading the Linear layer from DRAM costs 10.7 mJ, 140 times its 77 µJ of arithmetic. The depthwise layer, with only 3.6 million MACs, is memory-bound too.

pythondef layer_time(macs, weight_elems, act_elems, flops_per_s, bytes_per_s, bytes_per_elem=4):
    t_comp = 2 * macs / flops_per_s                        # one MAC = 2 FLOP
    t_mem  = (weight_elems + act_elems) * bytes_per_elem / bytes_per_s
    return max(t_comp, t_mem), ("memory" if t_mem > t_comp else "compute")

print(layer_time(16_777_216, 16_777_216, 8_192, 1e12, 25e9))  # about (0.00269, 'memory')

The failure: optimising the wrong corner

Symptom: you halve a model's operations and the phone runs it no faster. Measure: Tmem is the larger term. Fix: measure on the target device, then cut the larger term, for example with fewer or smaller weights.

A layer has Tcomp = 30 microseconds and Tmem = 2,700 microseconds. You make the chip's arithmetic twice as fast. What happens to the layer's latency?

Chapter 9

Memory Has Two Bills: Parameters on Disk, Activations While Running

Count a network's weights, turn them into megabytes, and see why activations break small chips

Moving house needs room for what you own and floor space to unpack. A network has both bills: parameters and model size, then activations.

Count the parameters

Slide 56: the parameter count is the number of elements in all weight tensors. Per layer type, bias ignored:

Layer#ParametersChapter
Linearco · ci2
Convolutionco · ci · kh · kw3
Grouped convolutionco · ci · kh · kw / g5
Depthwise convolutionco · kh · kw5

Slide 61 sums AlexNet to 60,954,656, about 61M (Chapter 10 lists each layer). The slide prints 24,848 for conv1, a typo: 96 × 3 × 11 × 11 = 34,848.

From parameters to megabytes

Model size is the storage the weights need: the parameter count times the bit width, the bits per weight.

Say it aloud

Model size equals the number of parameters times the bit width.

Model size
model size storage for all the weights, in bits. Divide by 8 for bytes.
#Parameters
number of parameters how many weights the network has.
bit width
bit width bits per weight: 32 for a standard float, 8 for a small integer.
In plain words

Multiply the number of weights by the bits each one takes. Divide by 8 to get bytes.

With numbers

AlexNet at 32 bits: 60,954,656 × 4 bytes = 243.8 MB, about 244 MB. At 8 bits: 61 MB. Slide 63 prints 224 MB, a digit swap.

Count the activations

A layer's activation count is its output channels times height times width. AlexNet's sum to 932,264 (slide 70). The network frees a layer's input once the layer finishes. So the memory you need is the peak activation, the largest input plus output: 150,528 + 290,400 = 440,928 at conv1.

Fit the peak into the chip

Bars: one layer's input plus output. Dashed line: a microcontroller's 256 kB.

8 bits

Counts from lecture slide 70, batch 1. The 256 kB limit is from slide 67, and a real chip also needs room for code. 1 kB = 1,000 bytes.

At 8 bits the peak is 441 kB, 1.7 times the 256 kB limit. At 4 bits, 220 kB fits.

The surprise: activations, not parameters, are the bottleneck

Slide 65 compares 8-bit models at about 70 percent ImageNet top-1. MobileNetV2-0.75 has 4.6 times fewer parameters than ResNet-18, but a 1.8 times larger peak activation. In 32-bit training (slide 68), MobileNetV2-1.4 cuts ResNet-50's 102 MB of parameters 4.3 times, but its 707 MB of activations only 1.1 times.

Weigh the weights

Model size on a log scale. A model fits a device when the bar stops before its tick.

16 bits

Parameter counts from lecture slides 2 and 61. Ticks: 256 kB microcontroller, illustrative 8 GB phone, and slide 3's A100, B200 and R200. Weights only.

GPT-3 at 16 bits: 175 billion × 2 bytes = 350 GB, or 5 A100 cards of 80 GB. At 4 bits, 87.5 GB fits on 2.

pythonimport torch, torch.nn as nn

def profile(model, x, bits=8):
    params = sum(p.numel() for p in model.parameters())     # #Parameters
    size_mb = params * bits / 8 / 1e6                        # model size
    acts = []
    hooks = [m.register_forward_hook(lambda m, i, o: acts.append((i[0].numel(), o.numel())))
             for m in model.modules() if len(list(m.children())) == 0]
    model.eval()
    with torch.no_grad(): model(x)
    for h in hooks: h.remove()
    peak = max(a + b for a, b in acts)                         # peak = largest input + output
    return params, size_mb, peak

The failure: shrinking the wrong list

Symptom: you quantize a vision model's weights to 8 bits for a 256 kB chip, and it still does not run. Measure: the peak activation, 1,372 kB in MobileNetV2's worst early block (slide 67). Fix: a smaller input, narrower early layers, or patch-by-patch processing.

A network has 20 million parameters stored as 8-bit numbers. What is its model size?

Chapter 10

MACs, FLOPs and OPs Count the Work a Network Does

Count the multiply-adds in every layer, convert them to FLOPs, and see why weights and work peak in different places

A baker's cost is how often she uses each recipe line, not the size of the book. Weights are the book, and work is the repeats.

A multiply-accumulate, or MAC, multiplies two numbers and adds the product to a running total. Slide 72: a matrix-matrix product (GEMM) of m by k and k by n takes k MACs for each of its m × n outputs.

LayerMACs (batch 1)Read it as
Linearco · cico outputs, ci MACs each
Convolutionci · kh · kw · ho · wo · coho wo co outputs, ci kh kw MACs each
Grouped convolution(ci/g) · kh · kw · ho · wo · coeach output reads only its group's channels
Depthwise convolutionkh · kw · ho · wo · coeach output reads one channel

For a convolution, count the outputs and the MACs each one needs. The outputs are ho × wo × co. Each sums over ci input channels and a kh by kw patch.

Say it aloud

MACs equals c-i times k-h times k-w, times h-o times w-o times c-o.

MACs
MACs multiply-adds for one image, bias ignored.
ci · kh · kw
c-i times k-h times k-w the MACs for one output: one per input channel per patch cell.
ho · wo · co
h-o times w-o times c-o the number of outputs.
In plain words

Multiply the MACs per output by the number of outputs. Against the weight count, the only new factor is h-o times w-o: how often the layer reuses each weight.

With numbers

AlexNet's conv1 (slide 77) needs 3 × 11 × 11 = 363 MACs per output. It has 55 × 55 × 96 = 290,400 outputs, so 105,415,200 MACs. With 34,848 weights, the layer uses each weight 3,025 times.

Slides 61 and 77 count AlexNet layer by layer. The conv layers hold 3.8 percent of the weights and do 91.9 percent of the MACs:

LayerParametersMACs
Conv1, 11 by 11, 3 to 9634,848105,415,200
Conv2, 5 by 5, 96 to 256, g = 2307,200223,948,800
Conv3, 3 by 3, 256 to 384884,736149,520,384
Conv4, 3 by 3, 384 to 384, g = 2663,552112,140,288
Conv5, 3 by 3, 384 to 256, g = 2442,36874,760,192
Linear, 9,216 to 4,09637,748,73637,748,736
Linear, 4,096 to 4,09616,777,21616,777,216
Linear, 4,096 to 1,0004,096,0004,096,000
Total60,954,656 (61M)724,406,816 (724M)

Count the work

Pick a layer. The blue bar is weights, the warm bar is MACs. Both share one scale. Drag the map size and see only the warm bar move.

128
56 by 56

Batch 1, bias ignored, 3 by 3 kernels. A Linear layer has no map at batch 1, so its MACs equal its weights.

Conv 3 by 3, 128 channels, 56 by 56 map: 147,456 weights and 462,422,016 MACs. Each weight works 3,136 times. At a 1 by 1 map the two counts meet.

From MACs to FLOPs, FLOPS, OPs and OPS

Slide 79: a multiply is one floating point operation, or FLOP, and an add is another. So one MAC is 2 FLOPs, and AlexNet's 724M MACs are about 1.4 GFLOPs. Mind the capital S:

WordMeaningExample
FLOPsA count of floating point operations: a fact about a model.AlexNet: 1.4 GFLOPs
FLOPSFLOPs per second: a fact about a chip (slide 79).1 TFLOPS
OPsOperations of any type, so integer networks count too (slide 80).AlexNet: 1.4 GOPs
OPSOperations per second.4 TOPS

On a 1 TOPS chip, AlexNet needs at least 1.4 ms of arithmetic. That is only Tcomp from Chapter 8. The memory term may be larger.

pythondef conv_cost(ci, co, kh, kw, ho, wo, g=1):
    params = co * (ci // g) * kh * kw
    macs   = (ci // g) * kh * kw * ho * wo * co       # outputs x MACs each
    return params, macs, 2 * macs                       # FLOPs = 2 x MACs

print(conv_cost(3, 96, 11, 11, 55, 55))      # (34848, 105415200, 210830400)
print(conv_cost(128, 128, 3, 3, 56, 56, g=128)) # (1152, 3612672, 7225344) depthwise

The failure: comparing FLOPs with FLOPS

Symptom: a 50 TFLOPS chip, a 4 GFLOPs model, and a promise of 12,500 runs per second. Measure: memory time and a peak the chip rarely reaches make it far fewer. Counting a MAC as 1 operation, not 2, adds a factor of 2. Fix: write units and measure on the device.

A 3 by 3 conv layer maps 64 channels to 64 channels and outputs a 28 by 28 map. How many MACs does it do for one image?

Chapter 11

The Field Guide: The Numbers, the Terms and the Code to Keep

Gather everything into one page you can return to, and see the question the rest of the course answers

The lecture closes where it began. Slide 81 repeats the first chart: today's AI is too big. Slide 82 plots image classifiers by accuracy against billions of MACs, with bubble size for parameters. Accuracy has been bought with work and weights.

Slide 83 asks the question the next lectures answer: how should we make deep learning more efficient? Lab 0, a PyTorch tutorial, follows this lecture.

The numbers that matter

WhatNumberWhy it matters
Model growth against GPU memory0.05B to 2,700B (54,000 times); 16 GB to 288 GB (18 times)The gap that compression must bridge (Ch 0)
Growth rates on the slidemodels 4 times per 2 years, Moore 2 timesThe gap doubles every 2 years (Ch 0)
Conv weights, 128 to 128, 3 by 3147,456, any map sizeWeights do not know the picture size (Ch 3)
AlexNet conv1 output(224 + 4 − 11) / 4 + 1 = 55Padding and stride formula (Ch 4)
Depthwise plus pointwise, 128 channels17,536 against 147,456 weights, 8.4 times fewerThe MobileNet trick (Ch 5, 7)
Inverted block, N = 24 at 56 by 568,208 weights, 451,584-number middleFew weights, big activations (Ch 7, 9)
SegFormer against EfficientViT638 ms against 46 ms, 82.4 against 82.7 mIoULatency can improve with accuracy (Ch 8)
DRAM read against float multiply640 pJ against 3.7 pJMoving data costs more than computing (Ch 8)
AlexNet parameters and model size60,954,656; 244 MB at 32 bits, 61 MB at 8Size is parameters times bit width (Ch 9)
AlexNet peak activations150,528 + 290,400 = 440,928The peak decides what fits in SRAM (Ch 9)
MobileNetV2 peak against MCU limit1,372 kB against 256 kB; 4.6 times fewer parameters than ResNet-18 but a 1.8 times larger peakActivations are the bottleneck (Ch 9)
AlexNet MACs and FLOPs724,406,816 MACs, about 1.4 GFLOPsOne MAC is two FLOPs (Ch 10)
Where AlexNet's cost livesconv: 3.8% of weights, 91.9% of MACs; Linear: 96.2% of weights, 8.1% of MACsWeights and work peak in different layers (Ch 10)

The terms in one place

TermPlain meaningWhere
Weight, parameter, synapseA number the network learns. Stored on disk.1
Activation, feature, neuron outputA number computed while the network runs. Held in memory.1
WidthThe number of neurons or channels in a hidden layer.1
Batch size nHow many examples go through together.2
Receptive fieldThe part of the input one output depends on.3, 4
Weight sharingOne kernel reused at every position.3
Padding, strideBorder added; jump between kernel stops.4
Grouped, depthwise, pointwiseConvolutions with split channels; one channel each; 1 by 1.5
Residual connectionA shortcut that adds the input to the output.7
Latency, throughputTime for one task; tasks per second.8
Memory-bound, compute-boundLimited by bytes moved; limited by operations.8
Model size, peak activationWeights times bit width; the largest input plus output.9
MAC, FLOP, FLOPS, OP, OPSMultiply-add; one multiply or add; FLOPs per second; any operation; per second.10

The checklist before you shrink a model

  1. Name the target: smaller, faster or greener. Name the device.
  2. Count parameters per layer and sum them. Convert to megabytes at your bit width.
  3. Count the activations of every layer and find the peak pair of input plus output.
  4. Count the MACs per layer. Check whether a source means MACs or FLOPs.
  5. For the slowest layers, compare Tcomp with Tmem on the real chip.
  6. Only then pick a method: fewer weights, fewer bits, cheaper layers, or smaller activations.

The core as code

pythondef out_size(h, k, p, s):                       # Ch 4: map size after a conv or pool
    return (h + 2*p - k) // s + 1

def conv_cost(ci, co, k, ho, g=1):                # Ch 5, 9, 10: weights, MACs, output activations
    w = co * (ci // g) * k * k
    return w, w * ho * ho, co * ho * ho

def model_mb(params, bits):                     # Ch 9: storage
    return params * bits / 8 / 1e6

def latency(macs, bytes_moved, flops, bw):      # Ch 8: max of compute and memory time
    return max(2 * macs / flops, bytes_moved / bw)

print(out_size(224, 11, 2, 4))                # 55
print(model_mb(60_954_656, 8))               # 60.95 MB

Where it sits in the field

Every efficiency method uses this vocabulary. Pruning, in Lecture 3, removes weights. Quantization, in Lecture 5, lowers the bit width in the model-size formula. Architecture search, in Lecture 7, searches over the block shapes of Chapter 7. And MCUNet takes the peak-activation lesson of Chapter 9 all the way to a chip with 256 kB.

Keep going

Back to the case for efficiency: Lecture 1. Forward: Lecture 3, Pruning I. Deeper on single blocks: Convolutional Networks, Normalization, Activation Functions and the Transformer. The reading list (slide 86) cites the Batch Norm paper (Ioffe and Szegedy, ICML 2015) and the Group Norm paper (Wu and He, ECCV 2018). It also cites AlexNet, VGG, ResNet, MobileNetV2 and a survey by Deng et al. (IEEE 2020).

The takeaway. Parameters, activations, MACs, bytes and joules are five different bills. Each layer type pays them in different amounts. Measure all five before you shrink anything.

Credit and source: this lesson re-teaches Lecture 2 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026) by Song Han and the MIT HAN Lab. The course page has the slides and the lab. All explanations, devices and worked numbers here are our own. Where a slide had a typo (the conv1 count and the 244 MB size), we corrected it and said so. Slide 65's peak activation bar for MobileNetV2-0.75 is 1.8 times taller than ResNet-18's, and we report it that way.

You must run a vision network on a chip with 256 kB of working memory. Its weights are already small. Which measurement do you take first?

Now press Teach and explain, from memory, why AlexNet's weights and its work sit in different layers. Then go back to the bars at the top and move the bit width once more.

MIT 6.5940 Lecture 2: Basics of Neural Networks
The course site and slides · Back to Lecture 1 · On to Lecture 3 · Back to Gleams