Level 5 Independent Engineering Research · Term 3: Advanced Computing and System Design
How computation is bounded by complexity, hardware, memory and energy: from asymptotics and pipelines to caches, silicon manufacturing and embedded machine learning, and how engineers co-design algorithms and hardware and compare them fairly.
In this file: 28 lessons across weeks 19–27, with 147 practice questions (questions only, no answers).
Conduct an independent, reproducible engineering investigation using advanced mathematics, estimation and computing, and communicate it to the standard of an early research publication. Levels describe what you can do, not your age. About About 3–4 hours a week: 1.5 hours of study, 1.5–2 hours of computation or research work and 30 minutes of writing. Research weeks are self-paced within that budget..
Week 19: Computational complexity
This week you will
- Analyse time and space complexity, including best, worst and average cases.
- Solve divide-and-conquer recurrences by unrolling them.
- Explain tractable versus intractable problems and why heuristics and approximations are used.
How fast does the work grow?
Your code sorts 1,000 readings in a millisecond. Will a million readings take two seconds, or seventeen minutes?
Why it matters
A benchmark on today's input tells you almost nothing about tomorrow's. Asymptotic analysis does: it says how the work grows, which is what decides whether a perception pipeline, a planner or a database survives contact with real data. It is the first question a reviewer asks about any algorithm.
Goals
- Count the basic operations of a loop nest and express the count in Big-O, Big-Ω and Big-Θ notation.
- Distinguish best, worst and average cases, and time from space complexity.
- Predict how run time scales when the input grows or the machine gets faster.
Predict
Algorithm A does 100·n operations; algorithm B does n². For which inputs is A faster?
- Always: 100·n is linear
- Never: 100 is a big constant
- Only when n > 100
- Only when n < 100
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Set n = 10, then 30, then 60. Watch which bars turn orange (over a second) and red (over a year). Then make the machine 1,000× faster and see how much bigger an input each algorithm can now handle in one second.
What the interactive shows, in words
The racer lists seven growth rates. At n = 20 on a billion-operations-per-second machine: log n and n are nanoseconds, n² is 400 ns, n³ is 8 µs, 2ⁿ is about 1 ms, n! is about 77 years. A 1,000× faster machine lets n² handle 32× bigger inputs but 2ⁿ only about 10 more items.
Understand
Count operations, not seconds
Pick a basic operation (a comparison, a multiply, a memory read) and count how many times it runs as a function of input size n. Seconds depend on the machine; the count depends only on the algorithm. Two nested loops over n items give n² executions of the inner line; a loop that halves i each pass gives ⌊log₂ n⌋.
O, Ω and Θ
f(n) = O(g(n)) means f grows no faster than g: there are constants c and n₀ with f(n) ≤ c·g(n) for all n ≥ n₀. Ω is the matching lower bound, and Θ means both. So 3n² + 50n + 7 is Θ(n²): the leading term dominates and constants are dropped. Big-O is an upper bound, so n is also O(n²), but saying Θ(n) is more informative.
Best, worst, average
Linear search finds the item first time in the best case (Θ(1)), last in the worst (Θ(n)), and about halfway on average if every position is equally likely. Quicksort is Θ(n log n) on average but Θ(n²) in the worst case. Engineers designing real-time systems usually care about the worst case, because a deadline missed once can be a failure.
Space counts too
Memory is a resource with its own complexity. Merge sort needs Θ(n) extra space; heapsort needs Θ(1). On a microcontroller with 64 KB of RAM, an algorithm with the better time complexity can be useless if its space complexity does not fit.
Explain it another way: intuitive
Imagine handing out exam papers. Giving one to each student is linear work. Having every student shake hands with every other is quadratic: double the class and the handshakes quadruple.
Explain it another way: technical
Asymptotic notation classifies functions by growth rate: Θ(1) ⊂ Θ(log n) ⊂ Θ(n) ⊂ Θ(n log n) ⊂ Θ(n²) ⊂ Θ(2ⁿ) ⊂ Θ(n!). Analysis fixes a cost model (for example, the RAM model where each primitive operation costs 1) and derives a bound on the count.
Explain it another way: mathematical
For f(n) = n(n−1)/2: f(n) ≤ ½n² for all n ≥ 1, so f = O(n²) with c = ½; and f(n) ≥ ¼n² for n ≥ 2, so f = Ω(n²). Hence Θ(n²). For the speed-up question: if T(n) = c·n^k and the machine is s times faster, the input size that fits a fixed time grows by s^(1/k).
Explain it another way: applied
A robot's obstacle check that compares every pair of points in a 10,000-point lidar scan does 5×10⁷ comparisons per scan. A k-d tree cuts that to roughly n log n ≈ 1.3×10⁵: the difference between 10 scans a second and none.
Try these examples
Example 1
Count the inner executions: for i in 0…n−1: for j in i+1…n−1: work() with n = 6.
The worked solution is in the online lesson.
Example 2
An n² algorithm handles n = 1,000 in 1 s. Roughly what n fits in 1 s on a machine 100× faster?
The worked solution is in the online lesson.
Common mix-ups
O(n) always beats O(n²).
✓ Only for large enough n. Constants and lower-order terms decide small inputs, so measure there too.Big-O means the exact running time.
✓ It is an upper bound up to a constant factor. Θ gives a tight bound; neither gives seconds.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. How many times is work() called when n = 16? Code: i = n; while i > 1: { work(); i = floor(i / 2) }
Answer: calls
2. Which is the tightest description of f(n) = 4n³ + 200n² log n + 10⁶?
- Θ(n³)
- Θ(n² log n)
- Θ(10⁶)
- O(n⁴) and nothing tighter
3. A braking controller must finish its computation within 2 ms every cycle. Which complexity matters most?
- Best case
- Average case
- Worst case
- Space complexity only
4. How many times is work() called when n = 270? Code: for i in 0 … n−1: for j in i+1 … n−1: work()
Answer: calls
5. An n³ algorithm handles n = 200 in one second. The machine is replaced with one 8 times faster. What n now fits in one second?
Answer:
6. Merge sort (Θ(n log n) time, Θ(n) extra space) and heapsort (Θ(n log n) time, Θ(1) extra space) must sort 40 KB of samples on a chip with 48 KB of free RAM. Which is safer?
- Merge sort, it is usually faster
- Heapsort, it fits in memory
- Either: they have the same time complexity
- Neither can sort on a microcontroller
Apply it
Pick three pieces of code you wrote this year (a filter, a search, a loop over sensor data). For each, state the basic operation, its count as a function of n, its Θ class and its extra space. Then estimate the largest n each could process in 10 ms on a 100 MHz microcontroller doing one operation per cycle.
Reflect
Which algorithm you have used would hurt most if its input grew 100 times, and why?
Divide, conquer and count with recurrences
Merge sort splits a list in half, sorts each half, then merges. How do you count the work of something defined in terms of itself?
Why it matters
FFTs, merge sort, k-d trees, Strassen's matrix multiply and many control and vision algorithms are recursive. Their cost is given by a recurrence, and solving it tells you whether splitting the problem actually helped.
Goals
- Write a recurrence T(n) = a·T(n/b) + f(n) for a divide-and-conquer algorithm.
- Solve a recurrence by unrolling it and summing the work level by level.
- Recognise the three regimes of the master theorem and when the work is dominated by the leaves, the levels or the root.
Predict
T(n) = 2·T(n/2) + n with T(1) = 1. Roughly what is T(1024)?
- About 1,024
- About 11,000
- About 1,000,000
- About 2,048
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, write merge sort with a global counter that increases by one for every element written during a merge. Run it for n = 16, 64, 256 and 1024 and compare the count with n log₂ n. Then change the split to thirds and see what changes.
What the interactive shows, in words
The derivation unrolls T(n) = aT(n/b) + n^c level by level: level j costs n^c (a/b^c)^j, so the total is a geometric series whose ratio decides whether the root, every level, or the leaves dominate.
Understand
From code to recurrence
Read the algorithm: how many recursive calls (a), how much smaller each is (b), and how much work outside the calls (f(n)). Merge sort: two calls on halves plus a linear merge, T(n) = 2T(n/2) + n. Binary search: one call on a half plus a comparison, T(n) = T(n/2) + 1. A base case such as T(1) = 1 stops the recursion.
Unroll and sum
Draw the recursion tree. Write the work at each level, then add the levels. This always works, and it shows where the cost lives: at the root, spread evenly, or in the millions of tiny leaves. For exact values with n a power of two, you can also just build upwards: T(1), T(2), T(4), …
The master theorem is a shortcut, not magic
Comparing a with b^c tells you which end of the tree dominates. It needs the subproblems to be equal in size and f(n) to be a polynomial. Uneven splits (quicksort's worst case, T(n) = T(n−1) + n) are not covered: unrolling gives n(n+1)/2, Θ(n²).
Explain it another way: intuitive
Think of a tournament bracket. Each round halves the players, and every round has the same total number of matches to referee. Rounds × work per round is the total.
Explain it another way: technical
A recurrence relates T(n) to T on smaller inputs. Methods: unrolling or recursion trees, substitution (guess and prove by induction), and the master theorem for T(n) = aT(n/b) + Θ(n^c).
Explain it another way: mathematical
With n = 2^k: T(2^k) = 2T(2^(k−1)) + 2^k. Divide by 2^k: S(k) = S(k−1) + 1 with S(0) = 1, so S(k) = k + 1 and T(n) = n(log₂ n + 1).
Explain it another way: applied
The Cooley–Tukey FFT has T(n) = 2T(n/2) + n, so it is Θ(n log n) instead of the Θ(n²) of a direct discrete Fourier transform. That single recurrence is why real-time audio and radar processing are possible on small chips.
Derivation: Unrolling T(n) = a·T(n/b) + n^c
Level 0 (the root) does n^c work. It makes a subproblems of size n/b.
Level 1 does a·(n/b)^c = n^c·(a/b^c) work. Level j does n^c·(a/b^c)^j.
There are log_b n levels, ending in a^(log_b n) = n^(log_b a) leaves of cost 1.
So T(n) = n^c · Σⱼ (a/b^c)^j, a geometric series with ratio r = a/b^c.
If r < 1 the root dominates: T = Θ(n^c). If r = 1 every level costs the same: T = Θ(n^c log n). If r > 1 the leaves dominate: T = Θ(n^(log_b a)).
Merge sort: a = 2, b = 2, c = 1, so r = 1 and T = Θ(n log n). Binary search: a = 1, b = 2, c = 0, r = 1, T = Θ(log n).
Try these examples
Example 2
Karatsuba multiplies two n-digit numbers with 3 half-size multiplications plus linear work. What is its complexity?
The worked solution is in the online lesson.
Common mix-ups
Splitting a problem in half always makes it faster.
✓ Only if the number of subproblems and the combine cost do not outweigh the shrinkage. 4T(n/2) + n is Θ(n²): no better than the direct method.The master theorem solves every recurrence.
✓ It needs equal-size subproblems and polynomial extra work. Otherwise unroll or use substitution.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. T(n) = 3·T(n/2) + n for n > 1, with T(1) = 1. What is T(32)?
Answer:
2. An algorithm checks the middle of a sorted array, then recurses on one half. Which recurrence describes it?
- T(n) = 2T(n/2) + 1
- T(n) = T(n/2) + 1
- T(n) = T(n − 1) + 1
- T(n) = 2T(n/2) + n
3. T(n) = 2·T(n/2) + 1 for n > 1, with T(1) = 1. What is T(32)?
Answer:
4. For T(n) = 8T(n/2) + n², which part of the recursion tree dominates?
- The root: Θ(n²)
- All levels equally: Θ(n² log n)
- The leaves: Θ(n³)
- It cannot be solved
5. Quicksort's worst case gives T(n) = T(n − 1) + n with T(1) = 1. What is T(10)?
Answer:
Apply it
Write a recursive maximum-finder that splits the array in half, and a recursive one that removes one element at a time. Write both recurrences, solve them, then count operations in the Code Lab for n up to 4096 and plot both against your predictions.
Reflect
Where in a recursion tree did you expect the work to be before this lesson, and where is it for merge sort?
When exact answers are out of reach
A delivery van must visit 20 shops. Trying every route would take a fast computer about two years. How do real route planners answer in a second?
Why it matters
Scheduling, routing, chip placement, packing and many planning problems are NP-hard. Engineers still solve them every day, by giving up a guarantee of optimality in exchange for speed, and by measuring how much they gave up.
Goals
- Explain the difference between polynomial-time (tractable) and exponential-time problems.
- Describe P, NP and NP-hard informally, using the idea that checking can be easier than finding.
- Justify using a heuristic or approximation algorithm and measure its gap from the optimum on small cases.
Predict
Going from 9 cities to 10 multiplies the number of distinct round trips by about…
- 1.1×
- 2×
- 9×
- 100×
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start at 4 cities and add one at a time up to 9, watching 'tours tried'. On several random maps, compare the greedy nearest-neighbour route with the exact best. How far off is greedy at its worst?
What the interactive shows, in words
The explorer draws 4 to 9 random cities with two routes: the exact best tour (found by trying all (n−1)!/2 tours) and the greedy nearest-neighbour tour. A table reports tours tried, both lengths and the percentage gap; at 20 cities brute force would need about 6×10¹⁶ tours.
Understand
Tractable means polynomial
A problem is usually called tractable if some algorithm solves it in O(n^k) time for a fixed k. Sorting, shortest paths (Dijkstra) and linear systems are tractable. Problems whose best known algorithms take 2ⁿ or n! time become impossible to solve exactly beyond a few dozen items, whatever the hardware.
P, NP and NP-hard, informally
P: problems solvable in polynomial time. NP: problems where a proposed answer can be checked in polynomial time (is this route shorter than 500 km? add up its legs). NP-hard: at least as hard as every NP problem; a fast algorithm for one would give fast algorithms for all. Nobody has proved P ≠ NP, but no one has found a polynomial algorithm for an NP-hard problem either, so engineers plan as if none exists.
Heuristics and approximations
A heuristic (nearest neighbour, greedy packing, simulated annealing) is fast but has no promise about quality. An approximation algorithm comes with a proof: for travelling-salesperson maps that obey the triangle inequality, Christofides' algorithm is never worse than 1.5× optimal. Either way, measure the gap on cases small enough to solve exactly, as the explorer does.
Explain it another way: intuitive
Checking that a jigsaw is finished takes a glance. Finishing it takes an afternoon. Many engineering problems look like jigsaws: easy to check, hard to find.
Explain it another way: technical
Decision problems are classified by resource bounds. NP-complete problems (SAT, Hamiltonian cycle, subset sum, decision-TSP) are in NP and NP-hard; they reduce to each other in polynomial time. Optimisation versions are NP-hard. Practical tools: branch-and-bound, integer programming solvers, local search and problem-specific heuristics.
Explain it another way: mathematical
Exact TSP by brute force costs (n − 1)!/2 tour evaluations, each Θ(n). By Stirling, n! ≈ √(2πn)(n/e)ⁿ, which outgrows any cⁿ. Held–Karp dynamic programming does better, Θ(n²·2ⁿ), but is still exponential. Nearest neighbour is Θ(n²).
Explain it another way: applied
Chip design tools place millions of standard cells and route their wires: NP-hard problems at enormous scale. They use heuristics such as simulated annealing and analytic placement, and accept good rather than optimal layouts.
Try these examples
Example 1
How many distinct round trips through 12 cities, ignoring direction?
The worked solution is in the online lesson.
Example 2
A greedy route is 112 km and the exact best is 100 km. Report the heuristic's quality.
The worked solution is in the online lesson.
Common mix-ups
NP means 'not polynomial'.
✓ It means 'nondeterministic polynomial': solutions are checkable in polynomial time. P is inside NP.If a problem is NP-hard, engineers cannot solve it.
✓ They solve large instances well with heuristics, approximations and solvers, and small ones exactly.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which statement captures membership of NP?
- It can be solved in polynomial time
- A proposed solution can be checked in polynomial time
- It can never be solved exactly
- It needs a non-deterministic computer
2. How many distinct round trips (direction ignored) through 8 cities?
Answer:
3. Your greedy scheduler beats random scheduling on every test. What should the report claim?
- It is optimal
- It is better than random on these tests; its gap to optimal is measured on small cases where the optimum can be computed
- NP-hard problems cannot be evaluated
- Nothing until P vs NP is solved
4. How many times is work() called when n = 270? Code: for i in 0 … n−1: for j in i+1 … n−1: work()
Answer: calls
5. Which problem has a known polynomial-time algorithm?
- Shortest path between two nodes in a road graph with positive lengths
- Shortest tour visiting every node once
- Choosing a subset of parcels that exactly fills a van's weight limit
- Colouring a map with 3 colours so neighbours differ
Apply it
In the explorer, record the greedy-to-optimal ratio on 20 random maps of 8 cities. Report the mean, the worst case and a histogram. Then propose one improvement to nearest neighbour (for example, 2-opt: reverse a segment if it shortens the tour) and predict whether it narrows the gap.
Reflect
Name a problem from your own projects that is secretly a search over every combination. What heuristic would you try?
Week 20: Computer microarchitecture
This week you will
- Use the Iron Law T = IC × CPI × cycle time to compare designs.
- Compare single-cycle, multi-cycle and pipelined datapaths.
- Explain data, control and structural hazards and how forwarding, stalls and prediction handle them.
Single-cycle, multi-cycle and the Iron Law
Chip A runs at 4 GHz, chip B at 2 GHz. B finishes your program first. How?
Why it matters
Clock frequency is the number on the box, but it is one factor of three. Every architecture decision, from the instruction set to the cache, moves instruction count, cycles per instruction or cycle time, and usually trades one against another. The Iron Law is how architects keep score.
Goals
- State the Iron Law T = IC × CPI × cycle time and say which design choices change each factor.
- Compare a single-cycle and a multi-cycle datapath by cycle time and CPI.
- Compute execution time and speed-up for two designs from their IC, CPI and clock frequency.
Predict
A single-cycle CPU must fit its slowest instruction (a load, 800 ps) into every cycle. A multi-cycle version uses 200 ps steps; loads take 5 steps and ALU ops 4. For a program of only ALU ops, which is faster?
- Single-cycle: 800 ps per instruction
- Multi-cycle: 800 ps per instruction, the same
- Multi-cycle is slower: it has more cycles
- Single-cycle, because CPI = 1 is always best
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the Nibble machine and step your multiply program through fetch, decode and execute. Count how many steps each instruction takes: that count is the machine's CPI per instruction type, and the step time is its cycle time.
What the interactive shows, in words
The Nibble machine activity can be done on paper: list the instructions of the multiply program, give each a step count (fetch, decode, execute), and add them up over the loop iterations to get cycles and CPI.
Understand
Single-cycle datapath
Every instruction completes in one long clock cycle, so CPI = 1, but the cycle must be long enough for the slowest path (instruction memory → register read → ALU → data memory → register write, for a load). Simple instructions waste most of the cycle.
Multi-cycle datapath
Break execution into steps (fetch, decode, execute, memory, write-back) and give each step one short cycle. Instructions use only the steps they need, so CPI is now an average (perhaps 4) but the cycle is about the length of one step. Hardware can be reused across steps: one memory and one ALU instead of separate ones.
Three factors, coupled
A richer instruction set lowers IC but may raise CPI or the cycle time. A deeper pipeline shortens the cycle but raises CPI when hazards hit. A good comparison quotes all three and measures them on the same program, compiled the same way, which is why benchmark suites exist.
Explain it another way: intuitive
Your journey time is number of stops × minutes per stop × how long each minute takes. A train that stops less often can beat a faster train that stops everywhere.
Explain it another way: technical
CPI = Σᵢ (fraction of instruction class i) × CPIᵢ. MIPS and GHz alone are misleading because they ignore IC and CPI. Only total execution time on a defined workload is a fair performance metric.
Explain it another way: mathematical
For a mix with fractions pᵢ and step counts cᵢ on a multi-cycle machine with step time τ: T = IC × (Σ pᵢcᵢ) × τ. Single-cycle: T = IC × 1 × max(path delays). Multi-cycle wins when Σ pᵢcᵢ × τ < max delay.
Explain it another way: applied
Arm Cortex-M0 microcontrollers take more than one cycle for some instructions but run at low clocks with tiny power; desktop cores push CPI well below 1 by issuing several instructions per cycle. Both are judged by the same equation.
Derivation: The Iron Law, from units
Time per program = (instructions / program) × (cycles / instruction) × (seconds / cycle).
The units cancel: instructions × cycles/instruction × seconds/cycle = seconds. So T = IC × CPI × t_clk = IC × CPI / f.
IC is set by the algorithm, the compiler and the instruction set. CPI by the microarchitecture (pipelining, caches, prediction). t_clk by the circuit and the process technology.
Speed-up of B over A = T_A / T_B = (IC_A/IC_B) × (CPI_A/CPI_B) × (f_B/f_A).
Example: A has IC = 10⁹, CPI = 2, 4 GHz: T = 0.5 s. B has IC = 0.8×10⁹, CPI = 1.1, 2 GHz: T = 0.44 s. B wins by 0.5/0.44 ≈ 1.14× despite half the clock.
Try these examples
Example 1
A mix is 50% ALU (4 steps), 20% loads (5), 10% stores (4), 20% branches (3). Step time 200 ps. Compare with an 800 ps single-cycle design.
The worked solution is in the online lesson.
Common mix-ups
A higher clock frequency always means a faster computer.
✓ Only if IC and CPI stay the same. Execution time on the real workload is the only fair measure.Multi-cycle machines are slower because CPI > 1.
✓ Their cycle is much shorter, so time per instruction can be lower; CPI alone says nothing.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A program executes 750 million instructions with an average CPI of 0.8 on a 2 GHz processor. How long does it take, in milliseconds?
Answer: ms
2. A program's mix is 60% ALU (1 cycle), 15% loads (2 cycles), 20% branches (3 cycles) and 5% stores (2 cycles). What is the average CPI?
Answer:
3. A compiler optimisation removes redundant instructions without changing the hardware. Which Iron Law factor does it change most directly?
- Instruction count
- Cycle time
- Clock frequency
- None
4. A program executes 200 million instructions with an average CPI of 1.8 on a 3 GHz processor. How long does it take, in milliseconds?
Answer: ms
5. Design A: CPI 1.6 at 3 GHz. Design B: CPI 1.0 at 2.4 GHz, same instruction count. What is B's speed-up over A?
Answer: ×
Apply it
Your Nibble multiply program runs a loop. Count its dynamic instruction count for 3 × 5 and estimate CPI from the steps you counted. If the machine ran at 1 MHz, how long would 15 × 15 take? Which factor would you attack first to speed it up?
Reflect
Which factor of the Iron Law did you think about least before today, and where have you seen it matter?
Pipelining: an assembly line for instructions
A laundry takes 30 minutes to wash, 40 to dry and 20 to fold. How long do four loads take if you never wait for one to finish before starting the next?
Why it matters
Pipelining is why one processor core retires billions of instructions per second. It is also a general engineering pattern: video codecs, network routers and factory lines all overlap stages. Understanding its limits stops you expecting a 20-stage pipeline to be 20 times faster.
Goals
- Draw a pipeline diagram for n instructions on a k-stage pipeline and count total cycles k + n − 1.
- Explain why pipelining improves throughput but not the latency of one instruction.
- Derive the limit on pipeline speed-up from stage imbalance and register overhead.
Predict
5 instructions on an ideal 5-stage pipeline (one cycle per stage, no hazards). How many cycles?
- 5
- 9
- 25
- 10
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose 'Independent ALU ops', turn forwarding on and choose 'Perfect predictor'. Read the diagonal staircase and check the cycle count against k + n − 1. Then pick the other programs to see the ideal break: that is next lesson's topic.
What the interactive shows, in words
The pipeline table has one row per instruction and one column per clock cycle; each instruction's IF, ID, EX, MEM and WB cells shift one column to the right of the previous instruction's, forming a staircase. For 5 independent instructions it ends at cycle 9.
Understand
Throughput versus latency
Pipelining does not make one instruction faster: it still passes through every stage, and register overhead makes it slightly slower. What improves is throughput: once full, the pipeline completes one instruction every cycle. Ideal CPI approaches 1 for long runs.
The classic five stages
IF fetches the instruction, ID decodes it and reads registers, EX uses the ALU, MEM accesses data memory, WB writes the result back. Registers between stages hold each instruction's state so the stages can work on different instructions at once.
Balance and overhead
The clock must suit the slowest stage, and every stage boundary adds a register's setup and clock-to-output delay. Deeper pipelines get diminishing returns and, as you will see, pay more for every hazard. Modern designs settle on roughly 10–20 stages as a compromise.
Explain it another way: intuitive
A sandwich bar with one person doing everything makes a sandwich every 4 minutes. Four people, each doing one step, make one every minute once the line is going, though each sandwich still takes 4 minutes.
Explain it another way: technical
A k-stage pipeline has fill time (k − 1 cycles) and drain time; steady-state throughput is one instruction per cycle. Cycle time = max stage delay + register overhead (setup + clock-to-Q + clock skew).
Explain it another way: mathematical
S(n) = nT / ((k + n − 1)(T/k + o)). For n = 100, k = 5, o = 0: S = 500/104 ≈ 4.81. Efficiency S/k → 1 only as n → ∞.
Explain it another way: applied
A GPU is a deep pipeline in both senses: thousands of pixels flow through vertex, raster and shading stages. Its latency for one pixel is long; its throughput is enormous.
Derivation: How much faster can a pipeline be?
Unpipelined: each instruction takes T, so n instructions take n·T.
Split into k stages. If perfectly balanced, each stage is T/k, but each needs a pipeline register adding overhead o. Cycle = T/k + o.
Pipelined time for n instructions = (k + n − 1)(T/k + o).
Speed-up S = n·T / ((k + n − 1)(T/k + o)). As n → ∞, S → T/(T/k + o) = k / (1 + k·o/T).
With no overhead the limit is k. With o = 0.1 T, a 5-stage pipe tops out at 5/1.5 ≈ 3.3×; a 20-stage pipe at 20/3 ≈ 6.7×, not 20×.
Unbalanced stages are worse: the cycle is set by the slowest stage, so S ≤ T / max(stage delay).
Try these examples
Example 1
Stages of 200, 150, 250, 300 and 100 ps, register overhead 20 ps. Find the cycle time and the speed-up for many instructions versus the 1000 ps unpipelined design.
The worked solution is in the online lesson.
Common mix-ups
A k-stage pipeline makes the processor k times faster.
✓ Only with perfect balance, no overhead, no hazards and infinitely long programs. Real gains are smaller.Pipelining makes each instruction finish sooner.
✓ It makes instructions finish more often. Each one still takes all k stages.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. 127 instructions run on a 4-stage pipeline. Hazards insert 6 stall cycles in total. How many clock cycles until the last instruction completes?
Answer: cycles
2. A single-cycle datapath has a 5 ns cycle. It is split into 10 equal stages, each adding 0.1 ns of register (latch) overhead. What is the speed-up for 100 instructions with no stalls?
Answer: ×
3. Compared with the unpipelined design, the latency of a single instruction in a pipeline is…
- k times shorter
- About the same or slightly longer
- Always exactly one cycle
- Zero once the pipeline is full
4. 83 instructions run on a 8-stage pipeline. Hazards insert 9 stall cycles in total. How many clock cycles until the last instruction completes?
Answer: cycles
5. A 1,200 ps datapath is split into 6 perfectly balanced stages with 50 ps register overhead each. What is the speed-up limit for very long programs?
Answer: ×
Apply it
Sketch a 4-stage pipeline for a robot's sensor loop: read sensor, filter, decide, actuate. Give each stage a realistic time, find the cycle time and throughput, then argue whether the pipeline's extra latency is acceptable for a control loop.
Reflect
Where else have you seen a pipeline (in software, in a kitchen, in a factory)? What was its slowest stage?
Hazards, forwarding and branch prediction
An instruction needs a number the previous one hasn't finished computing. Does the whole assembly line stop?
Why it matters
Hazards are where pipelines lose their promise. Forwarding paths, branch predictors and separate instruction and data caches exist purely to fight them, and they occupy a large fraction of a modern core's design effort. Compilers reorder code to dodge them too.
Goals
- Identify data (read-after-write), control and structural hazards in a short program.
- Count stall cycles with and without forwarding, including the load-use case.
- Explain branch prediction and compute the CPI cost of mispredictions.
Predict
add r1, r2, r3 is followed immediately by sub r4, r1, r5. With no forwarding (results read from the register file), how many stall cycles?
- 0
- 1
- 2
- 4
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Every stall cycle adds to CPI, and this calculator shows how much. Set branches to 20%, mispredict to 10% and penalty to 2: read the CPI. Raise the penalty to 15 (a deep pipeline) and watch the branch slice grow. Pin a design, then trade a faster clock for a bigger penalty and read the speed-up.
What the interactive shows, in words
The Iron Law calculator shows CPI as base + branch stalls + memory stalls. With 20% branches, 10% mispredicted at 2 cycles, and 30% memory instructions missing 5% at 40 cycles, CPI = 1 + 0.04 + 0.6 = 1.64, and T = IC × CPI ÷ f.
Understand
Data hazards
A read-after-write hazard occurs when an instruction needs a register that an earlier, still-in-flight instruction will write. Without help, the reader stalls in ID until the writer reaches WB: 2 bubbles for adjacent instructions in the classic 5-stage pipe. Forwarding (bypassing) wires the ALU output straight back to the ALU input, removing the stall for ALU results.
The load-use stall
A load's data appears only at the end of MEM. Even with forwarding, an instruction that uses it immediately must wait one cycle. Compilers hide this by scheduling an independent instruction between the load and its use, which is why the 'Load then use' program in the pipeline diagram has an unrelated sub in the middle.
Control and structural hazards
A branch is not resolved until EX, so the pipeline has already fetched 2 instructions that may be wrong. Stalling on every branch wastes those cycles always; predict not taken wastes them only when the branch is taken; dynamic predictors learn each branch's habit and are right well over 90% of the time on typical code. A structural hazard arises when two stages need one resource, like a single memory port for fetch and data: hence separate instruction and data caches.
Hazards in the Iron Law
Every stall adds to CPI: CPI = 1 + (data stalls per instruction) + (branch fraction × mispredict rate × penalty) + (memory stalls). Deeper pipelines raise the branch penalty, so a faster clock can lose to a shorter pipe with a better predictor.
Explain it another way: intuitive
A kitchen line where the next cook needs the sauce the previous cook is still stirring. Either they wait, or the first cook hands the sauce across the counter as soon as it's ready instead of putting it in the fridge first. That hand-over is forwarding.
Explain it another way: technical
Hazard detection logic in ID compares source registers with destination registers of instructions in EX and MEM, and either inserts a bubble (stalls PC and IF/ID, zeroes ID/EX control) or selects a forwarding mux input. Branch predictors (2-bit saturating counters, branch target buffers) let fetch continue speculatively; mispredictions flush the wrong-path instructions.
Explain it another way: mathematical
With branch fraction b, misprediction rate m and penalty P: CPI_branch = b·m·P. For b = 0.2, m = 0.05, P = 15: 0.15 extra CPI. Halving m to 0.025 is worth the same as cutting P from 15 to 7.5.
Explain it another way: applied
Long pipelines in early-2000s desktop processors reached very high clocks but suffered heavy misprediction penalties; later designs returned to shorter pipelines with much better predictors. The trade-off is exactly the one in the Iron Law calculator.
Try these examples
Example 1
lw r1, 0(r2) then add r3, r1, r4, with forwarding. Stalls?
The worked solution is in the online lesson.
Example 2
Branches are 15% of instructions; a predictor is wrong 8% of the time; the penalty is 3 cycles. Extra CPI?
The worked solution is in the online lesson.
Common mix-ups
Forwarding removes all data hazards.
✓ It cannot help a load followed immediately by its use: the data does not exist yet.Branch prediction is a guess, so it cannot be relied on.
✓ Wrong guesses are detected and flushed; prediction only affects speed, never correctness.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. lw r5, 4(r2) / add r6, r5, r1. Which hazard and, with forwarding, how many stall cycles?
- Structural, 0
- Data (load-use), 1
- Control, 2
- Data, 0 thanks to forwarding
2. A pipeline has base CPI 1. Branches are 15% of instructions, 20% of them are mispredicted, costing 2 cycles each. Loads and stores are 20% of instructions, 10% of them miss in the cache, costing 100 cycles each. What is the effective CPI?
Answer:
3. Design B doubles the pipeline depth of A, raising the clock 1.6× and the branch penalty from 2 to 5 cycles. Branch fraction 20%, mispredict 10%, base CPI 1 for both, memory ignored. Which is faster?
- A
- B
- Equal
- Cannot tell without IC
4. A pipeline has base CPI 1. Branches are 20% of instructions, 10% of them are mispredicted, costing 15 cycles each. Loads and stores are 35% of instructions, 4% of them miss in the cache, costing 50 cycles each. What is the effective CPI?
Answer:
5. On the classic 5-stage pipeline with no forwarding, a chain of 4 ALU instructions each uses the previous one's result. How many total cycles? (Ideal is 8.)
Answer: cycles
6. Why do most processors have separate L1 instruction and data caches?
- To store more data
- To remove the structural hazard of fetch and load/store needing memory in the same cycle
- Because instructions are larger than data
- To make branch prediction possible
Apply it
Take the 'Loop with a taken branch' program in the pipeline diagram. Reorder instructions (on paper) to remove the load-use stall without changing the result, then count the cycles you save over 1,000 iterations with predict-not-taken versus a perfect predictor.
Reflect
Which hazard surprised you most, and which fix (hardware or compiler) do you find more elegant?
Week 21: Memory hierarchy
This week you will
- Explain registers, caches, main memory and storage by latency and capacity.
- Split an address into tag, index and offset and predict hits and misses for an access pattern.
- Compute AMAT for one and two cache levels.
Locality and the memory hierarchy
Two loops add up the same million numbers. One is ten times slower. Same chip, same maths. What is different?
Why it matters
A modern core can do an addition in under a nanosecond but waits around a hundred nanoseconds for main memory. Caches hide that gap, but only for programs with locality. Writing cache-friendly code is often the cheapest speed-up an engineer can get.
Goals
- Order registers, caches, main memory and storage by latency, capacity and cost per byte.
- Explain temporal and spatial locality with code examples.
- Predict qualitatively whether an access pattern will hit or miss in a cache.
Predict
A cache with 16-byte blocks reads 32 consecutive 4-byte integers, starting empty. How many misses?
- 32
- 8
- 1
- 16
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Run 'Walk an array', then 'Small loop, twice', then 'Big stride', all direct-mapped with 16 B blocks. For each, predict the hit rate before you press Show all. Then try 32 B blocks on the array walk and on the stride.
What the interactive shows, in words
The cache simulator lists each address, its set and tag, and whether it hits. With 16-byte blocks: walking 32 integers gives 8 misses and 24 hits; reading 16 integers twice gives 4 misses; a 64-byte stride misses every time.
Understand
The hierarchy
Registers (bytes to a few KB, under a nanosecond), L1 cache (tens of KB, about 1 ns), L2/L3 (hundreds of KB to tens of MB, several to tens of ns), DRAM (GB, around 100 ns), flash or disk (TB, microseconds to milliseconds). Each level is bigger, slower and cheaper per byte than the one above. Typical figures vary widely between chips.
Temporal locality
Data used now is likely to be used again soon: loop counters, a filter's coefficients, the top of the stack. Keeping recently used data in a small fast memory serves those repeat visits.
Spatial locality
Data near what you just used is likely to be used next: the next array element, the next instruction. Caches move whole blocks (often 64 bytes) so one miss pre-loads the neighbours. Walking a 2-D array row by row in a row-major language uses this; walking it column by column wastes it.
Explain it another way: intuitive
Your desk, your bookshelf and the library. You keep the book you're using on the desk (temporal) and take the next chapter's book from the same shelf while you're there (spatial).
Explain it another way: technical
Hit rate h = hits/accesses. Misses are compulsory (first touch), capacity (working set too big) or conflict (blocks fighting for the same set). Block size trades spatial-locality gains against fewer blocks and a longer miss penalty.
Explain it another way: mathematical
For a sequential walk of 4-byte words with B-byte blocks, the miss rate is 4/B: 25% at 16 B, 6.25% at 64 B. For a stride s ≥ B, every access misses: miss rate 1.
Explain it another way: applied
Image-processing code tiles an image into small squares that fit in the cache, processing each completely before moving on. The arithmetic is identical; the speed is not.
Try these examples
Example 1
A C program sums a 1000×1000 int matrix as sum += a[j][i] (column by column). Why is it slow, and what is the fix?
The worked solution is in the online lesson.
Common mix-ups
Memory access time is constant, so only operation counts matter.
✓ A cache miss can cost 100 times a hit. Access patterns change real run time massively.Bigger blocks are always better.
✓ They help sequential access but waste bandwidth and capacity on strided or random access.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A filter applies the same 5 coefficients to every sample. Which locality do the coefficients show?
- Temporal
- Spatial only
- Neither
- Only compulsory misses
2. A loop reads 256 consecutive 4-byte floats into an empty cache with 64-byte blocks. How many misses?
Answer: misses
3. A direct-mapped cache has 4 lines of 16 bytes and starts empty. The CPU reads these byte addresses in order: 124, 272, 272, 368, 20, 20, 272, 144, 144, 144. How many reads hit?
Answer: hits
4. Reading every 64th byte with 16-byte blocks gives 100% misses. What happens if blocks grow to 32 bytes?
- Misses halve
- Still 100% misses
- No misses
- Misses double
5. Which list is ordered from fastest to slowest?
- DRAM, L1, registers, SSD
- Registers, L1, L2, DRAM, SSD
- L1, registers, DRAM, L2
- SSD, DRAM, L2, L1
Apply it
Write two versions of a 2-D image blur in the Code Lab: row-major and column-major traversal. Without timing them, predict which is faster and by roughly how much using a 64-byte block. Then explain how you would test your prediction fairly.
Reflect
Which piece of your own code would you now rewrite for locality?
Inside a cache: tags, sets and ways
A cache holds a tiny fraction of memory. When the CPU asks for address 0x1F40, how does the cache know in one nanosecond whether it has it?
Why it matters
Cache organisation is a precise piece of digital design: a few bits of the address choose where to look, the rest are compared to check you found the right thing. Getting the bit split right is the first step in designing, simulating or debugging any memory system.
Goals
- Split an address into tag, index and offset bits for a given cache size, block size and associativity.
- Trace a direct-mapped and a 2-way set-associative cache with LRU through an address stream.
- Explain how tag comparison is built from logic gates and why associativity costs hardware.
Predict
Two arrays exactly one cache-size apart are read alternately (a[0], b[0], a[1], b[1], …) in a direct-mapped cache. What happens?
- Almost every access hits
- Every access misses: they evict each other
- Half hit, half miss
- The cache stores both in one line
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the logic lab, build a 2-bit equality comparator: XNOR each pair of tag bits, then AND the results. This is the 'hit' signal of one cache way. Count the gates, then work out how many a 4-way cache with 18-bit tags needs.
What the interactive shows, in words
The logic lab task can be done as a truth table: a 2-bit comparator outputs 1 only when A1 = B1 and A0 = B0, built as AND(XNOR(A1, B1), XNOR(A0, B0)). Each cache way needs one such comparator, as wide as the tag.
Understand
Offset, index, tag
With B-byte blocks, the lowest log₂ B bits are the offset (which byte in the block). With S sets, the next log₂ S bits are the index (which set to look in). The remaining high bits are the tag, stored with the block and compared on every access. Sets S = cache size ÷ (block size × ways).
Direct-mapped versus set-associative
Direct-mapped (1 way): each block has exactly one possible line. Fast and simple: one tag comparison. N-way set-associative: each set holds N blocks, so N comparisons happen in parallel and a multiplexer picks the hit way. Conflict misses fall; area, energy and sometimes hit time rise. Fully associative is one set holding everything.
Replacement and writes
When a set is full, LRU (least recently used) evicts the block untouched for longest; real caches often approximate it. Stores need a policy too: write-through sends every write to the next level; write-back marks the block dirty and writes it only on eviction, saving bandwidth.
The hardware cost
Each way needs a tag-width equality comparator: one XNOR per bit plus an AND tree, and a valid bit. A 4-way cache with 18-bit tags needs 4 × 18 = 72 XNORs before the AND trees and way multiplexer. That is the area and energy behind 'just add associativity'.
Explain it another way: intuitive
A cloakroom with numbered hooks. Direct-mapped: your ticket number decides the one hook your coat must go on, even if it's taken. 2-way: each number has two hooks, so two coats with the same number can both stay.
Explain it another way: technical
Lookup: index selects a set; all ways' tags are read and compared with the address tag in parallel; hit = OR over ways of (valid AND tag match); data multiplexer selects the hitting way; offset selects the word.
Explain it another way: mathematical
For a 32 KB, 8-way cache with 64 B blocks and 48-bit addresses: offset = 6, sets = 32768/(64×8) = 64, index = 6, tag = 48 − 12 = 36 bits.
Explain it another way: applied
Many microcontrollers have no data cache at all, only a small flash prefetch buffer, so their timing is predictable for real-time control. Application processors use 4- to 16-way caches because conflict misses would cost more than the comparators.
Try these examples
Example 1
A 32 KB direct-mapped cache, 64 B blocks, 32-bit addresses. Split the address.
The worked solution is in the online lesson.
Common mix-ups
Higher associativity always makes a cache better.
✓ It cuts conflict misses but adds comparators, energy and sometimes hit time. Gains shrink beyond 8 ways for many workloads.The index bits are the high bits of the address.
✓ Index comes just above the offset, so consecutive blocks fall in consecutive sets.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A 32 KB 4-way set-associative cache has 16-byte blocks and 64-bit byte addresses. How many offset bits are there?
Answer: bits
2. A 8 KB direct-mapped cache has 128-byte blocks and 32-bit byte addresses. How many offset bits are there?
Answer: bits
3. A direct-mapped cache has 4 lines of 16 bytes and starts empty. The CPU reads these byte addresses in order: 124, 272, 272, 368, 20, 20, 272, 144, 144, 144. How many reads hit?
Answer: hits
4. Going from direct-mapped to 4-way set-associative at the same capacity mainly costs…
- More tag comparators and a way multiplexer
- More capacity
- Smaller blocks
- Nothing: it is free
5. A single set with 2 ways and LRU replacement sees blocks A, B, A, C, B. Which accesses hit?
- Only the second A
- The second A and the last B
- None
- All after the first two
6. How many single-bit XNOR gates do the tag comparators of an 8-way cache with 20-bit tags need?
Answer: XNORs
Apply it
Using the cache simulator, find an access stream of at most 12 addresses that has more misses in a 2-way cache than in a direct-mapped one of the same size. (Hint: LRU is not always kind.) Explain why it happens.
Reflect
What part of a cache's design felt most like ordinary digital logic you already knew?
Average memory access time
A cache hits 95% of the time. Is that good? It depends entirely on what the other 5% cost.
Why it matters
Architects argue about caches in AMAT. It turns hit rate, latency and memory speed into one number in cycles, and it shows why a slightly bigger, slower L1 can lose to a small fast one backed by a good L2.
Goals
- Compute AMAT = hit time + miss rate × miss penalty for one cache level.
- Extend AMAT to two levels using L2 local miss rate.
- Fold memory stalls into the Iron Law and judge which cache change helps most.
Predict
L1 hits in 1 cycle with a 5% miss rate; memory takes 100 cycles. What is the AMAT?
- 1 cycle
- 5 cycles
- 6 cycles
- 100 cycles
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start with L2 off. Raise main-memory latency and watch AMAT climb. Turn L2 on and find the L2 miss rate at which it stops being worth having. Which change saves more: halving the L1 miss rate, or halving the L2 hit time?
What the interactive shows, in words
The AMAT explorer shows a stacked bar: L1 hit time, plus L1 misses times L2 time, plus global misses times memory time. With h₁ = 1, m₁ = 5%, h₂ = 10, m₂ = 20% and memory 100 cycles, AMAT = 2.5 cycles; without L2 it is 6.
Understand
One formula, three levers
AMAT = hit time + miss rate × miss penalty. Reduce hit time (small, simple L1), reduce miss rate (bigger, more associative, better prefetching) or reduce miss penalty (an L2, faster memory, critical-word-first). They fight: bigger and more associative usually means slower hits.
Local and global miss rates
L2's local miss rate looks bad (20–50% is common) because L1 has already filtered out the easy accesses. What matters for AMAT is the global rate m₁·m₂, often well under 1%.
Back to the Iron Law
Memory stalls add to CPI. A program with 0.3 memory accesses per instruction and 1.5 extra cycles per access from misses gains 0.45 CPI: as much as many branch-prediction improvements. This is why memory is often called the bottleneck.
Explain it another way: intuitive
Your average commute: most days the bus is on time, but one day in twenty it breaks down and you wait an hour. That rare hour dominates the average.
Explain it another way: technical
AMAT is an average; real out-of-order cores overlap some misses (memory-level parallelism), so effective stall time can be lower. AMAT remains the standard first-order model.
Explain it another way: mathematical
∂AMAT/∂m₁ = P₁ and ∂AMAT/∂h₁ = 1. With P₁ = 30, cutting the miss rate by 0.01 saves 0.3 cycles; cutting hit time by 1 saves 1 cycle. Compare costs in hardware to choose.
Explain it another way: applied
Embedded designers sometimes place time-critical code in tightly coupled memory (TCM), a small SRAM with a fixed one-cycle access and no misses: AMAT = 1 exactly, which makes deadlines provable.
Derivation: AMAT for two levels, and back into CPI
One level: every access pays h₁; a fraction m₁ also pays the penalty P₁. AMAT = h₁ + m₁P₁.
With L2, an L1 miss is served by L2, whose own average time is h₂ + m₂·t_mem, where m₂ is L2's local miss rate (misses ÷ accesses that reach L2).
So P₁ = h₂ + m₂·t_mem and AMAT = h₁ + m₁(h₂ + m₂·t_mem).
Global L2 miss rate = m₁·m₂: the fraction of all accesses that reach memory.
Memory stall cycles per instruction = (memory accesses per instruction) × (AMAT − h₁), if the hit time is already counted in base CPI.
Example: h₁ = 1, m₁ = 0.05, h₂ = 10, m₂ = 0.2, t_mem = 100: AMAT = 1 + 0.05 × 30 = 2.5 cycles, versus 6 without L2.
Try these examples
Example 1
Option A: 1-cycle L1, 6% miss rate. Option B: 2-cycle L1, 3% miss rate. Both backed by a 40-cycle L2 that never misses. Which is better?
The worked solution is in the online lesson.
Common mix-ups
A 95% hit rate means memory is 95% as fast as the cache.
✓ With a 100-cycle penalty, AMAT is 6× the hit time. Misses dominate.A 30% L2 miss rate means L2 is useless.
✓ It is a local rate on the hard accesses L1 missed; the global rate is far lower.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A cache has a hit time of 3 cycles, a miss rate of 1% and a miss penalty of 100 cycles. What is the AMAT in cycles?
Answer: cycles
2. L1: hit time 1 cycles, miss rate 10%. L2: hit time 8 cycles, local miss rate 10%. Main memory: 300 cycles. What is the AMAT in cycles?
Answer: cycles
3. A cache has a hit time of 2 cycles, a miss rate of 5% and a miss penalty of 100 cycles. What is the AMAT in cycles?
Answer: cycles
4. L1 miss rate is 4% and L2 local miss rate is 25%. What percentage of all accesses go to main memory?
Answer: %
5. AMAT = 1 + 0.08 × 50. Which single change helps most?
- Cut hit time from 1 to 0.5 cycles
- Cut miss rate from 8% to 6%
- Cut miss penalty from 50 to 45 cycles
- All save the same
6. Base CPI is 1. There are 0.4 memory accesses per instruction, L1 hit time is included in base CPI, and AMAT is 3 cycles with a 1-cycle hit time. What is the effective CPI?
Answer:
Apply it
Design a two-level hierarchy for a 'module check': choose L1 and L2 hit times and miss rates (state your assumptions) to achieve AMAT under 2 cycles with a 150-cycle memory. Show the calculation and argue which assumption is least realistic.
Reflect
Which surprised you more: how much a few misses cost, or how much an L2 rescues?
Week 22: Hardware–software co-design and integrated circuits
This week you will
- Partition a task between hardware and software and justify the split with Amdahl's law.
- Describe a chip's architecture: die, standard cells, interconnect and clock distribution.
- Explain wafers, photolithography, process nodes, yield and cost per die.
Hardware or software? Partitioning a task
Moving one function into custom hardware makes it 50 times faster. Why might the whole program only get twice as fast?
Why it matters
Phones contain video encoders, image processors and neural accelerators because some jobs are worth fixing in silicon. Others stay in software because they change, or because they barely affect total time. Deciding which is which, with numbers, is co-design.
Goals
- Explain what hardware–software co-design is and the costs of moving a function into hardware.
- Use Amdahl's law to bound the overall speed-up from accelerating part of a task.
- Compare a software loop with a hardware circuit for the same function by operation count and gate delay.
Predict
Computing the parity of an 8-bit byte in software takes a loop of about 8 iterations. How many gate delays does a hardware XOR tree need?
- 8
- 3
- 1
- 64
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Build a 4-input parity circuit from XOR gates in the logic lab, first as a chain (three XORs in a row) then as a balanced tree. Check the truth tables match, and count the gate levels from input to output in each.
What the interactive shows, in words
In the logic lab, a 4-input parity chain is XOR(XOR(XOR(A, B), C), D): 3 gate levels. A balanced tree is XOR(XOR(A, B), XOR(C, D)): 2 levels. Both give 1 when an odd number of inputs are 1.
Understand
What co-design means
Co-design decides together which functions run as software on a processor and which become dedicated hardware (an accelerator, a peripheral, an FPGA block), and designs the interface between them. Software is flexible and cheap to change; hardware is fast and energy-efficient for a fixed job but costs area, design effort and verification.
When hardware wins
Good candidates are hot (a large share of run time), stable (the algorithm won't change), regular (lots of parallel, simple operations, like filtering, encryption or matrix multiply) and data-local (little traffic in and out). Poor candidates are rarely run, branchy or still evolving.
Count before you build
Profile first: measure where time goes. Use Amdahl's law to bound the gain. Then estimate the hardware: gates or multipliers needed, its latency in gate delays or cycles, and the data movement cost. The parity example shows the typical shape: software Θ(n) instructions, hardware Θ(log n) gate delays but Θ(n) gates.
Explain it another way: intuitive
A kitchen buys a dough mixer because bread takes most of the morning, not a special egg-cracker for the one omelette a day.
Explain it another way: technical
Partitioning is an optimisation over latency, throughput, energy, area and flexibility, subject to interface bandwidth. Typical interfaces are memory-mapped registers, DMA and shared buffers. Hardware–software interfaces must be specified precisely so both sides can be verified independently.
Explain it another way: mathematical
Amdahl: S = 1/((1 − p) + p/s + c), where c is the communication overhead as a fraction of the original time. With p = 0.6, s = 20, c = 0.05: S = 1/(0.4 + 0.03 + 0.05) ≈ 2.08×.
Explain it another way: applied
Microcontrollers include hardware CRC units, timers, PWM generators and DMA because those tasks are simple, constant and frequent. The robot's control logic stays in software, where it can be retuned.
Derivation: Amdahl's law
Let the original run time be 1, and let a fraction p of it be the part you accelerate.
The accelerated part becomes s times faster, so it takes p/s. The rest still takes 1 − p.
New time = (1 − p) + p/s, so overall speed-up S = 1 / ((1 − p) + p/s).
As s → ∞, S → 1/(1 − p). If only 50% of the time is accelerated, no accelerator can beat 2×.
Example: p = 0.8, s = 50: S = 1/(0.2 + 0.016) ≈ 4.6×. Doubling s to 100 only gives 4.8×: optimise the other 20% next.
Add the cost of moving data to and from the accelerator to the new time and the speed-up falls further.
Try these examples
Example 1
A rover's image pipeline spends 70% of its time in a 3×3 convolution. An accelerator makes convolution 30× faster but adds data copies costing 5% of the original time. Overall speed-up?
The worked solution is in the online lesson.
Common mix-ups
Making the slowest function 100× faster makes the program nearly 100× faster.
✓ Only the accelerated fraction shrinks; the rest sets a hard ceiling of 1/(1 − p).Hardware is always better than software.
✓ Hardware is faster for fixed, regular work but costs area, energy for idle logic, design time and flexibility.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. 80% of a program's run time is moved onto a hardware accelerator that makes that part 2× faster. What is the overall speed-up?
Answer: ×
2. 50% of a program's run time is moved onto a hardware accelerator that makes that part 20× faster. What is the overall speed-up?
Answer: ×
3. Which function is the best candidate for a hardware accelerator in a drone?
- The menu system of its phone app
- A fixed FIR filter run on every IMU sample at 8 kHz
- The mission planner that changes every flight
- Error logging that runs once per crash
4. How many levels of 2-input XOR gates does a balanced parity tree need for a 32-bit word?
Answer: levels
5. A task is 40% accelerable. What is the best overall speed-up any accelerator can give?
- 1.4×
- About 1.67×
- 2.5×
- Unlimited
Apply it
Pick one subsystem from a robot you know (sensing, estimation, control, communication). Estimate (with stated assumptions) the fraction of CPU time each function takes, then argue which single function you would move into hardware, the Amdahl bound on the gain, and what interface it would need.
Reflect
What does your software do that you would be happy to freeze into silicon forever, and what would you never freeze?
Inside an integrated circuit
A processor die the size of a fingernail holds billions of transistors and kilometres of wire. How is something that complex designed at all?
Why it matters
Every algorithm you write eventually runs on a physical object whose wires have resistance, whose clock takes time to arrive and whose area costs money. Knowing the chip's architecture explains why some designs are fast, others hot, and others simply too expensive to make.
Goals
- Describe a chip's physical architecture: die, standard cells, rows, metal interconnect layers, I/O pads and packaging.
- Explain clock distribution, clock skew and why wires, not transistors, often limit speed.
- Outline the digital design flow from RTL to layout and the power–performance–area trade-offs at each step.
Predict
As transistors shrank over the last decades, which got relatively worse?
- Transistor switching speed
- The delay of long wires across the chip
- The number of transistors per mm²
- Nothing: everything improved
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the Silicon Studio. Find (or build) a small logic block and look at how it is described: which parts are logic cells, which are wires and which are flip-flops on the clock. Note anything the studio says about delay or area, and list three things that would change if the block were twice as big.
What the interactive shows, in words
A chip floorplan: rows of equal-height standard cells in the core, SRAM blocks beside them, I/O pads around the edge, and metal layers above. A clock tree branches from one input to every flip-flop; long wires are broken by repeaters.
Understand
Die, cells and rows
The die is the rectangle of silicon that becomes one chip. Digital logic is built from a standard-cell library: pre-designed, pre-characterised gates and flip-flops (NAND2, INV, DFF, …) of equal height, placed in rows like bricks so their power rails line up. Memories (SRAM macros), analogue blocks and I/O pads around the edge complete the floorplan.
Interconnect
Cells are joined by many layers of metal interconnect (often 10 or more) separated by insulator and linked by vias. Lower layers are thin and dense for short local wires; upper layers are thick for long routes, power and clock. Wire delay grows roughly with the square of length for an unbuffered RC wire, so long nets are split with repeater buffers.
Clock distribution
Every flip-flop must see the clock edge at nearly the same moment. A clock tree (or mesh) of buffers fans the clock out from one source to millions of flip-flops. The difference in arrival times is skew; it eats into the time available for logic. The clock network switches every cycle, so it can take a large share of dynamic power, which is why designers clock-gate idle blocks.
The design flow
Engineers write RTL (register-transfer level code), simulate it, synthesise it into a netlist of standard cells, then place and route it, check timing (every path must fit in the clock period), power and manufacturing rules, and finally send the layout to the fab. Each step trades power, performance and area (PPA).
Explain it another way: intuitive
A chip is a city: standard cells are identical terraced houses in streets, metal layers are roads stacked on flyovers, and the clock tree is a city-wide bell that must ring in every house at the same instant.
Explain it another way: technical
Static timing analysis checks setup: t_clk ≥ t_clk→Q + t_logic + t_wire + t_setup + t_skew, for every register-to-register path. Hold checks guard against data arriving too early. Synthesis maps RTL onto library cells; place-and-route optimises wirelength and timing.
Explain it another way: mathematical
A distributed RC wire of length L has delay ≈ 0.38·r·c·L², with r and c per unit length. Doubling L quadruples delay; splitting it into k buffered segments gives delay ∝ k·(L/k)² + k·t_buf = L²/k + k·t_buf, minimised at k ∝ L.
Explain it another way: applied
Large processors have separate clock domains and power domains so idle cores can be clock-gated or switched off; phone chips combine CPU cores, GPU, modem and accelerators on one die (a system-on-chip) to cut data movement.
Try these examples
Example 1
A register-to-register path has clock-to-Q 50 ps, logic 600 ps, wire 150 ps, setup 40 ps and skew 30 ps. What is the maximum clock frequency?
The worked solution is in the online lesson.
Common mix-ups
Chip speed is limited only by how fast transistors switch.
✓ Wires, clock skew and setup times are part of every path; on modern chips long wires are often the limit.Engineers draw every transistor by hand.
✓ Digital chips are described in RTL and built from standard cells by synthesis and place-and-route tools; people design the architecture, constraints and verification.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Why are standard cells all the same height?
- So they look tidy
- So they can be placed in rows sharing power and ground rails
- Because transistors are all the same size
- To make them slower
2. A critical path totals 400 ps of logic and wire, plus 60 ps clock-to-Q, 40 ps setup and 25 ps skew. Maximum clock frequency in GHz?
Answer: GHz
3. An unbuffered wire 1 mm long has 20 ps delay. Using the RC model (delay ∝ L²), what is the delay of a 3 mm wire?
Answer: ps
4. Why does clock gating an idle block save power?
- It lowers the supply voltage
- Its flip-flops and clock buffers stop switching, so no dynamic power is spent on them
- It removes leakage completely
- It makes the clock faster elsewhere
5. A chip switches an effective capacitance of 1 nF with activity factor α = 0.3, at 0.7 V and 2 GHz. What is its dynamic power in watts?
Answer: W
Apply it
Write a one-page floorplan proposal for a small robot controller chip: a CPU core, 64 KB SRAM, a PWM block, an ADC and I/O pads. Sketch where each goes, which wires are long, where the clock enters and which blocks you would clock-gate, and justify each choice in PPA terms. (Conceptual only: no fabrication.)
Reflect
Which physical limit of chips would you most like to see solved, and what would it let you build?
Wafers, lithography and yield
A wafer full of chips comes out of the fab. Some dies work and some don't, and the bigger the chip, the worse the odds. Why?
Why it matters
Chip economics is ruled by yield. It explains why designers fight for every square millimetre, why leading-edge chips are expensive, and why large processors are now assembled from several smaller chiplets. These are simplified models; real fabs guard their numbers closely.
Goals
- Describe the manufacturing sequence: wafer, photolithography, etching, deposition, doping, testing, dicing and packaging.
- Estimate dies per wafer and yield with the Poisson model Y = e^(−D·A).
- Compute cost per good die and explain why die area drives cost faster than linearly.
Safety: Semiconductor fabrication uses hazardous chemicals, gases and high-energy equipment in specialist cleanrooms. This lesson is conceptual and simulation-based only; do not attempt any part of it physically.
Predict
Doubling a die's area (same wafer, same defect density). What happens to the number of working dies per wafer?
- Halves exactly
- Falls by more than half
- Stays the same
- Falls by less than half
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Fix the defect density at 0.1 per cm² and sweep die area from 20 to 600 mm². Watch yield and cost per good die. Then fix the area at 400 mm² and halve the defect density: how much cheaper does each die get?
What the interactive shows, in words
The explorer draws a circular wafer tiled with square dies, defects as random dots, and dies with a defect shown in red (also counted in text). For 300 mm, 100 mm² dies and 0.1 defects/cm², the formula gives 640 dies, yield 90.5% and about 579 good dies.
Understand
From sand to wafer
Ultra-pure silicon is grown as a single crystal ingot and sliced into polished wafers, today usually 300 mm across. Each wafer carries hundreds of copies of the chip, called dies, side by side.
Photolithography, layer by layer
A light-sensitive photoresist is spun on, exposed through a patterned mask (reticle) with deep-ultraviolet or extreme-ultraviolet light, and developed. The exposed pattern then guides etching, deposition of new material, or doping (implanting atoms to change conductivity). Repeating this for dozens of layers builds transistors at the bottom and metal wiring above. A process node (for example '7 nm' or '3 nm') names a technology generation; the number no longer equals any single physical dimension.
Test, dice, package
Finished wafers are probed: each die is tested electrically and failures are marked. The wafer is diced, good dies are packaged (bonded to a substrate with pins or balls) and tested again. Defects (a particle, a lithography error) kill dies at random, which is what the yield model captures.
Why area is expensive
Bigger dies mean fewer per wafer and lower yield, so cost per good die grows faster than area. Edge loss adds to it: square dies can't tile a circle. That is why designers fight for area, why the same design gets cheaper as a process matures and D falls, and why chiplets split a big design into several small, high-yield dies.
Explain it another way: intuitive
Sprinkle a few crumbs at random over a tray of biscuits. Small biscuits: most stay clean. One giant biscuit: it almost certainly catches a crumb.
Explain it another way: technical
Yield components: line yield (wafers surviving the process), die yield (defect-limited, the model here), parametric yield (dies too slow or too leaky) and packaging/test yield. Total cost includes wafer, test, packaging and yield loss at each step.
Explain it another way: mathematical
C_die = C_wafer / (DPW · e^(−DA)). For small DA, e^(−DA) ≈ 1 − DA; for large DA the exponential dominates. d ln C/d A ≈ 1/A + D: cost grows faster than area by the extra factor e^(DA).
Explain it another way: applied
Several recent desktop and server processors combine multiple compute chiplets with a separate I/O die in one package, partly because small dies yield much better than one huge monolithic die.
Derivation: Where e^(−D·A) comes from
Assume killer defects land independently and uniformly on the wafer, D per cm² on average.
Then the number of defects k on one die of area A follows a Poisson distribution with mean λ = D·A.
P(k) = λ^k e^(−λ) / k!. A die works only if k = 0, so Y = P(0) = e^(−D·A).
Example: D = 0.1 /cm², A = 100 mm² = 1 cm²: Y = e^(−0.1) ≈ 90.5%. At 4 cm², Y = e^(−0.4) ≈ 67%.
Good dies per wafer = DPW × Y, with DPW ≈ π(d/2)²/A − πd/√(2A). Cost per good die = wafer cost ÷ (DPW × Y).
Real defects cluster, so fabs often use the negative-binomial model, which gives higher yield for large dies than Poisson. The trend is the same.
Try these examples
Example 1
300 mm wafer, 100 mm² dies, D = 0.1 /cm², wafer cost $10,000 (illustrative). Cost per good die?
The worked solution is in the online lesson.
Common mix-ups
Doubling die area doubles the cost per chip.
✓ It more than doubles it: fewer dies per wafer and lower yield multiply.The node number is the size of the transistors.
✓ It is a generation label; physical dimensions differ and are not one number.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. With a Poisson yield model Y = e^(−D·A), what percentage of 20 mm² dies work when the defect density is 0.3 defects per cm²?
Answer: %
2. Estimate the whole dies on a 200 mm wafer for a 200 mm² die using DPW = π(d/2)²/A − πd/√(2A). Round down.
Answer: dies
3. A processed 300 mm wafer costs $5000 (an illustrative figure). It holds 306 dies of 200 mm², and the defect density is 0.1 per cm² (yield Y = e^(−D·A)). What is the cost per good die in dollars?
Answer: $
4. Which order is right for patterning one layer?
- Etch, expose, coat resist, develop
- Coat resist, expose through a mask, develop, etch or deposit
- Dice, expose, etch, package
- Dope, dice, coat, expose
5. What does a process node name such as '5 nm' mean today?
- Every transistor gate is exactly 5 nm long
- A technology generation label; it no longer matches a single physical dimension
- The wafer is 5 nm thick
- The chip runs at 5 GHz
6. With D = 0.2 /cm², what is the yield (as a percentage) of one 6 cm² monolithic die? (Four 1.5 cm² chiplets would each yield 74%.)
Answer: %
Apply it
Using the explorer, find the die area at which cost per good die doubles compared with a 50 mm² die, for D = 0.1 and D = 0.5 per cm². Write a short memo (with the numbers and the model's assumptions) recommending a monolithic or chiplet approach for a 500 mm² design.
Reflect
What is one design decision you have made that would look different if every square millimetre cost money?
Week 23: Embedded machine learning concepts
This week you will
- Describe training versus inference and why inference must fit memory, time and energy budgets.
- Count MACs and memory footprint of a small network.
- Explain int8 quantisation and measure its accuracy cost.
Training versus inference: counting the cost
Training a speech model took a data centre. Running it fits on a chip in a light switch. What makes the two so different?
Why it matters
Keyword spotting, gesture detection, predictive maintenance and visual wake-up all run small neural networks on microcontrollers. Whether a model fits is a calculation, not a guess: MACs for time and energy, bytes for memory.
Goals
- Distinguish training from inference and explain why only inference must run on the device.
- Count multiply-accumulate operations (MACs) for dense and convolutional layers.
- Estimate a model's latency from MACs and a device's MAC rate, and list its memory needs (weights and activations).
Predict
A layer connects 128 inputs to 64 outputs. How many multiplications does one inference through it need (ignoring biases)?
- 192
- 8,192
- 128
- 64
Write down your guess and your reason. The reveal is in the online lesson.
Discover
The Nibble machine has no multiply instruction: your Level 4 program multiplies by repeated addition. Count how many instructions one 4-bit multiply takes, then estimate how many instructions a single 8,192-MAC layer would need on such a machine. That is why real chips have hardware multipliers and MAC units.
What the interactive shows, in words
The Nibble machine task can be done on paper: multiplying x by y with repeated addition runs the loop y times, about 7 instructions each, so one 4-bit multiply costs tens of instructions. A layer of 8,192 MACs would need hundreds of thousands.
Understand
Two phases
Training searches for weights that minimise a loss over a dataset, using many passes of forward computation, gradient computation and updates: expensive, done once on big hardware. Inference runs one forward pass with fixed weights on a new input: much cheaper, done millions of times, often on the device itself for latency, privacy or battery reasons.
Counting MACs
A multiply-accumulate does y ← y + w·x. A dense layer with a inputs and b outputs costs a·b MACs. A convolution producing an H×W×C_out output with k×k kernels over C_in channels costs H·W·C_out·k²·C_in. Add the layers. Activations (ReLU) and pooling are usually small by comparison.
Memory: weights and activations
Weights must be stored somewhere, usually flash: one value per connection. Activations (the intermediate results) must fit in RAM while a layer runs: roughly the largest input plus output of any layer. A microcontroller with 1 MB flash and 256 KB RAM sets hard limits on both.
From MACs to milliseconds
Latency ≈ MACs ÷ (MACs per cycle × clock rate), plus memory stalls. A core doing 1 MAC per cycle at 100 MHz runs a 2 million-MAC model in about 20 ms. Vector (SIMD) instructions or a small accelerator can do 4–8 MACs per cycle at 8 bits.
Explain it another way: intuitive
Training is writing a recipe book by cooking thousands of trial dishes. Inference is following one recipe once: much quicker, and you can do it in a tiny kitchen.
Explain it another way: technical
A forward pass computes y = f(Wx + b) layer by layer. Training adds backpropagation, roughly 2–3× the forward cost, plus storing activations for the backward pass and many epochs over the data.
Explain it another way: mathematical
Total MACs = Σ_layers (fan-in × outputs). For a 3×3 conv, 16 → 32 channels on a 32×32 map: 32·32·32·9·16 = 4,718,592 MACs. A 1×1 conv on the same map: 524,288, nine times fewer, which is why efficient networks use depthwise-separable convolutions.
Explain it another way: applied
A typical keyword-spotting model for microcontrollers has tens of thousands of weights and a few million MACs per second of audio, small enough to run continuously on a coin-cell-friendly chip.
Try these examples
Example 1
A network: 49×10 audio features flattened (490 inputs) → dense 64 → dense 12. MACs and weights?
The worked solution is in the online lesson.
Common mix-ups
Running a model costs as much as training it.
✓ One inference is a single forward pass; training is many passes plus gradients over a whole dataset.Only the number of weights matters.
✓ A convolution reuses few weights many times: MACs, not weights, set its time; activations set its RAM.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A convolution layer takes a 8×8 image with 8 channels and produces a 8×8 output with 32 channels using 5×5 kernels. How many MACs does it need?
Answer: MACs
2. A network has two fully connected layers: 784 inputs → 16 hidden units → 2 outputs. How many multiply-accumulate operations (MACs) does one inference need (ignore biases and activations)?
Answer: MACs
3. Which phase normally runs on a battery-powered sensor?
- Training
- Inference
- Both, equally
- Neither
4. A model needs 3,000,000 MACs. The core does 2 MACs per cycle at 80 MHz. Ignoring memory stalls, what is the latency in ms?
Answer: ms
5. A neural network has 600000 weights stored at 16 bits each. How many kilobytes (1 KB = 1024 bytes) do the weights occupy?
Answer: KB
Apply it
Design (on paper) a classifier for 3-axis accelerometer gestures sampled at 50 Hz in 2 s windows. Choose layer sizes, count MACs and weights, and check it against a budget of 100 KB flash, 32 KB RAM and 10 ms on a 64 MHz core doing 1 MAC per cycle. State every assumption.
Reflect
If a device can't run your model in time, which would you change first: the model, the precision or the hardware? Why?
Quantisation: fewer bits, smaller models
Store every weight in 8 bits instead of 32 and the model is four times smaller. How much accuracy do you lose? Sometimes almost none.
Why it matters
int8 quantisation is the standard way to fit networks onto phones and microcontrollers: 4× less memory, cheaper integer MACs and lower energy per operation. Knowing how it works, and how to measure what it costs, is core embedded-ML engineering.
Goals
- Quantise real values to b-bit integers with a scale factor and recover them (dequantise).
- Relate bit width to rounding error, memory footprint and the cost of arithmetic.
- Measure, rather than assume, the accuracy cost of quantisation on held-out data.
Predict
Weights range from −0.5 to +0.5 and are stored as symmetric int8 (−127…127). What is the largest rounding error on any weight?
- About 0.002
- About 0.04
- 0.5
- Zero
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Sweep the bits from 16 down to 2 and read the accuracy curve. Find the smallest bit width that stays within 1 percentage point of float. Then set 1,000,000 parameters and find the smallest width that fits the 256 KB budget. Do the two answers agree?
What the interactive shows, in words
The explorer plots accuracy of a toy classifier against bit width: 90.25% in float and at 8, 12 and 16 bits, 90% at 6 bits, about 89% at 3 and 4 bits, and about 74% at 2 bits. Footprint = parameters × bits ÷ 8; one million int8 weights take about 977 KB, so they do not fit a 256 KB budget.
Understand
Scale and zero point
A quantised tensor stores small integers plus one scale (and sometimes a zero point for asymmetric ranges, useful for ReLU outputs that are never negative). Per-channel scales, one per output channel, often keep accuracy much better than one scale for the whole layer.
Why accuracy often survives
A trained network is robust to small perturbations of its weights; int8 errors are tiny compared with the spread of the weights. Below about 4 bits, errors become comparable to the weights themselves and decisions start to flip. Outliers matter too: one huge weight stretches the scale and wastes resolution on everyone else.
Measure on held-out data
Compare float and quantised accuracy on the same held-out test set, report both with their uncertainty, and look at which inputs changed class. Calibration (choosing scales from representative data) and quantisation-aware training can recover accuracy at low bit widths. The explorer's toy classifier shows the trend only.
Explain it another way: intuitive
Measuring a room in whole centimetres instead of micrometres: the furniture still fits, and the notebook is much shorter. Measure in whole metres and things stop fitting.
Explain it another way: technical
Post-training quantisation maps float32 weights (and activations, with calibration) to int8. Kernels use int8 × int8 → int32 accumulation and requantise outputs. Hardware SIMD instructions run several int8 MACs per cycle.
Explain it another way: mathematical
For weights with max|w| = 1: b = 8 gives s = 1/127 and RMS error ≈ 0.0023; b = 4 gives s = 1/7 and RMS error ≈ 0.041. Footprint = N·b/8 bytes.
Explain it another way: applied
Mobile and microcontroller ML frameworks routinely ship int8 models; many microcontroller cores include DSP instructions that perform two or four 8- or 16-bit MACs in one cycle.
Derivation: Symmetric uniform quantisation and its error
Choose a scale s = max|w| / (2^(b−1) − 1), so the largest weight maps to the largest integer.
Quantise: q = round(w / s), clamped to the b-bit range. Dequantise: ŵ = q·s.
The rounding error e = ŵ − w lies in [−s/2, s/2]. If it is roughly uniform, its RMS is s/√12.
Each extra bit halves s, so it halves the error: about 6 dB better signal-to-quantisation-noise per bit.
Integer MACs: Σ wᵢxᵢ ≈ s_w s_x Σ q_w q_x. The sum runs in integers (with a 32-bit accumulator) and one rescale happens at the end.
Try these examples
Common mix-ups
Quantisation always destroys accuracy.
✓ At 8 bits the loss is often small; it must be measured, and grows quickly below about 4 bits.Quantising to 8 bits makes inference exactly 4× faster.
✓ Memory shrinks 4×; speed depends on hardware support for int8 MACs and on memory traffic.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Weights lie in [−2, 2] and are quantised to symmetric int8 with qmax = 127. What is the scale (step size)?
Answer:
2. A neural network has 50000 weights stored at 4 bits each. How many kilobytes (1 KB = 1024 bytes) do the weights occupy?
Answer: KB
3. With scale 0.02, what integer does w = −0.537 quantise to (round to nearest)?
Answer:
4. One weight in a layer is 50× larger than all the others. What happens with a single per-layer int8 scale?
- Nothing: int8 is exact
- Most small weights round to a handful of levels near zero, losing resolution
- The large weight is clipped to zero
- Footprint grows
5. Which evaluation of an int8 model is fair?
- Accuracy on the training set
- Accuracy of float and int8 models on the same held-out test set, with uncertainty
- Accuracy on whichever test examples int8 gets right
- Model size only
Apply it
Quantise a small set of filter coefficients (for example, the FIR or complementary filter you used in Term 2) to 16, 8 and 4 bits in the Code Lab. Measure the output error on the same test signal for each and decide which width you would ship, against an error requirement you write down first.
Reflect
Where else in engineering do you trade precision for size or speed?
Fitting a model into memory, time and energy
A smartwatch must recognise a gesture in 20 ms, using under 1 mJ, with 64 KB of RAM. Can your model do it? Work it out before you build it.
Why it matters
Embedded ML projects fail most often on budgets, not on accuracy. A few lines of arithmetic, done early, decide whether a design is possible and which knob to turn. This is the habit research engineers bring to any resource-constrained system.
Goals
- Build a budget table for an on-device model: flash, RAM, latency and energy per inference.
- Estimate energy per inference from MAC count and memory traffic, and explain why data movement often dominates.
- Choose between shrinking the model, lowering precision and changing hardware with evidence.
Predict
On a typical small chip, which costs more energy: one 8-bit MAC, or reading one byte from off-chip DRAM?
- The MAC, by far
- About the same
- The DRAM read, by roughly 100× or more
- Neither uses energy
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, write a function that takes a list of layer sizes and returns MACs, weight bytes (at a chosen bit width), peak activation bytes and energy per inference for given pJ/MAC and pJ/byte. Test it on the network from the worked example, then search for the largest hidden layer that fits a 1 mJ, 64 KB RAM budget.
What the interactive shows, in words
A budget table has four rows: flash (weights and code), RAM (peak activations), latency (MACs ÷ MAC rate) and energy (MACs × energy per MAC + bytes × energy per byte). The worked example needs 0.67 ms and 0.92 µJ, mostly from reading weights.
Understand
The budget table
Write one row per resource: flash (weights + code), RAM (peak activations + buffers + stack), latency (MACs ÷ MAC rate + overheads) and energy (MAC energy + memory energy + idle energy). Each has a limit from the product requirement. The design is feasible only if every row fits, with a margin.
Energy per inference
E ≈ MACs × e_MAC + bytes moved × e_byte + P_idle × time. Because e_byte can be tens to hundreds of times e_MAC (depending on which memory), a model with fewer weight reads can beat one with fewer MACs. Reusing data already in registers or SRAM is the key trick of efficient accelerators.
Which knob?
Too big for flash: quantise or prune. Too big for RAM: process in smaller tiles, or choose layers with smaller activations. Too slow: fewer MACs, SIMD instructions or an accelerator. Too much energy: reduce data movement, then MACs, then duty-cycle the device. Each change must be re-checked against accuracy on held-out data.
Explain it another way: intuitive
Packing for a flight with a weight limit, a size limit and a time limit at security. Every item must pass all three, and the heavy boots matter more than the socks.
Explain it another way: technical
Roofline thinking: performance is limited either by compute (MACs per second) or by memory bandwidth (bytes per second × operations per byte). Arithmetic intensity, MACs per byte moved, tells you which.
Explain it another way: mathematical
Example: 2×10⁶ MACs at 1 pJ = 2 µJ; 200 KB of weights read from flash at 20 pJ/byte = 4 µJ; total 6 µJ. Quantising to 4 bits halves the weight bytes: 2 + 2 = 4 µJ, a 33% saving with no change in MACs.
Explain it another way: applied
Always-on audio wake-word detectors often run a tiny first-stage model continuously and wake a larger model (or the main processor) only when it fires: a cascade that keeps average energy low.
Try these examples
Example 1
Budget check: 32,128 MACs and 32 KB of int8 weights; 1 MAC/cycle at 48 MHz; 3 pJ/MAC; 25 pJ/byte from flash. Latency and energy?
The worked solution is in the online lesson.
Common mix-ups
Fewer MACs always means less energy.
✓ Memory traffic often costs more than arithmetic; a model with more MACs but more data reuse can use less energy.If it fits in flash, it fits.
✓ RAM for activations, latency and energy are separate budgets that must each be met.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. One inference performs 1000000 MACs at 0.2 pJ each and reads 50000 bytes from memory at 100 pJ per byte. What is the energy per inference in microjoules (µJ)?
Answer: µJ
2. One inference performs 50000 MACs at 3 pJ each and reads 10000 bytes from memory at 5 pJ per byte. What is the energy per inference in microjoules (µJ)?
Answer: µJ
3. A network has two fully connected layers: 64 inputs → 32 hidden units → 4 outputs. How many multiply-accumulate operations (MACs) does one inference need (ignore biases and activations)?
Answer: MACs
4. Your model's weights fit in flash, but one layer's input and output activations together exceed RAM. What is the most direct fix?
- Quantise the weights further
- Process the layer in tiles, or redesign it with smaller activations
- Raise the clock
- Train for longer
5. A 200 mAh, 3 V coin cell stores about 2,160 J. If each inference costs 5 µJ and nothing else used energy, how many inferences is that? (Answer in millions.)
Answer: million
Apply it
Write a one-page feasibility study for an on-device classifier of your choice: requirement, budget table with every assumption and its source, the calculation, and a recommendation. Mark every number you have not measured as an estimate.
Reflect
Which budget row would you have forgotten if you had started by training the model?
The perceptron: one neuron draws one line
The first learning machine, built in 1958, could tell shapes apart by nudging a few numbers. What exactly was it nudging, and what could it never learn?
Why it matters
Every neural network, from a keyword spotter on a microcontroller to a large language model, is built from units that compute a weighted sum and pass it through a simple function. The perceptron is that unit at its plainest. Understanding what one neuron can and cannot separate tells you why networks need layers, and how few multiplications a tiny on-device classifier really needs.
Goals
- Compute a perceptron's weighted sum and output from weights, bias and inputs.
- Interpret w·x + b = 0 as a decision boundary and say what the weights and bias do to it.
- Apply the perceptron learning rule and explain why it cannot learn XOR.
Predict
A perceptron classifies points on a flat 2-D plot. What shape is the border between the region it labels 1 and the region it labels 0?
- A circle
- A straight line
- Any curve it likes, after enough training
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Use the separable dataset with η = 0.5 and press “Show next example” repeatedly. Watch the line jump only when a point is misclassified. Then switch to the XOR pattern and run several full passes: does it ever settle?
What the interactive shows, in words
The perceptron diagram plots six points on a 0–5 grid: class 0 (circles) at (1, 1), (2, 1) and (1, 3); class 1 (squares) at (3, 4), (4, 2) and (4, 4). Weights start at zero. Each step shows one example; if it is misclassified the weights and bias change by η(t − y)x and the decision line moves. The readout gives the weights, the bias and how many points are misclassified; on this set it reaches zero. On the XOR set ((1, 1) and (4, 4) class 0; (1, 4) and (4, 1) class 1) at least one point is always wrong.
Understand
Weighted sum, bias, step
A perceptron takes inputs x₁, x₂, … and computes z = w₁x₁ + w₂x₂ + … + b. The weights say how much each input matters (and in which direction); the bias b shifts the result. A step function then decides: output 1 if z ≥ 0, else 0. With w = (2, 1) and b = −6, the input (3, 1) gives z = 6 + 1 − 6 = 1, so output 1; the input (1, 2) gives z = −2, so output 0.
The decision boundary is a line
The output switches where z = 0: for two inputs, w₁x₁ + w₂x₂ + b = 0 is a straight line. With w = (2, 1), b = −6 it is 2x₁ + x₂ = 6, through (3, 0) and (0, 6). The weight vector points across the line towards the class-1 side; scaling all weights and bias together changes nothing about the line. Changing b slides the line without turning it.
Learning by fixing mistakes
The perceptron rule looks at one example at a time. If it is right, nothing changes. If it is wrong, each weight moves by η(t − y)xᵢ and the bias by η(t − y), where t is the target, y the output and η the learning rate. A missed 1 (t − y = +1) adds the input to the weights, raising z for that input next time; a false 1 subtracts it. If a separating line exists, this is guaranteed to find one.
The XOR wall
XOR labels (0, 0) and (1, 1) as one class and (0, 1) and (1, 0) as the other. No straight line separates them, so a single perceptron keeps getting at least one point wrong forever. Adding a hidden layer of neurons fixes this: two lines combined can carve out the diagonal pair. That insight, and a way to train hidden layers, is what turned perceptrons into neural networks.
Explain it another way: intuitive
Think of a referee with a ruler laid across a pitch: everything on one side is “in”, everything on the other is “out”. Each time the referee gets a call wrong, the ruler is nudged towards that point. A ruler can turn and slide, but it can never bend round a corner.
Explain it another way: technical
A perceptron is a linear classifier: y = H(wᵀx + b) with H the Heaviside step. The rule is stochastic gradient descent on the perceptron criterion and converges in a finite number of updates when the data are linearly separable (Novikoff's theorem bounds the number of mistakes by (R/γ)², where R is the data radius and γ the margin). On non-separable data it never stops changing.
Explain it another way: mathematical
z = w·x + b. Boundary: {x : w·x + b = 0}, a hyperplane with normal w at signed distance −b/‖w‖ from the origin. Update on a mistake: w ← w + η(t − y)x, b ← b + η(t − y). Example: w₁ = 0.5, η = 0.5, x₁ = 3, t = 1, y = 0 gives w₁ = 0.5 + 0.5 × 1 × 3 = 2.0.
Explain it another way: applied
A microcontroller can run a perceptron on three accelerometer features with three multiplications, two additions and a comparison per reading: microseconds and a few bytes of weights. Many on-device “is the machine vibrating abnormally?” detectors start as exactly this before anyone reaches for a deep network.
Try these examples
Example 2
The perceptron above wrongly outputs 1 for (4, 1), whose target is 0. Apply one update with η = 0.5.
The worked solution is in the online lesson.
Common mix-ups
A perceptron can learn any pattern if you train it long enough.
✓ It can only learn patterns a straight line (a hyperplane) separates. XOR needs a hidden layer.The perceptron rule changes the weights after every example.
✓ It changes them only when the example is misclassified; correct answers leave the weights alone.Bigger weights mean a better classifier.
✓ Multiplying all weights and the bias by the same positive number leaves the boundary exactly where it was.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A perceptron has weights w₁ = 1 and w₂ = −5 and bias b = 0. For the input (x₁, x₂) = (4, 4), what is the weighted sum z = w₁x₁ + w₂x₂ + b?
Answer:
2. A perceptron has w₁ = 1, w₂ = −2 and b = 3. What is z for the input (x₁, x₂) = (4, 1)?
Answer:
3. You increase a perceptron's bias b and leave the weights alone. What happens to its decision line?
- It rotates
- It slides parallel to itself
- It bends
4. Why can a single perceptron never classify all four XOR points correctly?
- The learning rate is too small
- No straight line separates the two classes
- It needs more training passes
5. A perceptron misclassifies an example. Its weight is w₁ = 0.7, the learning rate is η = 0.2, the input is x₁ = −4, the target is t = 0 and the perceptron output y = 1. Using w₁ ← w₁ + η(t − y)x₁, what is the new w₁? (2 decimal places)
Answer:
Apply it
Find, by hand, weights and a bias that make a perceptron compute logical AND on inputs 0 and 1 (output 1 only for (1, 1)). Then do OR. Explain in two sentences why no choice works for XOR, and sketch how two perceptrons feeding a third could.
Reflect
What does a perceptron's weight vector “point at”, and why does adding the input to the weights after a missed 1 make that input score higher next time?
Gradient descent on a one-neuron network
A network with millions of weights learns by asking one question of each weight: “if I nudge you, does the error go up or down?” How is that question answered?
Why it matters
Training is just repeated small corrections. The perceptron's rule only works for a hard step; real networks use smooth activations so that calculus can say exactly how much each weight is to blame. Do it once by hand for one neuron and backpropagation stops being magic: it is the chain rule, applied layer by layer.
Goals
- Write the squared-error loss for one sigmoid neuron and derive ∂L/∂w with the chain rule.
- Carry out one gradient-descent update by hand and check that the loss falls.
- Explain what happens when the learning rate is too small or too large.
Predict
You double the learning rate of a model that was training slowly but steadily. What is the risk?
- None: it will just train twice as fast
- The steps may overshoot the minimum and the loss can grow
- The model will forget its data
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start at w₀ = −1. Take steps with η = 0.1, then 0.5, then 0.9, then 1.05. For each, count steps until the readout says converged, or note when it never does.
What the interactive shows, in words
The gradient-descent diagram plots the loss L(w) = (w − 3)² + 1 as a U-shaped curve with its lowest point at w = 3. Each press of Take one step moves w by −η × 2(w − 3) and marks the new point. From w₀ = −1: with η = 0.1 the points creep towards 3; with η = 0.5 the first step lands exactly on 3; with η = 0.9 they zig-zag across the minimum but settle; with η = 1.05 each zig-zag is wider and the readout warns that training is diverging.
Understand
A smooth neuron and its loss
Replace the hard step with the sigmoid σ(z) = 1/(1 + e^(−z)), which glides from 0 to 1. One neuron computes y = σ(wx + b). To measure how wrong it is on an example with target t, use the squared-error loss L = ½(y − t)². The ½ is only there to cancel a 2 when we differentiate. Training means choosing w and b to make L small across the data.
Blame by the chain rule
L depends on w only through z and y, so ∂L/∂w = (∂L/∂y)(∂y/∂z)(∂z/∂w) = (y − t) · y(1 − y) · x. Each factor has a meaning: how wrong the output is, how sensitive the sigmoid is at this point (at most 0.25, at z = 0), and how big the input was. A zero input gets no blame. The same idea, repeated backwards through layers, is backpropagation.
One step downhill
Gradient descent updates w ← w − η·∂L/∂w: move against the gradient, scaled by the learning rate η. Take w = 0.5, b = 0, x = 2, t = 1. Then z = 1, y ≈ 0.7311, ∂L/∂w ≈ (−0.2689)(0.1966)(2) ≈ −0.1058. With η = 1, w becomes ≈ 0.6058 and the loss falls from ≈ 0.0362 to ≈ 0.0263. Negative gradient, so w went up.
Choosing the learning rate
For the bowl L(w) = (w − 3)², each step multiplies the distance from the minimum by (1 − 2η). With η = 0.1 the distance shrinks by 0.8 per step: safe but slow. η = 0.5 lands exactly on the minimum. Between 0.5 and 1 it overshoots but still settles; above 1 the distance grows every step and training diverges. Real loss surfaces are not perfect bowls, which is why η is tuned and often decreased over time.
Explain it another way: intuitive
You are on a foggy hillside and want the valley floor. You can only feel the slope under your feet, so you step downhill, a distance proportional to how steep it is. Tiny steps take forever; giant leaps can carry you clean over the valley and up the other side.
Explain it another way: technical
Full-batch gradient descent averages ∂L/∂w over all examples before each update; stochastic (SGD) and mini-batch variants use one or a few examples per step, trading noise for speed. For a quadratic with curvature λ, steps converge if 0 < η < 2/λ. Momentum and adaptive methods (such as Adam) change the effective step per weight.
Explain it another way: mathematical
y = σ(z), z = wx + b, L = ½(y − t)². σ'(z) = σ(z)(1 − σ(z)). Chain rule: ∂L/∂w = (y − t)σ'(z)x, ∂L/∂b = (y − t)σ'(z). For L = a(w − c)², dL/dw = 2a(w − c) and w − c is multiplied by (1 − 2aη) each step, so convergence needs |1 − 2aη| < 1.
Explain it another way: applied
On-device training is rare because each step needs the forward pass, the gradients and memory for both, but fine-tuning only the last layer (a few hundred weights) is feasible on a microcontroller. Most embedded ML trains on a computer with exactly this procedure, then ships only the final weights.
Derivation: ∂L/∂w for one sigmoid neuron
Define z = wx + b, y = σ(z) = 1/(1 + e^(−z)), and L = ½(y − t)².
Outer link: ∂L/∂y = (y − t), because the ½ cancels the 2 from differentiating a square.
Middle link: dσ/dz = e^(−z)/(1 + e^(−z))² = σ(z)·(1 − σ(z)) = y(1 − y).
Inner link: ∂z/∂w = x (and ∂z/∂b = 1).
Multiply the links (chain rule): ∂L/∂w = (y − t) · y(1 − y) · x, and ∂L/∂b = (y − t) · y(1 − y).
Update: w ← w − η(y − t)y(1 − y)x. Check with numbers: w = 0.5, b = 0, x = 2, t = 1 gives ∂L/∂w ≈ −0.1058; η = 1 gives w ≈ 0.6058, and the loss drops from ≈ 0.0362 to ≈ 0.0263.
Try these examples
Example 1
For L(w) = (w − 3)², start at w = 5 with η = 0.25. Take one step.
The worked solution is in the online lesson.
Example 2
A sigmoid neuron has z = 0. What is σ'(z), and why does it matter?
The worked solution is in the online lesson.
Common mix-ups
The gradient points towards the minimum.
✓ It points uphill, in the direction of steepest increase. Gradient descent steps the opposite way.A larger learning rate always trains faster.
✓ Beyond a limit set by the curvature (η > 1 for (w − 3)²) the steps overshoot and training diverges.Backpropagation is a different algorithm from the chain rule.
✓ It is the chain rule applied layer by layer, reusing each layer's partial results.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A model's loss as a function of one weight is L(w) = 2(w − (−5))². Starting at w = 0 with learning rate η = 0.25, what is w after one gradient-descent step w ← w − η·dL/dw? (2 decimal places)
Answer:
2. What is the slope σ'(z) = σ(z)(1 − σ(z)) of the sigmoid at z = 0?
Answer:
3. For L(w) = (w − 3)², start at w = 5 with learning rate η = 0.25. What is w after one gradient-descent step?
Answer:
4. During training the loss jumps around and then grows larger every epoch. What is the most likely cause?
- The learning rate is too small
- The learning rate is too large
- There is too much training data
5. For one neuron, ∂L/∂w = (y − t)·y(1 − y)·x. An example has input x = 0. How much does it change w?
- Not at all
- A lot, because the error is large
- It depends only on the learning rate
6. One neuron computes y = σ(wx + b) with the sigmoid σ(z) = 1/(1 + e^(−z)). Here w = 1.4, b = 0.3, the input x = 1 and the target t = 1. The loss is L = ½(y − t)². What is ∂L/∂w? (4 decimal places)
Answer:
Apply it
Train the one-neuron example by hand for three steps (w = 0.5, b = 0, x = 2, t = 1, η = 1), updating both w and b with ∂L/∂b = (y − t)y(1 − y). Tabulate w, b, y and L after each step and confirm the loss falls every time. Then repeat the first step with η = 20 and describe what happens to y.
Reflect
In your own words: what does each of the three factors in (y − t)·y(1 − y)·x contribute to how much a weight is blamed for an error?
Cross-validation: grading a model fairly
Your classifier scores 97% on your data, then 71% on the device in the field. Which number was lying, and how could you have known before shipping?
Why it matters
A small dataset is the normal situation in embedded machine learning: a few hundred labelled vibration recordings, not millions of images. One lucky train/test split can make a model look far better or worse than it is. Cross-validation uses every example for testing exactly once, so the score you report is the one you can defend.
Goals
- Run k-fold cross-validation: split, train on k − 1 folds, test on the held-out fold, repeat.
- Report the mean and spread of fold scores and say what the spread tells you.
- Spot data leakage and keep a final test set untouched by model choices.
Predict
With 5-fold cross-validation, how many times is each example used for testing?
- Never: testing uses separate data
- Exactly once
- Five times
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose k = 2, then 4, then 6. Click through the held-out folds. How do the fold accuracies, their mean and their spread change as k grows?
What the interactive shows, in words
The k-fold diagram shows 24 labelled readings as a row of boxes numbered by fold (example i belongs to fold i mod k); the held-out fold is filled in. For each fold a threshold classifier is trained on the other folds (threshold halfway between the two class means) and tested on the held-out fold. A list gives each fold's training size, test size and accuracy, and the readout reports the mean accuracy, its standard deviation and its range for k = 2, 3, 4 or 6.
Understand
Why one split is not enough
Testing on the data you trained on rewards memorising: an overfitted model scores brilliantly and fails in the field. A single held-out split is honest but noisy, especially with little data: which examples happened to land in the test set can swing the score by several per cent. k-fold cross-validation reduces that luck by repeating the split k times.
The k-fold recipe
Shuffle (unless order matters), then cut the data into k equal folds. For each fold in turn: train a fresh model on the other k − 1 folds, test it on this one, record the score. With 1000 examples and k = 5, each model trains on 800 and is tested on 200. Report the mean of the k scores and their spread (standard deviation or range). Common choices are k = 5 or 10.
Reading the spread
Fold scores of 82, 85, 79, 88 and 81% have mean 83.0% and sample standard deviation about 3.5 points. That spread is part of the result: a rival model scoring 84% is not clearly better. A large spread means the model is sensitive to which data it sees, often a sign of too little data or of a few unusual examples clustered in one fold.
Leakage and the final test
Leakage is test information sneaking into training: normalising with statistics computed on all the data before splitting, near-duplicate recordings in different folds, or shuffling time-series so the model trains on the future. Do every preprocessing step inside each fold, and split by recording session or device, not by row. Use cross-validation to choose models; keep a separate test set you touch once, at the very end.
Explain it another way: intuitive
It is like a fair exam rota. Instead of one mock exam that might happen to cover your favourite topics, everyone in the class writes one question each, and you are tested on every question once while studying from the rest. Your average across all rounds is a far better guide to the real exam.
Explain it another way: technical
k-fold CV estimates generalisation error with lower variance than a single split. Larger k means more training data per model (less pessimistic bias) but more models to train and correlated estimates; leave-one-out (k = n) is the extreme. Stratified folds keep class proportions equal; grouped folds keep all samples from one session or device together to avoid leakage. Nested CV separates hyperparameter tuning from evaluation.
Explain it another way: mathematical
Folds F₁…F_k partition the n examples, |Fᵢ| = n/k. Model mᵢ is trained on all data except Fᵢ and scored sᵢ on Fᵢ. Report s̄ = (1/k)Σsᵢ and s = √(Σ(sᵢ − s̄)²/(k − 1)). Example: 82, 85, 79, 88, 81 → s̄ = 83.0, deviations −1, 2, −4, 5, −2, Σ squares = 50, s = √(50/4) ≈ 3.54.
Explain it another way: applied
For a vibration classifier recorded on 6 machines, split by machine (6 grouped folds): each fold asks “does it work on a machine it has never heard?”, which is the question the field deployment will ask. Splitting by individual recordings would mix each machine into both sides and report a falsely high score.
Try these examples
Example 1
A dataset has 500 examples and you use 10-fold cross-validation. How many examples does each model train on and test on?
The worked solution is in the online lesson.
Example 2
Fold accuracies are 82, 85, 79, 88 and 81%. Report the result properly.
The worked solution is in the online lesson.
Common mix-ups
Cross-validation replaces a final test set.
✓ It is for choosing between models and settings. Keep a separate test set untouched until the end, or your choices quietly overfit the CV score.A higher mean CV score always means a better model.
✓ Compare against the spread: a 1-point gain inside a 3.5-point standard deviation is not convincing evidence.Shuffling rows is always safe.
✓ For time series or repeated recordings, shuffling leaks the future or near-duplicates into training; split by time, session or device.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A dataset of 48 labelled examples is split into 8 equal folds for cross-validation. Each model is trained on all folds except the one it is tested on. How many examples does each model train on?
Answer:
2. You run 10-fold cross-validation on 500 examples. How many examples are in each held-out test fold?
Answer:
3. Which of these causes data leakage in cross-validation?
- Using k = 10 instead of k = 5
- Scaling features with the mean and spread of the whole dataset before splitting into folds
- Reporting the standard deviation of fold scores
4. Fold accuracies are 90, 72, 88, 91 and 74%. What should you report?
- 91%, the best fold
- The mean, 83%, with its large spread
- 90%, the first fold
5. A classifier is evaluated with 10-fold cross-validation. The accuracies on the 10 held-out folds are 81.7%, 71.2%, 86.5%, 84.4%, 81.8%, 81.9%, 74.2%, 72.9%, 74.9%, 81.5%. What is the mean cross-validated accuracy, in percent? (2 decimal places)
Answer: %
Apply it
You have 240 labelled audio clips from 8 rooms (30 per room) for a keyword spotter. Design the evaluation: how you would form folds (and why by room), how many clips each model trains and tests on, what you keep back as a final test, and the one table you would publish.
Reflect
Why does testing a model on the data it was trained on reward the wrong thing, and how does k-fold cross-validation stop that without wasting data?
Week 24: Resource-constrained computing
This week you will
- Trade power, performance and area using P = αCV²f.
- Design to a fixed energy budget with duty cycling.
- Measure the accuracy lost to reduced precision.
Power, performance and area
Two slow cores can do the work of one fast core and use less energy. Why don't chips always do that?
Why it matters
Every chip, from a hearing aid to a server, is designed against a power limit. PPA trade-offs explain multicore processors, big–little core designs and why phones lower their clock when they get warm.
Goals
- Use P_dyn = α·C·V²·f and leakage to estimate a chip's power.
- Explain dynamic voltage and frequency scaling (DVFS) and why energy per operation scales with V².
- Trade power, performance and area (PPA) using parallelism and voltage, and state the cost in silicon.
Predict
A chip lowers its voltage by 20% and its clock by 20%. Roughly what happens to dynamic power?
- Falls 20%
- Falls about 36%
- Falls about 49%
- Stays the same
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start at 1 unit, 1.0 V, 3 GHz. Now set 2 units and lower the voltage until 1.5 GHz is still reachable. Compare throughput, power, area and energy per operation. Then find the lowest energy per operation you can reach at any throughput, and the leakage term that stops you going lower.
What the interactive shows, in words
The PPA explorer reports throughput, power, area and energy per operation relative to one unit at 1 V and 3 GHz. Two units at about 0.7 V and 1.5 GHz give the same throughput for about 62% of the energy per operation but twice the area.
Understand
Dynamic and static power
Dynamic power comes from charging and discharging capacitance when signals switch: α·C·V²·f. Static (leakage) power flows even when nothing switches, because transistors never turn fully off; it grows with temperature, with area and as transistors shrink. Total P = P_dyn + P_leak.
DVFS
Dynamic voltage and frequency scaling picks the lowest voltage that supports the needed clock at each moment. Busy: high V, high f. Light load: lower both, saving cube-like power (V²·f). Phones and laptops do this hundreds of times a second.
PPA is a three-way trade
Performance can be bought with clock (costs power), with parallel units (costs area) or with smarter architecture (costs design effort and area). Area costs money through yield (week 22) and leakage. 'Race to idle' (finish fast at high V, then sleep) sometimes beats running slowly, when leakage or the rest of the system dominates.
Explain it another way: intuitive
Two people walking a load slowly use less energy than one person sprinting with it, but you need to pay two people.
Explain it another way: technical
Power density (W/mm²) and thermal limits mean not all transistors can be active at full V and f at once (sometimes called 'dark silicon'). Designers use power gating, clock gating, multiple voltage domains and heterogeneous cores.
Explain it another way: mathematical
Same throughput, N = 2 units at V' with f' = f/2: P'/P = V'²/V² (dynamic). For V = 1 V, V' = 0.7 V: 0.49, a 51% dynamic saving for 2× area.
Explain it another way: applied
Big–little designs pair high-performance cores with small efficient ones: background tasks run on the small cores at low voltage; bursts move to the big ones.
Derivation: Why lowering voltage saves energy, and what it costs
Each switching event charges a capacitance C to voltage V, drawing energy C·V² from the supply. With activity α and clock f: P_dyn = α·C·V²·f.
Energy per operation = P/f = α·C·V²: independent of f, quadratic in V.
But gates switch more slowly at lower V. A common model: f_max ∝ (V − V_t)^α_p / V, with threshold V_t and α_p ≈ 1.3–2.
To keep throughput while lowering f, add parallel units: N units at f/N give the same operations per second.
N units at lower V: power ≈ N·α·C·V_low²·(f/N) = α·C·V_low²·f, less than α·C·V²·f. The price is N× the area, plus leakage on every unit.
Leakage P_leak ≈ I_leak·V is paid all the time and grows with area; at very low V and f it dominates, so energy per operation has a minimum.
Try these examples
Example 1
α = 0.15, C = 2 nF, V = 0.9 V, f = 2 GHz. Dynamic power? Energy per cycle?
The worked solution is in the online lesson.
Common mix-ups
Lower clock frequency always saves energy.
✓ It saves power, but energy per operation only falls if voltage falls too; leakage over a longer run can even raise it.Parallel hardware is free performance.
✓ It costs area, leakage and money, and only helps if the work can be split.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A chip switches an effective capacitance of 0.5 nF with activity factor α = 0.2, at 0.9 V and 3 GHz. What is its dynamic power in watts?
Answer: W
2. A chip switches an effective capacitance of 5 nF with activity factor α = 0.1, at 0.8 V and 0.5 GHz. What is its dynamic power in watts?
Answer: W
3. Voltage drops from 1.1 V to 0.8 V and frequency from 2.4 GHz to 1.2 GHz. What fraction of the original dynamic power remains? (Answer as a decimal.)
Answer:
4. Halving the clock frequency at the same voltage changes dynamic energy per operation by…
- Halving it
- Nothing
- Doubling it
- Quartering it
5. Replacing one fast core with four slow low-voltage cores at equal throughput mainly costs…
- Power
- Area (and leakage), plus software that can use four cores
- Nothing
- Clock frequency of the cores is higher
Apply it
Using the PPA explorer, find a configuration that meets 6 G ops/s for the least energy per operation, and one that meets it in the least area. Report both, explain the difference with P = αCV²f, and say which you would choose for a drone and for a wall-powered server, and why.
Reflect
Where in your own projects have you traded speed for battery life without calling it PPA?
Energy budgets and duty cycling
A soil sensor must run for two years on two AA batteries. It can only be awake about one second in every hundred. How do you design for that?
Why it matters
Most deployed sensors, wearables and remote robots are energy-limited, not speed-limited. Duty cycling (sleep almost always, wake briefly) is the most powerful technique there is, and simple arithmetic tells you where every microjoule goes.
Goals
- Compute average power of a duty-cycled device from active and sleep power.
- Estimate battery life and identify which state dominates the energy budget.
- Compare energy per operation across computing choices and design a schedule that meets a lifetime target.
Predict
A node draws 10 mW for 10 ms every second and 5 µW asleep. What dominates its average power?
- Sleep
- Active
- They are about equal
- Neither: average power is zero
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, model a sensor node as a list of states (sleep, wake-up, sense, compute, transmit) each with a power and a duration. Compute energy per cycle, average power and battery life. Then vary the wake interval from 1 s to 10 min and plot battery life. Where does the curve flatten, and why?
What the interactive shows, in words
The derivation shows P_avg = D·P_on + (1 − D)·P_sleep. A node waking every 30 s for 50 ms at 24 mW and sleeping at 4 µW averages about 44 µW and would last about 9 years on a 1,000 mAh, 3.6 V cell in this ideal model.
Understand
Energy, not power
Batteries store energy (joules, or watt-hours). A task's cost is power × time, so a fast, power-hungry processor that finishes quickly and sleeps can use less energy than a slow, frugal one. Always compare energy per task.
Know your states
Real nodes have more than two states: deep sleep, wake-up (oscillator start, can be costly), sensing, computing, and radio transmit (often the most expensive per second). Measure or look up each, build a timeline, and add up the energy. The biggest slice is where design effort should go.
Computing less, or locally
Sending raw data by radio can cost far more energy than processing it locally and sending a short result. This is a key argument for embedded ML: a tiny on-device classifier that transmits only 'event detected' can extend battery life enormously, provided its own energy and false alarms are counted.
Explain it another way: intuitive
A lighthouse that flashes for a moment every ten seconds uses far less than a lamp left on, yet ships still see it. Most of the time, being off is the job.
Explain it another way: technical
Microcontrollers offer several low-power modes trading wake-up latency against sleep current; real-time clocks and wake-up interrupts schedule activity. Peripherals and pull-up resistors left on are common hidden drains.
Explain it another way: mathematical
P_avg = D·P_on + (1 − D)·P_sleep. Sensitivity: ∂P_avg/∂D = P_on − P_sleep ≈ P_on. Halving t_on halves the active contribution; halving P_sleep matters only when (1 − D)·P_sleep is comparable.
Explain it another way: applied
Wildlife trackers and environmental monitors are commonly designed to run for months to years on small batteries by sleeping almost always and waking briefly to sense and transmit.
Derivation: Average power and battery life
Over one period T, the node is active for t_on and asleep for T − t_on. Duty cycle D = t_on / T.
Energy per period E = P_on·t_on + P_sleep·(T − t_on). Average power P_avg = E / T = D·P_on + (1 − D)·P_sleep.
Battery energy ≈ capacity (Ah) × voltage (V) × 3600 J. Lifetime ≈ E_battery / P_avg (ignoring self-discharge and temperature).
As T grows, D → 0 and P_avg → P_sleep: sleep power sets the ceiling on lifetime.
Example: P_on = 15 mW, t_on = 20 ms, T = 10 s, P_sleep = 3 µW: D = 0.002, P_avg = 30 + 3 ≈ 33 µW. Two AA cells (about 2.5 Ah at 3 V ≈ 27 kJ) last about 26 years by this ideal sum; self-discharge will end them much sooner.
Try these examples
Example 1
A node wakes every 30 s for 50 ms at 24 mW and sleeps at 4 µW. Average power and life on a 1,000 mAh, 3.6 V cell?
The worked solution is in the online lesson.
Common mix-ups
The lowest-power processor gives the longest battery life.
✓ Energy per task decides it: a faster chip that sleeps sooner can win.Battery life = capacity ÷ active current.
✓ Use average current over the whole duty cycle, and allow for self-discharge, temperature and ageing.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A sensor node wakes every 5 s, runs for 2 ms at 30 mW, and sleeps the rest of the time at 10 µW. What is its average power in microwatts (µW)?
Answer: µW
2. A sensor node wakes every 2 s, runs for 50 ms at 5 mW, and sleeps the rest of the time at 1 µW. What is its average power in microwatts (µW)?
Answer: µW
3. A device averages 50 µW from a battery storing 10,000 J. Ignoring self-discharge, how many days will it last?
Answer: days
4. A node's average is 200 µW active + 3 µW sleep. Which change helps most?
- Halve the sleep current
- Halve the awake time per cycle
- Use a bigger enclosure
- Double the clock but keep awake time the same
5. Core A runs a task in 2 ms at 30 mW; core B takes 10 ms at 8 mW. Both sleep afterwards at the same power. Which uses less energy for the task?
- A (60 µJ)
- B (80 µJ)
- They are equal
- B, because its power is lower
Apply it
Design a duty-cycle schedule for a gesture-detecting wristband that must last 14 days on a 150 mAh, 3.7 V cell. Use the inference energy you estimated in week 23, add sensing and a radio message per detected gesture, and show the budget table with every assumption labelled.
Reflect
Which state of your device would you measure first if its battery died early, and why?
Reduced precision: range, resolution and error
Your filter works perfectly in Python floats. On the 16-bit chip, it slowly drifts and then explodes. What went wrong?
Why it matters
Reduced precision saves memory, time and energy, but every bit you remove costs either range (you overflow) or resolution (you round). The art is spending bits where the signal needs them, and proving with a measurement that the result still meets the requirement.
Goals
- Choose a fixed-point format (Qm.n) from a signal's range and the resolution needed.
- Explain overflow, rounding and accumulation of error in reduced-precision arithmetic.
- Measure accuracy loss from reduced precision or sample rate against a stated requirement.
Predict
A signed 4-bit register holds 7 (0111). You add 1. What does it hold?
- 8
- −8
- 0
- 7 (it saturates)
Write down your guess and your reason. The reveal is in the online lesson.
Discover
On the 4-bit register, show the largest and smallest values, then add 1 to 1111 and watch the carry fall off. Now imagine those 4 bits as Q1.3 fixed point (one integer bit, three fraction bits): what are its range and step size?
What the interactive shows, in words
The 4-bit register shows 0000 to 1111. In two's complement, 0111 is 7 and adding 1 gives 1000, which is −8: the value wraps. Read as Q1.3, the same bits cover −1 to 0.875 in steps of 0.125.
Understand
Qm.n formats
A signed Qm.n number has m integer bits (including sign) and n fraction bits: value = integer / 2ⁿ. Range ≈ [−2^(m−1), 2^(m−1)), step 2^(−n). Q1.15 in 16 bits covers [−1, 1) in steps of about 3×10⁻⁵. Choose m from the largest value the signal (and every intermediate result) can reach, then give the rest to n.
Where precision is lost
Rounding each result loses up to half a step. Multiplication doubles the fraction bits (Q1.15 × Q1.15 = Q2.30), so results are shifted back and rounded. Accumulation of many products needs extra headroom bits. Feedback (recursive filters, integrators) can accumulate rounding errors or sustain small oscillations (limit cycles).
Precision is a measured requirement
State the requirement first (for example, 'error under 0.5% of full scale'), then implement at candidate precisions on identical inputs, measure the error and pick the smallest that meets it with margin. The same applies to sample rate: lower rates save energy until aliasing or lag breaks the requirement. This is the method of the term project.
Explain it another way: intuitive
A ruler marked only in centimetres can't measure a hair, and a 30 cm ruler can't measure a room. Fixed point makes you pick your ruler before you start.
Explain it another way: technical
Fixed-point DSP uses integer ALUs with shifts for scaling, saturating arithmetic options, and wide accumulators (for example 40-bit on 16-bit DSPs) to avoid overflow in sums.
Explain it another way: mathematical
Quantisation noise of step Δ has variance Δ²/12. For Q1.15, Δ = 2⁻¹⁵, so RMS ≈ 8.8×10⁻⁶. A sum of N products, each rounded, has error variance about N·Δ²/12, so RMS error grows like √N.
Explain it another way: applied
Audio codecs, motor-control loops and many sensor filters on microcontrollers run in Q15 or Q31 arithmetic because integer instructions are faster and cheaper in energy than floating point on chips without an FPU.
Try these examples
Example 1
A gyro reads ±250 °/s and you need 0.01 °/s resolution. Pick a 16-bit signed format.
The worked solution is in the online lesson.
Common mix-ups
More fraction bits are always better.
✓ In a fixed word, every fraction bit is taken from range: you trade overflow risk for resolution.If the inputs fit, the result fits.
✓ Sums and products need more bits than their inputs; size every intermediate, or use a wide accumulator.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. What is the step size (resolution) of a signed Q4.12 number?
Answer:
2. What is the largest value a signed Q4.12 (16-bit) number can hold? (Give it to 4 decimal places.)
Answer:
3. Multiplying two Q1.15 numbers gives a 32-bit result in which format?
- Q1.15
- Q2.30
- Q1.31
- Q16.16
4. A neural network has 120000 weights stored at 8 bits each. How many kilobytes (1 KB = 1024 bytes) do the weights occupy?
Answer: KB
5. Why write the accuracy requirement before testing precisions?
- It is a formality
- So the choice follows from the requirement, not from whichever result looks best afterwards
- To make the code faster
- Because precision cannot be measured
Apply it
Start the term project: pick your algorithm, write the accuracy requirement and decision rule, and choose Q formats for a 16-bit and an 8-bit version with the range and resolution reasoning written out. Do not run anything yet.
Reflect
Where in your earlier projects did a number silently overflow or round, and how would you have caught it?
Week 25: Numerical optimisation
This week you will
- Analyse gradient descent convergence and choose a step size.
- Explain convexity and why non-convex problems have local minima.
- Compare first- and second-order methods and handle constraints with penalties.
Gradient descent and the learning rate
Blindfolded on a hillside, you can only feel the slope under your feet. How big should each step downhill be?
Why it matters
Gradient descent trains neural networks, fits models to data, tunes controllers and sizes components. Its single knob, the learning rate, decides whether it converges quickly, crawls or explodes, and that is a piece of maths you can predict.
Goals
- Apply the gradient-descent update x ← x − η∇f(x) by hand for a few steps.
- Derive the convergence condition 0 < η < 2/L for a quadratic with curvature L.
- Explain how the condition number (a narrow valley) slows convergence.
Predict
Minimising f(x) = x² (gradient 2x) from x = 1 with learning rate η = 1.1. What happens?
- Converges to 0
- Oscillates with growing size
- Stops at x = 1
- Converges to 1.1
Write down your guess and your reason. The reveal is in the online lesson.
Discover
On the round bowl, find the learning rate that reaches the centre in one step. Switch to the narrow valley with b = 4: raise η until it diverges, and note the value. Then set b = 10 and see why a safe η crawls along the valley floor.
What the interactive shows, in words
The explorer draws elliptical contours and the path of each gradient step. On f = ½(x² + 4y²) with η = 0.3, the y-coordinate shrinks by |1 − 1.2| = 0.2 per step and x by 0.7; at η = 0.6 the y-factor is |1 − 2.4| = 1.4 and the path diverges.
Understand
The update
The gradient ∇f points uphill, steepest. Gradient descent steps the other way: x ← x − η∇f(x). η, the learning rate or step size, scales the step. Repeat until the gradient is (nearly) zero or progress stalls.
Too small, too big, just right
Too small: correct but painfully slow. Too big: overshoot, oscillate, diverge. For a quadratic the boundary is exact: η < 2/L. In practice, start small, increase until the loss stops falling smoothly, then back off; or use a line search that picks η each step.
Narrow valleys
When curvature differs a lot between directions (an ill-conditioned problem), the steep direction limits η and the shallow direction then moves slowly: the zig-zag path in the explorer. Rescaling variables (preconditioning), momentum, or second-order methods fix this.
Explain it another way: intuitive
Walking downhill in fog: big strides get you down fast on a gentle slope but can leap across a narrow gully and land higher on the other side.
Explain it another way: technical
For L-smooth convex f with η = 1/L, f(x_k) − f* ≤ L‖x₀ − x*‖² / (2k): sublinear O(1/k). For μ-strongly convex f, convergence is linear with rate (1 − μ/L) per step.
Explain it another way: mathematical
f(x) = a(x − c)² has f' = 2a(x − c), so x_{k+1} − c = (1 − 2aη)(x_k − c). Hence x_k = c + (1 − 2aη)^k (x₀ − c), stable for 0 < η < 1/a.
Explain it another way: applied
Least-squares calibration of a sensor, fitting a motor model to step-response data and training a classifier all reduce to minimising a smooth loss; for the quadratic ones, the condition number of the data matrix predicts how slowly plain gradient descent will go.
Derivation: When does gradient descent converge on a quadratic?
Take f(x) = ½·a·x² with a > 0. Then f'(x) = a·x and the update is x_{k+1} = x_k − η·a·x_k = (1 − ηa)·x_k.
So x_k = (1 − ηa)^k · x₀: a geometric sequence. It shrinks to 0 if and only if |1 − ηa| < 1, i.e. 0 < η < 2/a.
Fastest: η = 1/a gives 1 − ηa = 0: one step. For 1/a < η < 2/a it overshoots and oscillates but still converges.
In two dimensions, f = ½(a₁x² + a₂y²) gives two independent factors (1 − ηa₁) and (1 − ηa₂). Stability needs η < 2/max(aᵢ).
With η limited by the steep direction, the shallow direction shrinks by (1 − a_min/a_max) per step at best. The condition number κ = a_max/a_min sets the pace: κ = 100 means about 100 steps per factor e.
For a general smooth f, L (the largest curvature, the Lipschitz constant of the gradient) plays the role of a_max: η < 2/L.
Try these examples
Example 1
f(x) = 2(x − 3)², x₀ = 7, η = 0.1. Find x₁ and x₂.
The worked solution is in the online lesson.
Common mix-ups
A bigger learning rate always gets there faster.
✓ Beyond 2/L it diverges, and between 1/L and 2/L it oscillates.Gradient descent finds the global minimum.
✓ On convex functions any minimum is global; on non-convex ones it finds a local minimum near the start (next lesson).
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Minimise f(x) = 1(x − -2)² by gradient descent with learning rate η = 0.2, starting from x₀ = 8. What is x after 6 steps?
Answer:
2. Minimise f(x) = 0.5(x − 3)² by gradient descent with learning rate η = 0.05, starting from x₀ = -4. What is x after 5 steps?
Answer:
3. f(x, y) = ½(3x² + 12y²). What is the largest learning rate for which gradient descent converges? (Strict upper bound.)
Answer:
4. Gradient descent zig-zags slowly down a long, narrow valley. The most direct cure is…
- A larger learning rate
- Rescaling the variables so the curvature is similar in every direction
- More random starting points
- Stopping earlier
5. For f(x) = ½·5x², which learning rate reaches the minimum in exactly one step from any start?
Answer:
Apply it
In the Code Lab, fit y = mx + c to ten noisy points by gradient descent on the mean squared error. Predict the largest stable η from the data (the largest eigenvalue of the 2×2 curvature matrix), then test your prediction just below and just above it.
Reflect
How would you choose a learning rate for a problem whose curvature you cannot compute?
Convexity and local minima
Two engineers run the same optimiser on the same design problem and get different answers. Who is wrong?
Why it matters
Whether a problem is convex decides whether an optimiser's answer can be trusted. Least squares, many control and resource-allocation problems are convex; neural network training, mechanical design and placement usually are not. Research engineers say which kind they solved.
Goals
- Define a convex function and a convex set and test simple functions for convexity.
- Explain why every local minimum of a convex function is global.
- Use multiple starts and sensitivity checks on non-convex problems and report what they show.
Predict
On f(x, y) = (x² − 1)² + ½y², gradient descent starts at x = −0.3. Where does it end?
- x = 1
- x = −1
- x = 0
- It depends on η only
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose the double well. Try start points from x₀ = −2 to +2. Record which minimum each reaches. Then return to the bowl and confirm every start reaches the same point. What property of the surface makes the difference?
What the interactive shows, in words
On the double-well surface f = (x² − 1)² + ½y², paths starting with negative x end at x = −1, positive x at x = +1. On the round bowl, every start ends at the centre.
Understand
Convex functions
f is convex if the straight line between any two points on its graph lies on or above the graph: f(θx + (1 − θ)y) ≤ θf(x) + (1 − θ)f(y). For twice-differentiable f this means f'' ≥ 0 (in 1-D) or a positive semi-definite Hessian. x², |x|, eˣ and ½xᵀAx with A positive semi-definite are convex.
Why convexity is precious
For a convex function on a convex set, every local minimum is a global minimum, and gradient methods with a sensible step converge to it from any start. You can also certify optimality: a zero gradient proves you are done.
Living with non-convexity
Non-convex functions can have many local minima, saddle points and flat regions. Practical responses: multiple random starts (report the spread of results), good initial guesses from physics, convex relaxations that give bounds, and global methods (simulated annealing, genetic algorithms) for small problems. Never present one run of a non-convex optimiser as 'the optimum'.
Explain it another way: intuitive
A single smooth bowl has one bottom; a landscape of hills and hollows has many. A ball rolls to whichever hollow is nearest.
Explain it another way: technical
Convex optimisation problems (linear, quadratic, second-order cone, semidefinite programmes) have mature solvers with optimality certificates. Non-convex problems are generally NP-hard to solve globally.
Explain it another way: mathematical
f(x) = (x² − 1)²: f'(x) = 4x(x² − 1), f''(x) = 12x² − 4. f'' < 0 for |x| < 1/√3 ≈ 0.577, so f is not convex there; x = 0 is a local maximum and x = ±1 are minima.
Explain it another way: applied
Choosing gear ratios, link lengths or PID gains for best performance is often non-convex. Engineers run many starts, plot the objective landscape when it is low-dimensional, and check that the chosen design is robust to small changes.
Try these examples
Common mix-ups
If an optimiser converges, it found the best answer.
✓ It found a stationary point. Only convexity (or a global method with proof) makes that the best.Non-convex problems cannot be optimised.
✓ They are optimised every day; you just report local results honestly and test robustness.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which function is convex on all real x?
- sin x
- x³
- eˣ + x²
- x⁴ − x²
2. Your optimiser returns a point with zero gradient on a convex objective. What can you conclude?
- It may be a local maximum
- It is a global minimum
- Nothing without more starts
- It is a saddle point
3. For f(x) = (x² − 1)², below what value of |x| is f''(x) negative? (3 decimal places.)
Answer:
4. Minimise f(x) = 1(x − 3)² by gradient descent with learning rate η = 0.25, starting from x₀ = 8. What is x after 3 steps?
Answer:
5. You tune a robot arm design with a non-convex objective. What is the honest report?
- 'We found the optimal design.'
- 'Best of 50 random starts; 38 reached within 1% of this value; results from the other 12 are shown.'
- 'Gradient descent converged, so it is optimal.'
- Report only the best run
Apply it
Run gradient descent on the double well from 21 evenly spaced starts between −2 and 2 (in the explorer or the Code Lab). Make a table of start → end point. Where is the boundary between the basins, and why there?
Reflect
Which optimisation in your own work was convex, and which only looked like it?
Newton's method, momentum and constraints
Gradient descent takes 200 steps down a narrow valley. Newton's method takes one. What is it using that gradient descent ignores?
Why it matters
Real optimisation problems are ill-conditioned and constrained: a motor's current is limited, a beam's stress must stay below yield. Second-order methods, momentum and penalties are the standard tools, and knowing their costs lets you choose one sensibly.
Goals
- Derive Newton's step x ← x − f'(x)/f''(x) from a quadratic model and compare its convergence with gradient descent.
- Explain momentum as a fix for ill-conditioned valleys.
- Handle a constraint with a penalty term and explain the trade-off in the penalty weight.
Predict
Newton's method on f(x) = ½·a·x² from any starting point takes how many steps to reach the minimum?
- One
- About 1/a
- About a
- It never reaches it exactly
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, minimise f(x, y) = ½(x² + 10y²) three ways from (2, 1): gradient descent with the best stable η, gradient descent with momentum (β = 0.8), and Newton's method. Count iterations to reach f < 10⁻⁶. Then add a penalty μ·max(0, x − 0.5)² and see how the answer depends on μ.
What the interactive shows, in words
The derivation fits a quadratic at the current point and jumps to its minimum: x ← x − f'(x)/f''(x). The penalty example gives x* = (2 + μ)/(1 + μ), approaching the constraint x = 1 as μ grows.
Understand
Second-order methods
Newton's method uses curvature to scale the step in every direction, so ill-conditioning disappears: the narrow valley looks round to it. Quasi-Newton methods (BFGS, L-BFGS) build an approximation of H⁻¹ from gradients, keeping most of the benefit at a fraction of the cost, and are the default for medium-sized smooth problems.
Momentum
Momentum keeps a running velocity: v ← βv − η∇f, x ← x + v. Along a consistent shallow direction the steps add up; across a steep gully they cancel. It is cheap, first-order, and widely used in training neural networks.
Constraints by penalty
To minimise f subject to g(x) ≤ 0, minimise f(x) + μ·max(0, g(x))². Small μ: the constraint is violated a little. Large μ: closer to feasible, but the problem becomes ill-conditioned and slow. Increase μ gradually, or use exact methods (Lagrange multipliers, projection, interior-point solvers) when feasibility is non-negotiable, such as a safety limit.
Explain it another way: intuitive
Gradient descent feels the slope; Newton also feels how the slope is changing, so it can guess where the bottom is and jump there.
Explain it another way: technical
Convergence: gradient descent is linear with rate depending on κ; Newton is locally quadratic; momentum (heavy ball) improves the dependence from κ to roughly √κ on quadratics. Penalty methods converge to the constrained optimum as μ → ∞.
Explain it another way: mathematical
1-D penalty: minimise (x − 2)² subject to x ≤ 1, using (x − 2)² + μ(x − 1)² for x > 1. Setting the derivative to zero: x* = (2 + μ)/(1 + μ). μ = 1: 1.5; μ = 10: 1.09; μ = 100: 1.0099 → 1 as μ → ∞.
Explain it another way: applied
Model-predictive controllers solve a small constrained quadratic programme every few milliseconds, with actuator limits as constraints, using interior-point or active-set solvers designed for exactly this structure.
Derivation: Newton's step from a quadratic model
Near x_k, approximate f by its second-order Taylor expansion: f(x_k + d) ≈ f(x_k) + f'(x_k)·d + ½f''(x_k)·d².
Minimise the model over d: derivative f'(x_k) + f''(x_k)·d = 0, so d = −f'(x_k)/f''(x_k).
Newton update: x_{k+1} = x_k − f'(x_k)/f''(x_k). In n dimensions: x ← x − H⁻¹∇f, with H the Hessian.
It is Newton–Raphson root-finding applied to f' = 0, which you met for solving equations.
Cost: forming and solving with H is O(n²) memory and O(n³) time per step, versus O(n) for a gradient step. Trade: few expensive steps versus many cheap ones.
Caution: if f'' ≤ 0 the step can go uphill; practical methods add a line search or modify H.
Try these examples
Example 1
Newton's method on f(x) = x⁴ from x₀ = 1. Find x₁ and x₂.
The worked solution is in the online lesson.
Common mix-ups
Second-order methods are always better.
✓ They take fewer steps, but each costs far more; for huge problems cheap first-order steps win.A penalty enforces the constraint exactly.
✓ Only in the limit μ → ∞; at finite μ the solution sits slightly outside.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Apply one step of Newton's method to f(x) = 3x² − 12x + 1 from x₀ = 10. What is x₁?
Answer:
2. Minimise (x − 2)² subject to x ≤ 1 with the penalty μ(x − 1)² for x > 1 and μ = 9. What x does the penalised problem give?
Answer:
3. For a problem with a million variables, why is plain Newton's method rarely used?
- It converges too slowly
- Storing and solving with a million-by-million Hessian is far too expensive
- It only works in 1-D
- It cannot handle convex problems
4. A motor current must never exceed its rating. Which constraint method suits that best?
- A small penalty
- An exact constraint method (projection, interior-point or clamping) that guarantees feasibility
- Ignore it and check afterwards
- A random search
5. Minimise f(x) = 2(x − 1)² by gradient descent with learning rate η = 0.05, starting from x₀ = 5. What is x after 4 steps?
Answer:
Apply it
Write a short comparison table (method, iterations, cost per iteration, total work) for the three methods you ran in the Code Lab. Then argue which you would use for 10, 10,000 and 10 million variables.
Reflect
Which method would you trust for a safety-critical constraint, and what evidence would convince a reviewer?
Week 26: Engineering system evaluation
This week you will
- Write a benchmark protocol with conditions, warm-up, repeats and an analysis plan.
- Choose primary and secondary metrics and report results with uncertainty.
- Use an ablation to attribute performance to components.
Benchmarking computer systems fairly
Your new code is '30% faster' on your laptop. Run it again and it's 5% slower. Which number goes in the report?
Why it matters
Performance numbers are notoriously easy to get wrong: caches warm up, clocks scale with temperature, background tasks interfere. A sound benchmark protocol is what turns 'it felt faster' into evidence a reviewer will accept.
Goals
- Write a benchmark protocol: workload, conditions, warm-up, repeats and an analysis plan.
- Choose primary and secondary metrics (latency percentiles, throughput, energy, memory, accuracy).
- Report a comparison with uncertainty and recognise multi-objective trade-offs with a Pareto view.
Predict
A controller's loop time is measured 1,000 times: mean 2.1 ms, but 1% of runs take 9 ms. The deadline is 5 ms. Which metric matters most?
- Mean
- Median
- 99th-percentile or worst case
- The fastest run
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the trade-offs lab. Treat the designs as candidate system configurations. Change the weights on each criterion and see which designs stay on the Pareto front no matter what. A fair benchmark reports the whole front, not just the winner under your favourite weights.
What the interactive shows, in words
The trade-offs lab scores six designs on several criteria with adjustable weights and highlights those on the Pareto front, which never change with the weights; only the single 'winner' does.
Understand
Protocol first
Fix the workload (inputs, sizes, a standard suite if one exists), the system (hardware, OS, compiler and flags, versions), conditions (power mode, temperature, background load) and the procedure: warm-up runs discarded, N timed repeats, randomised or interleaved order between the systems being compared. Write it down before running, as in Term 2's pre-registration.
Metrics
Primary metric: the one your claim rests on, chosen in advance (for example p99 latency). Secondary: throughput, energy per task, peak memory, accuracy. For distributions, report median and tail percentiles, not just the mean. Use execution time, not MIPS or GHz, as the Iron Law warns.
Uncertainty and comparison
Repeat runs vary. Report the spread (standard deviation or interquartile range) and a confidence interval for the difference between systems, from paired or interleaved runs. A 3% gain with a ±5% interval is not a demonstrated gain.
Trade-offs
Many systems win on one metric and lose on another: faster but hungrier, smaller but less accurate. A design is Pareto-optimal if nothing beats it on every metric at once. Show the front and say which point your requirement selects.
Explain it another way: intuitive
Timing a runner once on a windy day tells you little. Time several races, same track, same conditions, alternate the runners, and report the spread.
Explain it another way: technical
Sources of noise: frequency scaling, thermal throttling, cache and TLB state, memory layout, interrupts, other processes. Mitigations: fixed frequency or performance governor, warm-up, pinning to cores, many repeats, interleaving, and reporting the environment.
Explain it another way: mathematical
With n paired runs and differences dᵢ, the mean difference d̄ has standard error s_d/√n. A 95% interval is roughly d̄ ± 2s_d/√n for moderate n. Speed-up ratios are better summarised with geometric means across workloads.
Explain it another way: applied
Industry benchmark suites (for processors, embedded ML and databases) specify the workload, the rules and what must be reported, precisely so that results from different labs can be compared.
Try these examples
Example 1
Ten paired runs of old vs new code give time differences (old − new) with mean 1.2 ms and standard deviation 2.0 ms. Is the new code faster?
The worked solution is in the online lesson.
Common mix-ups
One run is enough if the computer is fast.
✓ Run-to-run variation is often several percent; repeats and intervals are essential.The mean latency is the right summary.
✓ For deadlines and user experience, tails (p95, p99, max) matter more.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Why discard warm-up runs?
- To hide slow results
- Because first runs include one-off costs (cold caches, loading, JIT compilation) not present in steady state
- To make the numbers smaller
- Because the first run is always wrong
2. Sixteen paired runs give a mean difference of 0.8 ms with standard deviation 1.6 ms. What is the standard error of the mean difference, in ms?
Answer: ms
3. Design A: 10 ms, 50 mJ. B: 12 ms, 30 mJ. C: 14 ms, 55 mJ. Which are Pareto-optimal (lower is better on both)?
- A only
- A and B
- B and C
- All three
4. A program executes 200 million instructions with an average CPI of 1.8 on a 3 GHz processor. How long does it take, in milliseconds?
Answer: ms
5. Which practice makes a two-system timing comparison fairest?
- Run all of A, then all of B, on a warming laptop
- Interleave A and B runs on a fixed-frequency machine, same inputs, with the order randomised
- Run each once on different machines
- Use whichever run of each was fastest
Apply it
Write the benchmark protocol for your term project: workload, systems (three precisions), conditions, warm-up, number of repeats, primary and secondary metrics, how you will compute uncertainty, and your decision rule.
Reflect
What would a sceptical reviewer ask about the last performance claim you made?
Ablations: which part made it better?
Your new design is 40% faster. It has a bigger cache, a new predictor and a compiler flag. Which one did the work?
Why it matters
Claims like 'our architecture is faster' are only useful if you know why. Ablations isolate each change, so the next engineer knows which idea to keep. They are expected in any serious systems or ML paper.
Goals
- Design an ablation study that changes one component at a time against a fixed baseline.
- Attribute performance to components and recognise interactions between them.
- Explain an ablation's result from first principles (for example with AMAT or the Iron Law).
Predict
In the cache simulator, the 'Two arrays that collide' pattern runs direct-mapped. You change to 2-way AND 32-byte blocks at once, and misses drop. What can you conclude?
- Both changes helped equally
- Associativity did all the work
- You cannot tell which change helped without testing each separately
- Block size did all the work
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Baseline: 'Two arrays that collide', direct-mapped, 16 B blocks. Record the misses. Now change only associativity, then only block size (back to direct-mapped), then both. Fill a 2×2 table of misses. Then read the note under the simulator: what else changes when the block size changes with 8 lines fixed?
What the interactive shows, in words
With 'Two arrays that collide' (16 reads): direct-mapped with 16 B blocks gives 16 misses; 2-way gives 4; direct-mapped with 32 B blocks gives 2, because the 8-line cache doubles in size; 2-way with 32 B blocks also gives 2.
Understand
One change at a time
Start from the full system and remove (or start from the baseline and add) one component per run, holding everything else fixed: same inputs, same metric, same conditions. The difference from the reference attributes performance to that component.
Interactions
Components can interact: a bigger cache may make a prefetcher less useful, or a predictor may matter only with a deep pipeline. A full factorial design (every combination; 2ⁿ runs for n on/off components) reveals interactions; with many components, test the most plausible pairs.
Explain, don't just tabulate
Tie each effect to a mechanism. 'Two-way associativity removed the conflict misses because a[i] and b[i] share index bits' is a finding; '2-way is 4× better' is only a number. Mechanism-level explanations generalise to new workloads; raw numbers may not.
Explain it another way: intuitive
A cake tastes better after you changed the flour, the oven and the recipe. Bake it again changing only one of them to find out which one mattered.
Explain it another way: technical
Ablation design: define the reference configuration, the component list, the metric with uncertainty, and the order of runs (randomised). Report each ablation's effect with an interval, plus any interaction terms measured.
Explain it another way: mathematical
In a 2×2 factorial with outcomes y₀₀, y₁₀, y₀₁, y₁₁: main effect of A = ½[(y₁₀ − y₀₀) + (y₁₁ − y₀₁)]; interaction = ½[(y₁₁ − y₀₁) − (y₁₀ − y₀₀)].
Explain it another way: applied
Processor design teams evaluate each proposed feature with simulation ablations on benchmark suites, using the Iron Law to check whether a gain came through CPI, clock or instruction count.
Try these examples
Example 1
Simulator misses for the colliding arrays: baseline (direct-mapped, 16 B) 16; 2-way only 4; 32 B blocks only 2; both 2. Main effects and interaction?
The worked solution is in the online lesson.
Common mix-ups
If the full system is better, every component must be helping.
✓ Some may do nothing or even hurt; only ablations show it.Ablating each component once is enough.
✓ Components can interact; check plausible combinations and report uncertainty on each effect.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which is an ablation?
- Comparing your system with a competitor's
- Removing one component of your system at a time and measuring the change
- Running the full system ten times
- Tuning all parameters together
2. A 2×2 study of predictor (P) and cache (C) gives run times (ms): neither 100, P only 80, C only 70, both 55. What is the main effect of P (ms)?
Answer: ms
3. A direct-mapped cache has 4 lines of 16 bytes and starts empty. The CPU reads these byte addresses in order: 124, 272, 272, 368, 20, 20, 272, 144, 144, 144. How many reads hit?
Answer: hits
4. A cache has a hit time of 2 cycles, a miss rate of 8% and a miss penalty of 150 cycles. What is the AMAT in cycles?
Answer: cycles
5. Doubling the L1 cache cut run time by 20%. Which follow-up best explains it from first principles?
- Report '20% faster' and stop
- Measure the miss rate before and after and check whether AMAT × accesses per instruction accounts for the CPI change
- Try a third cache size and pick the best
- Measure clock frequency
Apply it
Plan the ablations for your term project: which components (precision of weights, precision of the accumulator, rounding mode, sample rate) will you vary one at a time, from which reference, and what mechanism do you predict for each effect?
Reflect
Think of a claim you have read that bundled several changes together. What ablation would have made it convincing?
Week 27: Architecture or algorithm comparison project
This week you will
- Compare two architectures or algorithms on accuracy, speed and resource use with a fair baseline.
- Explain the result from first principles (Iron Law, AMAT, complexity).
Designing an architecture comparison
Ripple-carry or carry-lookahead: which adder is 'better'? The honest answer starts with 'better at what, and how will we know?'
Why it matters
This week you run the term's comparison project. Whether it compares adders, precisions, cache settings or algorithms, the method is the same: a question, a baseline, a prediction from theory, measurements across conditions, and an honest report.
Goals
- Turn 'which is better?' into a measurable research question with a fair baseline and pre-stated metrics.
- Predict the outcome from first principles (complexity, gate depth, Iron Law) before measuring.
- Plan measurements across sizes so a trend, not a single point, answers the question.
Predict
A ripple-carry adder's delay grows linearly with the number of bits n. How does a carry-lookahead adder's delay grow, roughly?
- Also linearly
- Logarithmically (about log n levels)
- Quadratically
- It is constant
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open Level 5 'Investigate speed'. Before measuring, write your hypothesis about how the longest gate path grows with adder width. Then record at least four sizes, keeping everything else fixed, and compare the measured trend with your prediction.
What the interactive shows, in words
The Level 5 investigation builds adders of several widths from gates and reports their longest gate path. Ripple-carry paths grow by about 2 gate delays per bit; lookahead designs grow roughly with log₂ of the width but use more gates.
Understand
A measurable question
Replace 'which is better?' with something like: 'How does worst-case delay and gate count grow with width n for ripple-carry and carry-lookahead adders, for n = 4 to 32?' The question names the systems, the metrics, the conditions and the range.
Theory first
Write what you expect, with reasons: ripple delay ≈ 2n gate delays (Θ(n)); lookahead ≈ c·log₂ n (Θ(log n)) with more gates. A prediction made before measuring turns the experiment into a test. If the data disagree, that is a finding to explain, not a failure.
Fair comparison
Same gate library and delay model, same widths, same test inputs (including worst-case carry chains), equal effort on each design. Measure a range of sizes so the growth rate is visible; a single size can hide a crossover where the 'worse' design wins for small n.
Explain it another way: intuitive
Racing two cars on one short track tells you who wins that track. Racing them on tracks of many lengths tells you who wins in general and where the lead changes.
Explain it another way: technical
Report metrics as functions of size, fit the expected model (linear, logarithmic) and compare residuals. State the model of delay you used (unit gate delay, no wire delay) and its limits.
Explain it another way: mathematical
If T_ripple(n) = a·n and T_cla(n) = b·log₂ n + c, the crossover where lookahead becomes faster solves a·n = b·log₂ n + c; for a = 2, b = 4, c = 2: n = 8 gives 16 vs 14, so lookahead wins from about n = 8.
Explain it another way: applied
Real processors use parallel-prefix adders, a lookahead family, in their ALUs because a 64-bit ripple adder would set an unacceptably long critical path for the clock.
Try these examples
Example 1
Write a decision rule for the term project before measuring.
The worked solution is in the online lesson.
Common mix-ups
Theory isn't needed if you can measure.
✓ Without a prediction you cannot tell a surprising result from an expected one, or spot a measurement error.The faster design is better.
✓ Better depends on all the metrics that matter (area, energy, accuracy) and the requirement you stated.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which is the best research question for an adder comparison?
- Which adder is best?
- Is carry-lookahead cool?
- How do worst-case delay and gate count scale with width (4–32 bits) for ripple-carry and carry-lookahead adders?
- Can I build an adder?
2. With a model of 2 gate delays per bit for the carry, what is the worst-case carry delay of a 24-bit ripple-carry adder, in gate delays?
Answer: gate delays
3. How many times is work() called when n = 210? Code: for i in 0 … n−1: for j in i+1 … n−1: work()
Answer: calls
4. Why measure several sizes rather than one?
- It looks better in a report
- Growth rates and crossovers only show up across sizes; one point can mislead
- It is required by law
- Smaller sizes are always more accurate
5. 90% of a program's run time is moved onto a hardware accelerator that makes that part 5× faster. What is the overall speed-up?
Answer: ×
Apply it
Finish and submit the project's pre-registration: question, systems, baseline, metrics, sizes or conditions, prediction from first principles, decision rule and analysis plan. Then run the Level 5 adder investigation as a practice run of the method.
Reflect
What is your prediction for the term project, and what result would make you change your mind?
Explaining results from first principles
Your 8-bit version runs 2.6× faster than float, but the arithmetic is only 2× cheaper. Where did the rest come from?
Why it matters
A comparison is finished only when you can explain it. Explaining a speed-up with the Iron Law and AMAT, and an accuracy change with quantisation error, is what turns a table into understanding that transfers to the next design.
Goals
- Decompose a measured speed-up into Iron Law factors (IC, CPI, cycle time) and memory effects (AMAT).
- Check that a first-principles model explains the measured result within its uncertainty, and say what it does not explain.
- Write the results, recommendation and limitations of the term project honestly.
Predict
Halving data size (32-bit → 16-bit) often speeds up a memory-heavy loop by more than the arithmetic alone suggests. Why?
- 16-bit numbers are magic
- Twice as many values fit in each cache block and in the cache, so the miss rate falls
- The clock speeds up
- The compiler stops working
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Model your two systems. Pin the float version (your measured or estimated IC, CPI and miss rate). Then change only what precision changes: fewer instructions if SIMD packs more values, a lower miss rate if data is smaller. Does the model's speed-up match your measurement? Which factor explains most of it?
What the interactive shows, in words
The derivation splits a speed-up into factors: instruction-count ratio × CPI ratio × clock ratio. Halving instructions and cutting CPI from 2.2 to 1.6 predicts 2.75×, about two-thirds from fewer instructions and one-third from fewer cache-miss stalls.
Understand
Explain the numbers
For each metric, give the mechanism and check the size: operation counts for compute, bytes and AMAT for memory, quantisation step for accuracy, P = αCV²f and duty cycle for energy. A mechanism that predicts the right size of effect is far stronger than one that only predicts its direction.
Results that resist explanation
If the model leaves a gap, report it as an open question rather than stretching the explanation. 'The model predicts 2.75× but we measured 3.4×; we suspect hardware prefetching, which our model omits' is honest and useful.
The final report
Question and prediction; method (as pre-registered, with any deviations); results with uncertainty; first-principles explanation; recommendation from the pre-stated rule; limitations: simulation versus hardware, one workload, one compiler, toy data. No claim beyond the evidence.
Explain it another way: intuitive
A detective doesn't stop at 'the window was broken'; they explain how, and check the explanation fits every clue, including the ones that don't fit neatly.
Explain it another way: technical
Performance counters (instructions retired, cycles, cache misses, branch mispredictions) measure each Iron Law factor directly on real hardware; in simulation, the model provides them. Attribution should use the same counters for both systems.
Explain it another way: mathematical
Log-decomposition: ln S = Σ ln rᵢ, so each factor's share of the speed-up is ln rᵢ / ln S. Shares are additive in log space, unlike percentages of the raw ratio.
Explain it another way: applied
Performance engineers routinely present 'top-down' breakdowns of where cycles go (front-end stalls, back-end memory stalls, bad speculation, useful work) to justify which part of a system to optimise next.
Derivation: Decomposing a speed-up
T = IC × CPI × t_clk, with CPI = CPI_base + (memory accesses per instruction) × miss rate × miss penalty.
Speed-up S = T_A/T_B = (IC_A/IC_B) × (CPI_A/CPI_B) × (t_A/t_B). Taking logs, ln S = ln(IC ratio) + ln(CPI ratio) + ln(clock ratio): each factor's share adds.
Example: SIMD packing halves IC (ratio 2). Smaller data cuts the miss rate from 6% to 3% with 0.4 accesses per instruction and a 50-cycle penalty: CPI 1 + 1.2 = 2.2 → 1 + 0.6 = 1.6 (ratio 1.375). Clock unchanged.
Predicted S = 2 × 1.375 = 2.75×. If you measured 2.6× ± 0.1, the model explains it within uncertainty; the shares are ln 2 / ln 2.75 ≈ 68% from IC and 32% from CPI.
If the model and measurement disagree beyond uncertainty, something unmodelled matters (branch behaviour, prefetching, frequency scaling): say so and investigate.
Try these examples
Example 1
Float: IC 10⁹, CPI 1.8, 1 GHz. Int8: IC 0.3×10⁹, CPI 2.1, 1 GHz. Speed-up and its sources?
The worked solution is in the online lesson.
Common mix-ups
A good result needs no explanation.
✓ Without a mechanism, you cannot predict whether it will hold on the next workload or chip.If the model doesn't match, the experiment failed.
✓ A mismatch is information: it points to an effect your model left out.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A program executes 750 million instructions with an average CPI of 0.8 on a 2 GHz processor. How long does it take, in milliseconds?
Answer: ms
2. A pipeline has base CPI 1. Branches are 15% of instructions, 20% of them are mispredicted, costing 2 cycles each. Loads and stores are 20% of instructions, 10% of them miss in the cache, costing 100 cycles each. What is the effective CPI?
Answer:
3. Version B executes 0.5× the instructions of A, and its CPI falls from 2.0 to 1.5. Same clock. What speed-up does the Iron Law predict?
Answer: ×
4. Your model predicts 2.0× and you measured 2.9× ± 0.2. What should the report say?
- Adjust the model until it gives 2.9×
- The model explains part of the gain; the remaining gap is unexplained, with candidate causes and a test to check them
- Drop the measurement
- Claim the model is confirmed
5. L1: hit time 2 cycles, miss rate 5%. L2: hit time 8 cycles, local miss rate 40%. Main memory: 200 cycles. What is the AMAT in cycles?
Answer: cycles
6. Which is a genuine limitation to state for a browser-simulated precision study?
- 'Results are perfect'
- 'Results come from one workload in simulation; real hardware, compilers and data could change the ranking'
- 'No limitations'
- 'Someone else might disagree'
Apply it
Complete the term project report: results table with uncertainty, Iron Law and AMAT (or energy) decomposition of each difference, recommendation from your pre-stated rule, and a limitations section of at least four specific items.
Reflect
Which part of this term's toolkit (complexity, Iron Law, AMAT, yield, PPA, optimisation) do you expect to use first in your capstone, and for what?