AI Wiki中文/EN

Alpha–beta pruning

Alpha-beta 剪枝

Preserve minimax values while skipping refuted branches; distinguish search windows, returned bounds, equality cutoffs and depth estimates.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A reply can refute a move before every reply is known

MAX must choose one of three moves, A, B or C. After that, MIN chooses a terminal outcome. Every number below is utility for MAX; MIN prefers smaller values.

MAX’s moveMIN’s available outcomesExact value
A5, 8, 75
B5, −9, 6−9
C4, 10, 22

After examining A, MAX has a move worth 5. When searching B, the first reply also scores 5. MIN can choose that reply, so B cannot be worth more than 5. MAX can keep A without reading B’s other outcomes. For C, the first reply scores 4, which already rules it out. Only five terminal values were examined instead of nine.

This is alpha–beta pruning: stop exploring a branch once a bound proves that it cannot improve the decision being made above it. The exact root value remains 5. The returned number for B, however, might be 5 even though B’s exact value is −9. That difference will matter when choosing a move or caching results.

Berkeley’s course explains pruning through a known alternative at a MAX ancestor. Knuth and Moore’s 1975 analysis formalizes the search-window contract and proves correctness. Their paper analyzes an existing method; the date does not identify its invention. The table and program here are original examples. CS188, section 3.2.1, Knuth and Moore, pp.296–300

A window carries thresholds, not a promise about this node

Assume a finite, deterministic, two-player, zero-sum game with perfect information and alternating turns. All utilities are measured from MAX’s viewpoint. There are no chance nodes or hidden observations. Let V(s)V(s) be the minimax value for the tree being searched. For a depth-limited tree, the frontier evaluator is part of that definition; its answer need not equal the full game’s value.

An alpha–beta call receives a window (α,β)(\alpha,\beta) with α<β\alpha<\beta. Within the recursive search, alpha records a threshold established by MAX alternatives and beta records one established by MIN alternatives. These thresholds tell a descendant which distinctions still matter to its ancestors. An inherited alpha is not necessarily a lower bound on that descendant’s actual value. B in the opening example receives alpha = 5 and has value −9.

At a MIN node, suppose a searched child provides an upper bound uu with u≤αu\le\alpha. Then

V(s)≤u≤α.V(s)\le u\le\alpha.

Further MIN choices can only make its value smaller. A MAX ancestor already has an alternative meeting alpha, so the remaining siblings of this MIN node cannot make that branch preferable. The symmetric argument at a MAX node uses a known lower bound ℓ\ell with ℓ≥β\ell\ge\beta:

V(s)≥ℓ≥β.V(s)\ge\ell\ge\beta.

A MIN ancestor can use its existing alternative instead. Updating alpha upward at MAX nodes and beta downward at MIN nodes gives the usual stopping condition α≥β\alpha\ge\beta. Induction over the remaining depth makes this argument apply when the child itself returned a bound rather than an exact value. Pruning removes distinctions that the caller does not need; it does not assign exact values to every visited node.

The implementation below is fail-soft: a cutoff returns the best score encountered, which can lie outside the input window. Let rr be its return value and α0,β0\alpha_0,\beta_0 the window on entry. Its guarantee is

