Exercises — Chapter 34

Difficulty: ⭐ recall and concepts · ⭐⭐ apply to a position or a short script · ⭐⭐⭐ analyse, judge, transfer · ⭐⭐⭐⭐ open-ended research.

All scripts live in this chapter's code/ folder and import project/outpost/engine_lab.py. Run them from the chapter directory. A pure-Python engine is slow — keep depths low and node budgets modest, and say so when you report a result.


Part A — Concepts ⭐

A1. Define perft(d) in one sentence. Why is perft a test of the move generator and not of the engine?

Answer

perft(d) is the number of distinct move sequences (leaf positions, counted with repetition) of exactly d plies from a position, using only legal moves. It contains no evaluation and no search decisions, so if your count differs from the published number the error must be in move generation or make/unmake — castling, en passant, promotion, pins or checks. It says nothing about whether the engine plays well.

A2. Shannon (1950) distinguished "Type A" and "Type B" programs. Explain the difference and say which type Stockfish's search resembles today, and why the answer is "both".

Answer

Type A searches every legal move to a fixed depth (full width); Type B looks only at a selection of plausible moves, more deeply. Modern alpha-beta engines start full-width but prune and reduce so aggressively (late-move reductions, null-move pruning, futility pruning) that, in effect, they search a few moves deeply and the rest shallowly — a Type A skeleton with Type B behaviour. Chapter 34's node counts show this: Stockfish 19 reaches depth 20 with an effective branching factor near 1.5, far below the ~40 legal moves per position.

A3. Minimax and alpha-beta return the same value at the same depth. Then what, exactly, does alpha-beta save? And why does the saving depend on move ordering?

Answer

Alpha-beta skips branches that cannot change the result: once a move is refuted (the opponent has a reply at least as good for them as something we already have), the remaining replies need not be searched. How early the refutation is found decides how much is skipped — try the best move first and the cut-off comes immediately; try it last and alpha-beta degenerates towards minimax. Hence captures-first ordering, hash moves and killer moves.

A4. What is the horizon effect? Give the two-sentence version of how quiescence search fixes it, and one cost of the fix.

Answer

A fixed-depth search evaluates the position at the last ply even if a capture sequence is half-finished, so it can "see" a pawn won and miss the recapture one ply later, or push an inevitable loss just beyond its depth. Quiescence search keeps searching captures (and check evasions) beyond the nominal depth until the position is quiet, then evaluates. Cost: it can dominate the node count — in our engine more than 90% of all nodes at depth 5 were quiescence nodes.

A5. Name the two outputs of AlphaZero's neural network and say what each one replaces in a classical engine.

Answer

A policy (a probability for each legal move) and a value (an expected result for the position). The policy replaces hand-written move ordering and selectivity — it tells the tree search which moves to look at; the value replaces the hand-written evaluation function and, in AlphaZero's MCTS, the random playouts of older Monte Carlo methods.

A6. What does NNUE stand for, and what does "efficiently updatable" mean in practice?

Answer

Efficiently Updatable Neural Network (introduced by Yu Nasu for computer shogi in 2018). The first layer's output (the "accumulator") depends on which pieces stand on which squares; when one move changes only two or three piece–square pairs, the engine adds and subtracts just those columns instead of recomputing the layer. That makes a neural evaluation cheap enough to run inside a fast alpha-beta search on an ordinary CPU.

A7. True or false, with a reason: "Deep Blue beat Kasparov in both of their matches."

Answer

False. Kasparov won the 1996 Philadelphia match 4–2; Deep Blue won the 1997 New York rematch 3½–2½. Our master-games data contains all twelve games, and the results reproduce both scores.

A8. Why is a node-limited Stockfish (for example go nodes 100) a better sparring partner for measuring a hobby engine than Stockfish's Skill Level setting?

Answer

A node limit is deterministic and easy to describe: the same position and the same limit give the same move, so a match can be rerun and the result reproduced. Skill-level weakening deliberately injects randomness into move choice, so results vary from run to run and are harder to interpret. (Both are artificial; neither is "a 1500 player".)