{V(s)≤r≤α0,r≤α0,V(s)=r,α0<r<β0,V(s)≥r≥β0,r≥β0.\begin{cases}V(s)\le r\le\alpha_0,&r\le\alpha_0,\\V(s)=r,&\alpha_0<r<\beta_0,\\V(s)\ge r\ge\beta_0,&r\ge\beta_0.\end{cases}

The first case is a fail-low result, stored as an upper bound; the last is fail-high, stored as a lower bound. A full window (−∞,+∞)(-\infty,+\infty) gives an exact value because every terminal or frontier score in this program is a finite integer. Knuth and Moore express the central inside/outside-window distinction in their equation 9. The stronger retained-score inequalities above are the contract of our fail-soft implementation, checked separately against exhaustive values. Section 2, pp.297–298

Return a score together with what it means

This complete Python 3.10+ example represents a terminal by an integer and an internal node by a nonempty tuple of children. All scores use MAX’s perspective, even when maximizing=False. A depth of 1 permits one edge before frontier evaluation; it does not mean a complete MAX–MIN round.

evaluate(node, is_max) is required if search reaches a nonterminal with no depth left. It must return an integer estimate. A real terminal is checked first and always uses its actual utility, including at depth 0. Boolean scores, negative depths, invalid windows and invalid visited nodes are rejected. The supplied tree must satisfy the representation throughout; the program checks only visited nodes and does not validate pruned subtrees in advance.

move is an index among the root’s children. It is None for a terminal or a depth-zero frontier. With an exact result at a searched internal root, it identifies the first optimal child in the supplied order. With an upper or lower bound, treat it as a search candidate rather than a certified optimal move. The bound label is conservative: even a known terminal is labeled by its relation to the input window.

evaluations counts terminal reads plus frontier-evaluator calls. cutoffs counts occasions on which a closed window actually skips at least one sibling. Values are not clipped to alpha or beta.

from math import inf


def alpha_beta(tree, depth, maximizing=True, alpha=-inf, beta=inf, evaluate=None):
    if type(depth) is not int or depth < 0 or type(maximizing) is not bool:
        raise ValueError('depth must be a nonnegative integer; maximizing must be boolean')
    if any(type(v) not in (int, float) or v != v for v in (alpha, beta)) or alpha >= beta:
        raise ValueError('need numeric, non-NaN bounds with alpha < beta')
    if evaluate is not None and not callable(evaluate):
        raise ValueError('evaluate must be callable or None')
    original_alpha, original_beta = alpha, beta
    stats = {'evaluations': 0, 'cutoffs': 0}

    def visit(node, remaining, is_max, a, b):
        if type(node) is int:
            stats['evaluations'] += 1
            return node, None  # A real terminal overrides the depth cutoff.
        if type(node) is not tuple or not node:
            raise ValueError('internal nodes must be nonempty tuples; terminals are integers')
        if remaining == 0:
            if evaluate is None:
                raise ValueError('nonterminal depth cutoff needs an evaluator')
            value = evaluate(node, is_max)
            if type(value) is not int:
                raise ValueError('the evaluator must return an integer')
            stats['evaluations'] += 1
            return value, None
        value = -inf if is_max else inf
        move = None
        for index, child in enumerate(node):
            score, _ = visit(child, remaining-1, not is_max, a, b)
            if (is_max and score > value) or (not is_max and score < value):
                value, move = score, index  # Keep the first best move on equality.
            if is_max:
                a = max(a, value)
            else:
                b = min(b, value)
            if a >= b:
                stats['cutoffs'] += int(index+1 < len(node))
                break
        return value, move

    value, move = visit(tree, depth, maximizing, alpha, beta)
    bound = 'upper' if value <= original_alpha else 'lower' if value >= original_beta else 'exact'
    return {'value': value, 'bound': bound, 'move': move, **stats}


TREE = ((5, 8, 7), (5, -9, 6), (4, 10, 2))
print(alpha_beta(TREE, 2))
print(alpha_beta((TREE[1], TREE[2], TREE[0]), 2))
print(alpha_beta(TREE[1], 1, maximizing=False, alpha=5))
estimates = {TREE[0]: 0, TREE[1]: 9, TREE[2]: 1}
print(alpha_beta(TREE, 1, evaluate=lambda node, is_max: estimates[node]))

The four outputs are:

{'value': 5, 'bound': 'exact', 'move': 0, 'evaluations': 5, 'cutoffs': 2}
{'value': 5, 'bound': 'exact', 'move': 2, 'evaluations': 9, 'cutoffs': 0}
{'value': 5, 'bound': 'upper', 'move': 0, 'evaluations': 1, 'cutoffs': 1}
{'value': 9, 'bound': 'exact', 'move': 1, 'evaluations': 3, 'cutoffs': 0}

The second run orders moves B, C, A. Their values successively improve MAX’s alternative, so all nine outcomes are read. The third run isolates B with alpha = 5: return 5 means “at most 5”; its exact value remains −9. The last run stops after one edge and uses deliberately misleading estimates A → 0, B → 9, C → 1. It exactly solves that estimated frontier tree and selects B, whose actual full-depth value is −9. Safe pruning cannot repair an inaccurate evaluator.

The accompanying tests flatten each tree into an explicit frontier, then compute exhaustive values bottom-up. They compare all 38=65613^8=6561 assignments of −1,0,1 to the leaves of a depth-three binary tree, for both root players and several windows. Separate checks cover ragged trees, early terminals, depth cutoffs, bound direction, root actions and move ordering. The oracle contains no alpha or beta variables.

Order, equality, and the cost of looking deeper

Equality is enough for a cutoff when preserving the root value and one optimal move. It does not identify every optimal move, nor every child’s exact score. In the table, A returns exact 5 and B returns an upper bound of 5. If the root replaces A with B merely because their returned numbers tie, it chooses a move worth −9. The strict best-move comparison in the code keeps the first alternative and avoids that error. To enumerate all optimal actions, obtain adequate exact information about each candidate instead of treating equal bounds as equal values.

A course assignment may require a different visitation pattern. Berkeley’s Spring 2026 Project 2 explicitly forbids equality pruning to match its autograder. That is a stated interface requirement for that assignment, not a counterexample to the cutoff proof above. This article implements its own tree interface and equality rule. Project 2, Q3

For a complete uniform tree with branching factor b≥2b\ge2, depth dd, finite scores and an optimal child examined first at every internal node, the number of evaluated leaves is

L(b,d)=b⌈d/2⌉+b⌊d/2⌋−1.L(b,d)=b^{\lceil d/2\rceil}+b^{\lfloor d/2\rfloor}-1.

For b=3,d=4b=3,d=4, this is 17 leaves instead of 81. The two terms count leaves whose path always takes the first child at alternating levels; the all-first-child path belongs to both sets and is subtracted once. At fixed bb, this gives the familiar best-order scale O(bd/2)O(b^{d/2}). The worst case remains O(bd)O(b^d). Finding a good ordering is work too; the algorithm does not know exact child values for free. Knuth and Moore prove the regular-tree count and also show that “best child first” need not minimize work on every irregular tree. Section 6, pp.305–307

For this implementation, a search visiting MM nodes uses O(M)O(M) time when a score comparison and frontier evaluation take constant time. More generally, add the total evaluator cost. The recursion stack uses O(d)O(d) auxiliary space and can hit Python’s recursion limit on deep trees. The supplied nested tree already occupies memory for all its nodes; this teaching representation does not save the cost of building skipped branches. A game engine can generate children on demand, but must then account for move generation and state-copying costs.

A cached fail-high score is a lower bound, not an exact transposition value. Reusing such results requires bound type, remaining depth, player-to-move and compatible evaluation context. This code has no transposition table. Chance nodes require reasoning about weighted sums; replacing MIN by an average while retaining the same cutoff test is not justified.

Decide what can be skipped

1. B returns 5 after seeing only its first outcome. What does that establish, and why must MAX retain A on this tie?

Answer: B’s value is at most 5. Its unseen outcome −9 makes its actual value −9. A is already known to guarantee 5. Equal returned numbers do not establish equal exact child values, so replacing A with B is unjustified.

2. A MAX node has leaf children 8 and 12 and is searched with beta = 5. What does fail-soft return, and what is still unknown?

Answer: It reads 8, stops, and returns 8 as a lower bound. The true node value is at least 8; reading the second leaf would establish 12. Returning the window boundary 5 instead would discard a stronger bound. Neither 5 nor 8 should be stored as this node’s exact value.

3. Why can the depth-one run say “exact” while choosing B, which loses −9 under full search?

Answer: “Exact” refers to the minimax value of the specified truncated tree. At depth 1 its leaves are the supplied estimates 0,9,1, so MAX chooses 9. Those estimates are not terminal game utilities. Searching to depth 2 replaces them with the actual reply outcomes and selects A at 5.

4. For a regular binary tree of depth 5 with perfect ordering, how many leaves are evaluated? Does reordering always change the answer?

Answer: The count is 2³+2²−1=11, compared with 32 exhaustive leaves. Reordering preserves the full-window minimax value. It changes the work and can change which truly tied optimal move is retained. It cannot justify reporting every pruned child’s return as exact.

Pruning changes the work, not the adversarial model

Minimax defines the adversarial objective. Alpha–beta searches that same fixed tree more selectively. Move ordering and repeated depth searches can help establish useful bounds earlier, while an evaluator decides what a truncated leaf means. These are separate design choices and should be measured separately.

A useful experiment reports root value, selected move, searched depth, evaluated leaves, move-generation work and elapsed time. Verify narrow-window outputs against exhaustive values on small trees before adding caches or ordering heuristics. A function returning the right root score once can still have a reversed bound label or choose the wrong action on an equality cutoff.

The primary paper supplies correctness and conditional node-count analysis; the course supplies another explanation and a concrete contrasting grading convention. None of the source game benchmarks is reproduced here. The examples, finite-tree enumeration and returned-bound checks are original work for this edition.

Make a prediction, then check

A has exact value5. A MIN search of B reads its first result5 and cuts off,returning5. Can that justify replacing A with B?

Choose one answer

Learning objectives

  • Prove pruning from ancestor alternatives and distinguish window thresholds,exact values and returned bounds.
  • Check the tied-action trap,move-order counts and depth evaluation while verifying narrow-window bound directions.

Prerequisites & connections

Explore related knowledge →

References

  1. An Analysis of Alpha-Beta Pruning
    Donald E. Knuth; Ronald W. Moore · 1975
  2. CS188 — 3.2 Minimax
    University of California, Berkeley; CS188 course staff
  3. CS188 Spring2026 — Project2: Multi-Agent Search, Q3
    University of California, Berkeley; CS188 course staff · 2026

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable examples, independent finite-game oracles, bilingual review and a second Codex agent cross-check; not independent human peer review.

  • Compared both languages for MAX perspective,per-edge depth,terminal priority,window contract,strong fail-soft bounds,equality-pruning action trap,ordering and complexity qualifications; four display equations and Python blocks match exactly.
  • Seven independent tests passed:6,561 depth-three binary leaf assignments × both root players × five windows,against explicit-frontier bottom-up extrema without alpha/beta. Also120 ragged random trees,depths0–4,both players,early terminals,invalid inputs,duality,bound labels and regular-tree leaf counts.
  • Executed the complete migrated example:5-vs9 evaluations, B returns upper bound5 despite exact value−9, and shallow estimates choose B with value9. Both articles now reside in src/content/articles; tests read them with the repository test_sample_articles.example helper. Review remains written pending parent integration and review registration; no independent human expert review claimed.
  • Both migrated locales compiled independently with the current project MDX compiler, remark-math and strict KaTeX, with no compiler messages. The stock-phrase scan of these two articles passed. No whole-site check/build ran or modified shared build state.
  • Reread the migrated articles and revisited the prior second-agent cross-check:10,800 additional ragged-tree/depth/player/window cases and360 nonconstant perfectly ordered regular trees passed. Migration changed no algorithms, equations, sources or exercises; English only fixes three spaces before numbers, while Chinese is byte-identical. Both Python blocks and all four display equations remain identical to the drafts.
  • The original draft en.mdx, zh.mdx, metadata.json and test file remain in place with SHA256 values matching the pre-migration snapshot. Only the two published-path articles and migrated test were added; shared sources, catalogue, counts, reviews and docs were not edited. Whole-site typing, links, build and browser checks remain for parent integration.
  • Root reread the complete English article: inherited thresholds are not actual descendant bounds, fail-soft labels use the original window, strict improvements retain moves, terminals precede cutoffs, and regular-tree leaf-count and space conditions are retained.
  • All 79 search checks, 105 article Python programs and the prose scan passed. Migration-stage written-status notes describe that earlier phase; this record registers the checked files after source review and binds their current hashes. All reviews are AI technical checks, not independent human peer review.

Source locations checked:

  • An Analysis of Alpha-Beta Pruning · Read original printed pp.296–300 (§2 bounds, equation9 window contract, minimax/negamax forms), p.302 (artificial terminal evaluation), pp.305–307 (§6 Theorem1, Corollary1 and irregular-tree caveat). Visually checked p.297 equation9 and p.306 equation13 from the downloaded PDF after web screenshot cache failure. The stronger retained-score inequalities are independently proved/tested for our fail-soft code, not attributed verbatim to equation9.
  • CS188 — 3.2 Minimax · Read §3.2.1 lines113–126 and §3.2.2 lines127–139: ancestor-alternative pruning, root-value preservation and cutoff evaluation. Also checked §3.2 terminal utility and alternating player viewpoint. Own example uses fixed MAX-perspective values5/-9/2 rather than course game scores.
  • CS188 Spring2026 — Project2: Multi-Agent Search, Q3 · Read Q3 lines213–224: root value/action distinction, preserve provided child order, and explicit no-pruning-on-equality requirement for its autograder. Described as an assignment-specific interface requirement, not a mathematical ban on equality cutoff.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.