Part B — Positions ⭐⭐

Every position below is from a real game (or from engine_lab's own match games) and every solution was checked with Stockfish 19 at the depth stated. Evaluations are from White's point of view.

B1. Find the tactic. The Opera Game (Morphy vs the Duke of Brunswick and Count Isouard, Paris 1858), White to move.

Opera Game before White's 16th move

♟️ Position: White Kc1, Qb3, Rd1, Bg5, a2, b2, c2, e4, f2, g2, h2; Black Ke8, Qe6, Rh8, Bf8, Nd7, a7, e5, f7, g7, h7 — White to move. FEN: 4kb1r/p2n1ppp/4q3/4p1B1/4P3/1Q6/PPP2PPP/2KR4 w k - 0 16

Solution

16.Qb8+! Nxb8 17.Rd8# — Stockfish 19 at depth 20 reports #2 with exactly this line, and engine_lab's alpha-beta finds it at depth 3 with 4,142 nodes. The d7-knight is the only piece guarding both b8 and d8; the queen sacrifice deflects it and the rook, backed by the g5-bishop, mates. Note that engine_lab's static evaluation of the diagram is −0.86 (White has given material): only search sees the mate.

B2. Analyze this position (horizon). An OTB game played in January 2026, Black to move. White's queen attacks the rook on g7.

Black to move: save the rook or take the bishop?

♟️ Position: White Kg1, Qf6, Rb1, Bd3, Bd6, a3, e5, f2, g3, h2; Black Ka8, Qd4, Rd8, Rg7, Be8, a7, b7, d5, e6 — Black to move. FEN: k2rb3/pp4r1/3BpQ2/3pP3/3q4/P2B2P1/5P1P/1R4K1 b - - 2 35

Solution

35...Rgd7 holds the balance: 0.00 (Stockfish 19, depth 16). The tempting 35...Rxd6? (taking the bishop) is refuted not by a recapture but by 36.Qxg7, taking the other rook: +4.91 at depth 16. A depth-2 search without quiescence chose 35...Rxd6 because its lines ended right after White's reply and it misjudged the material; with quiescence, the same depth-2 search chose 35...Rgd7.

B3. Find the tactic (and avoid the trap). engine_lab vs Stockfish (one node per move), French Advance; engine_lab is Black and to move.

Black to move: two ways to attack

♟️ Position: White Kg1, Qb3, Re1, Ba3, Nb1, Ne5, a2, f3, g2, h2; Black Ke8, Qa1, Ra8, Rh8, Ba6, Ne4, a7, c3, c6, d5, e6, g7, h7 — Black to move. FEN: r3k2r/p5pp/b1p1p3/3pN3/4n3/BQp2P2/P5PP/qN2R1K1 b kq - 2 17

Solution

17...c2! wins: −6.19 (Stockfish 19, depth 20), threatening ...cxb1=Q. engine_lab played 17...Bc4??, which attacks the queen but allows a forced mate in three (#3 at depth 20). Our engine completed only depth 2 within its 5,000-node budget, and its quiescence search follows captures, not quiet mating moves. (The one-node Stockfish missed the mate too, and engine_lab won the game.) Before playing an attacking move, check the opponent's checks.

B4. Find the tactic (defence). engine_lab vs Stockfish (100 nodes per move), Queen's Gambit Declined; Black (Stockfish) to move. Black can take a knight on d4.

Black to move: is 12...Qxd4 safe?

♟️ Position: White Kg1, Qd1, Ra1, Rf1, Bd3, Bf4, Nc3, Nd4, a2, b2, e4, f2, g2, h2; Black Ke8, Qd8, Ra8, Rh8, Bb7, Bf8, Ne5, Nf6, a6, b5, e6, f7, g7, h7 — Black to move. FEN: r2qkb1r/1b3ppp/p3pn2/1p2n3/3NPB2/2NB4/PP3PPP/R2Q1RK1 b kq - 2 12

Solution

No: 12...Qxd4? 13.Bxb5+! (a check that uncovers the d1-queen against d4) axb5 14.Qxd4 wins the queen back with interest: +7.08 (Stockfish 19, depth 12) after 12...Qxd4, against −1.21 after the best move, 12...Nxd3 (Black is better). The pattern: a queen on the same file as the enemy queen with one of your own pieces between them — moving that piece with check is a discovered attack.

B5. Build the plan. Caruana–Nakamura, Candidates 2026, round 1. White to move.

White to move: how to increase the pressure?

♟️ Position: White Kg2, Qg4, Rf1, Bd5, a4, c4, d3, f2, g3, h4; Black Kg8, Qf6, Re8, Bc5, a5, b6, d4, f7, g7, h7 — White to move. FEN: 4r1k1/5ppp/1p3q2/p1bB4/P1Pp2QP/3P2P1/5PK1/5R2 w - - 7 30

Solution

30.h5! — Stockfish 19's first choice, +1.12 at depth 20 and +1.05 at depth 24 (multi-PV 3 at depth 20: h5 +1.24, Rh1 +1.03, Qd7 +0.65). The pawn takes g6 from Black's pieces and prepares Rh1 and h6; with the d5-bishop pinning f7 and Black lacking a light-squared bishop or knights, White's own king is not weakened by the advance. Caruana played it and won.

B6. Analyze this position (history). Deep Blue–Kasparov, New York 1997, game 2, after 45.Ra6. Black to move.

Black to move after 45.Ra6

♟️ Position: White Kf1, Qc6, Ra6, Be4, b4, c3, d5, f5, g2, h3; Black Kf7, Qb6, Rb8, Bd6, b5, c4, e5, f6, g7, h6 — Black to move. FEN: 1r6/5kp1/RqQb1p1p/1p1PpP2/1Pp1B3/2P4P/6P1/5K2 b - - 14 45

Solution

45...Qe3! is the only real try — Stockfish 19 at depth 24, multi-PV 3: Qe3 +1.10, Qxc6 +5.31, Qd8 +7.02. The queen counterattacks White's king and, after 46.Qxd6 Re8, collects checks and the e4-bishop. Stockfish still rates White better at depths 24–30 (about +1.1), so "Black had a forced draw" is more than the engine will confirm; "Black had serious counterplay" is what it supports. The game record continues 45...h5, after which White wins (+11.71 at depth 20).

B7. Find the best move. Deep Blue–Kasparov, Philadelphia 1996, game 1. Black to move; White is already clearly better (+3.00 at depth 24).

Black to move in Deep Blue–Kasparov 1996, game 1

♟️ Position: White Kg1, Qd5, Rc7, Nb7, a3, b3, f2, g3, h3; Black Kh8, Qf6, Rg8, Nd3, d4, f3, f7, h7 — Black to move. FEN: 6rk/1NR2p1p/5q2/3Q4/3p4/PP1n1pPP/5P2/6K1 b - - 2 32

Solution

Stockfish 19's choice is 32...Rg5 (+3.00 at depth 24), bringing the rook into the attack on White's king with tempo on the queen. Kasparov played 32...Re8, after which White's lead grows to +5.90 (depth 24): 33.Nd6 Re1+ 34.Kh2 Nxf2 35.Nxf7+ — the knight joins the attack on f7 and the black king. Black was losing either way, but 32...Rg5 kept practical chances.

B8. Engine analysis (judgment). Deep Blue–Kasparov, New York 1997, game 2. White to move (move 37).

White to move: 37.Be4 or 37.Qb6?

♟️ Position: White Kg1, Qf2, Ra1, Ra2, Bc2, b4, c3, d5, f5, g2, h3; Black Kg8, Qe8, Ra8, Rc8, Bd6, b5, c4, e5, f6, g7, h6 — White to move. FEN: r1r1q1k1/6p1/3b1p1p/1p1PpP2/1Pp5/2P4P/R1B2QP1/R5K1 w - - 0 37

Solution

37.Be4 — Stockfish 19's first choice in multi-PV 3 at depth 20 (+1.29) and depth 24 (+1.03), and in a single-line depth-24 search (+1.19); the queen raid 37.Qb6 scores only +0.44 to +0.47. Keeping the bishop on the long diagonal controls a8 and the light squares, and leaves Black without counterplay. This was Deep Blue's move.


Part C — Data & Code ⭐⭐–⭐⭐⭐

C1. Perft table ⭐⭐. Extend 01_perft.py to print perft_breakdown for Kiwipete at depth 2 and position 5 (rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8) at depth 2. Output: one line per position with nodes, captures, en passant, castles, promotions, checks and checkmates. Check that the node counts equal 2,039 and 1,486.

Hint

Kiwipete's depth-2 breakdown should show a single en passant capture: our perft bug hunt found that the no-en-passant generator is exactly one leaf short at depth 2 (2,038 vs 2,039). Use that as a check on your output.

C2. Ordering ablation ⭐⭐. Using count_nodes and the 12 OTB positions of 02_search_nodes.py, add a fourth ordering mode to Searcher — "killers only" (no captures-first) — and report the median nodes at depths 3 and 4 alongside the existing variants. Expected shape: a 4-column table; the value column must still agree with minimax.

C3. Better evaluation, better correlation? ⭐⭐⭐. Add a mobility term (number of legal moves × 3 cp, from White's view minus Black's) to a copy of evaluate. Rerun Part 1 of 03_eval_vs_stockfish.py on the same 240 positions. Report Pearson r overall, by phase, and for the 128 level-material positions. Does mobility help the static evaluation more than three plies of search would? (Compare with r = 0.812 static and 0.901 at depth 3.)

C4. A rematch ⭐⭐⭐. Rerun 04_match.py with engine_lab at 20,000 nodes per move against Stockfish at 100 nodes only (12 games). Report the score with a Wilson interval and compare with the 33.3% [14–61%] at 5,000 nodes. Budget the time first: our engine averaged 0.46 s per move at 5,000 nodes.

C5. Stockfish's effective branching factor by phase ⭐⭐. Modify stockfish_nodes in 02_search_nodes.py to sample 10 opening, 10 middlegame and 10 endgame positions (broadcast human games, seed 2026) and compute the geometric EBF between depths 10 and 20 for each phase. Output: a 3-row table (phase, median EBF, median nodes to depth 20).

C6. MCTS budget curve ⭐⭐⭐. For the Opera Game position, run engine_lab.mcts with 10 different seeds at each of 1,600, 3,200 and 6,400 simulations. Report the share of runs in which 16.Qb8+ is the most-visited move. What does the answer say about the role of the prior?

C7. The h-pawn by rating ⭐⭐⭐. Repeat 08_h_pawn_years.py for master games with both players rated 2400–2599 instead of 2600+. Is the 2010–2017 vs 2019–2026 rise also visible one level down? Report the two shares with Wilson intervals and sample sizes.


Part M — Mixed / Interleaved ⭐⭐–⭐⭐⭐

M1 (with Chapter 10) ⭐⭐. Chapter 10's calc.py has a checks-only mate search. Run it on the B3 position (after 17...Bc4) with White to move and n = 3. Does it find the mate that engine_lab missed, and with how many nodes? Explain why a narrow checks-only search succeeds where a broad but shallow search failed.

Answer

A mate in three needs five plies of look-ahead. engine_lab's full-width search ran out of its node budget at depth 2 in that busy position, because it spent its nodes on every legal move and on resolving captures. A checks-only search for the attacker has a branching factor of only a handful of moves (Chapter 10 found 3.4 legal replies on average after a check), so it reaches five plies cheaply. Selectivity, not raw effort, finds forcing wins — which is why engines extend checks and why humans scan checks first.

M2 (with Chapter 3) ⭐⭐. engine_lab's knight table gives a corner knight −15 and a central knight +15. Chapter 3 measured a knight on the rim against the centre in real games. Is a 30-centipawn spread consistent with what Chapter 3 found? Explain one reason a search engine might want a smaller or larger value than the data suggests.

Answer

Chapter 3 measured outcomes of real games, which mix the knight's placement with everything correlated with it (who is better, which openings produce rim knights). An engine's table is a heuristic for move ordering and leaf evaluation: too large a value makes the search waste moves re-centralising knights or refuse useful rim moves (a knight on a4 heading for c5); too small, and it drifts into passive placements. Engine developers tune such values by playing games, not by fitting outcome data — the two numbers answer different questions.

M3 (with Chapter 23) ⭐⭐⭐. Chapter 23 warned that single-PV and multi-PV searches can rank near-equal moves differently. Find two places in this chapter where we report both for the same position, and state the numbers. Would your practical conclusion change in either case?

Answer

Caruana–Nakamura before 30.h5: single-line +1.12 (d20) / +1.05 (d24), multi-PV 3 h5 +1.24 at d20 — same move first, conclusions unchanged. LCZero–Stockfish before 21.Rxe4: multi-PV 3 at d20 ranks Bxh3 −1.08 and Rxe4 −1.41, while a single-line d20 search after Rxe4 gives −1.04 — the ranking is inside the methods' disagreement, so "Rxe4 was a mistake" is not a safe conclusion. (Deep Blue game 2, move 37: Be4 first in both modes — +1.29/+1.03 multi-PV, +1.19 single-line at d24.)

M4 (with Chapter 30) ⭐⭐⭐. Our match produced 7/12, 4/12 and 1.5/12 against three Stockfish node limits. Using the Elo formula, convert each score to a rating difference and give a rough interval from the Wilson bounds. Then explain why these differences cannot be added up into a "rating" for engine_lab.

Answer

The difference D solves E = 1/(1 + 10^(−D/400)), i.e. D = 400·log10(E/(1−E)). For 58.3%: D ≈ +58 (Wilson 32–81% → about −131 to +252). For 33.3%: D ≈ −120 (14–61% → about −315 to +77). For 12.5%: D ≈ −338 (3–40% → about −604 to −70). The intervals are hundreds of points wide. They cannot be turned into a rating because the opponents are not on any calibrated scale (a node-limited Stockfish is not a rated player), because twelve games per level is far too few, and because engines' errors are of a different kind from humans', so the Elo model's assumptions about consistent performance across opponents do not obviously hold.

M5 (with Chapter 4) ⭐⭐. Chapter 4 found h-pawn storms rising from 16.0% of O-O vs O-O master games in the 1970s to 27.4% in the 2020s; this chapter found 11.0% → 15.9% from the 2000s to 2019–2026. Why are the two chapters' levels different though both use master games? (Hint: compare the filters.) Does the difference matter for the conclusion?

Answer

Chapter 4 counted all slow master games in which both sides castled kingside, at any rating, with no ply limit; this chapter required both players to be rated 2600+ and the push to come before ply 80. Different populations and windows give different levels. The conclusion — a rise over time — holds in both, which is the point of checking a trend with two definitions; neither can say why it rose.


Part D — Judgment & Transfer ⭐⭐⭐

D1. "Engines think like this, so I should too." Lena reads that Stockfish searches millions of positions and concludes she should "calculate everything". Using this chapter's node counts (minimax vs alpha-beta, Stockfish's effective branching factor near 1.5) and Chapter 10's forcing-move counts, write a short reply: what is the human analogue of move ordering, and of pruning? What changes for a 1200 player compared with a 2000 player?

Model answer

The lesson from engines is not "more nodes" but "the right nodes first". Alpha-beta's savings come almost entirely from trying the best candidates first, and Stockfish's depth comes from searching unpromising moves shallowly. The human analogue of ordering is the checks–captures–threats scan of Chapter 10 (about 6 forcing moves among ~35 legal ones in a middlegame); the analogue of pruning is dismissing quiet moves that do nothing against the opponent's threat. At 1200 the biggest gain is the ordering habit itself — most losses come from not looking at the opponent's forcing moves at all. At 2000 the gain is in pruning well: knowing which long lines need checking and which can be judged by evaluation (structure, activity, king safety) instead of calculation.

D2. Are engines creative? Sam says no ("it's arithmetic"), Dev says yes ("nobody told AlphaZero to push the h-pawn"). Write 200 words taking a position, using at least one piece of evidence from this chapter (the h-pawn trend data, Game Changer, the Deep Blue game 6 knight sacrifice, or our MCTS demo). Then write 100 words arguing the opposite side.

D3. When the engine number misleads. Our engine_lab picked 24.Qxd6 in the Kasparov–Topalov position while Stockfish 19 picks 24.Rxd4 but does not rate it winning. A club player sees "24.Rxd4 is the best move, −0.40" in an app. What should they conclude, and what should they not conclude? Connect your answer to Chapter 23's point about depth.

Model answer

They can conclude that, at the depth shown, the engine prefers the rook sacrifice to the alternatives — and that the alternatives are not better. They should not conclude that the sacrifice wins, or that it is "−0.40 and therefore bad"; an eval near zero after a spectacular sacrifice says the resulting position is roughly balanced with best defence, and humans rarely find best defence. Depth matters: Stockfish's verdict on this position moves with depth (Chapter 1 settled it at −0.46 at depth 12 to −0.17 at depth 32), so a single shallow number is a snapshot, not a ruling.

D4. Human vs machine, 1997 and now. In 1997 one match was front-page news; today a phone app beats every human. Using Case Study 1, explain why Deep Blue's 1997 win is still worth studying for a human player — what did Kasparov's game 6 opening choice show about playing against a calculating opponent?

Model answer

Game 6 shows how fast a single opening inaccuracy is punished by a calculating opponent: 7...h6 moved the position from +0.40 to +0.98 (Stockfish 19, depth 24), and the machine answered with the knight sacrifice 8.Nxe6, which is Stockfish 19's own first choice. Black's king never got castled; the game lasted 19 moves. For humans the lesson is general: against a strong calculator, choose positions where your understanding is an advantage, not sharp ones where one concrete line decides. The same idea underlies Grace's opening choice in Chapter 24.


Part E — Research & Extension ⭐⭐⭐⭐

E1. Make engine_lab stronger, and prove it. Add one feature to engine_lab.py — null-move pruning, late-move reductions, a mobility term, passed-pawn bonuses, or a better quiescence (static exchange evaluation to skip losing captures). Then rerun 04_match.py twice: once with the feature, once without, same openings, same node budget. Report the score difference with a Wilson interval and say honestly whether 36 games can distinguish your change from noise. (Hint: they usually cannot. Engine developers test changes over tens of thousands of games for exactly this reason.)

E2. Tune the evaluation on real games. Chapter 6 fitted piece values from 137,264 quiet OTB positions (P 1.12, B 3.06, R 4.81, Q 9.01 with N fixed at 3). Replace engine_lab's 1/3/3/5/9 with those values (and Chapter 6's bishop-pair estimate), and measure (a) the correlation of the static evaluation with Stockfish on the 240 positions of 03_eval_vs_stockfish.py, and (b) the match result. Does a "data-fitted" value table make a better engine? Write up why it might not — the fitted values describe outcomes of human games, not the needs of a search.

E3. The draw problem, a season later. Use the broadcast data's TCEC games (Case Study 2) as a baseline. When newer broadcast data is available, rerun 07_tcec.py and compare the draw rate in the top events and the share of opening pairs decided by the colour, not the engine. Write a one-page memo: is engine chess becoming "solved-looking" in the openings TCEC assigns, and what would you change in the format?