Algorithm Search⌘K

Algorithmadvanced

Sequence-form linear program

Also called sequence-form LP for zero-sum games.

Solves a two-player zero-sum extensive-form game with perfect recall by a linear program of size linear in the game tree.

Time
poly(N, L) worst
Space
O(N^2) extra
Where
L = the bit length of the payoffs and chance probabilities; N = the number of nodes of the game tree
Properties
deterministicexactofflineiterative
Origin
Daphne Koller, Nimrod Megiddo, Bernhard von Stengel, 1996

The sequence-form linear program finds the value and optimal strategies of a two-player zero-sum game in extensive form with imperfect information and perfect recall, such as a small poker game. It writes the strategies of both players in the sequence form, where a strategy is a vector with one entry per sequence of own moves and a few linear equations, and then solves one linear program whose size is linear in the game tree. The sequence form itself is a representation and has its own page; this page is the algorithm. It replaces the LP for matrix games, which on the normal form of a game tree can be exponentially large, and it differs from counterfactual regret minimization, which approximates the same equilibrium by repeated play.

In plain words

A strategy in a card game says what to do in every situation you can tell apart. Listing whole strategies gives far too many. Instead, keep for each line of your own moves the chance that you play all of it. These numbers must add up the right way: the chance of a line equals the sum of the chances of its continuations. The expected payoff is then a simple sum over the leaves of the tree. For a fixed plan of the first player, the best reply of the second player is a small linear program, and its dual can be merged into the first player's problem. The result is one linear program. Its solution gives the first player's plan, and its dual prices give the second player's plan.

The problem

Input: a finite game tree with two players and chance moves, information sets with perfect recall, and payoffs u(ℓ)u(\ell) to player 1 at the leaves; player 2 gets −u(ℓ)-u(\ell). Output: the value vv of the game and realization plans xx and yy, so that xx guarantees player 1 at least vv against every strategy of player 2 and yy holds player 1 to at most vv against every strategy of player 1.

In the sequence form, player 1's plans are X={x:Ex=e, x≥0}X = \{x : E x = e,\ x \ge 0\} and player 2's are Y={y:Fy=f, y≥0}Y = \{y : F y = f,\ y \ge 0\}, where e=(1,0,…,0)e = (1, 0, \ldots, 0) and f=(1,0,…,0)f = (1, 0, \ldots, 0); the expected payoff is xTAyx^{\mathsf T} A y with the sequence payoff matrix AA. The problem is

v=max⁡x∈Xmin⁡y∈YxTAy=min⁡y∈Ymax⁡x∈XxTAy.v = \max_{x \in X} \min_{y \in Y} x^{\mathsf T} A y = \min_{y \in Y} \max_{x \in X} x^{\mathsf T} A y .

For a fixed xx, the inner problem min⁡{(ATx)Ty:Fy=f, y≥0}\min \{(A^{\mathsf T} x)^{\mathsf T} y : F y = f,\ y \ge 0\} is a linear program, and by LP duality its value is max⁡{fTq:FTq≤ATx}\max \{f^{\mathsf T} q : F^{\mathsf T} q \le A^{\mathsf T} x\} with qq free. Putting the two maximizations together gives one LP.

The algorithm

  1. SEQUENCE-FORM-LP(T) ▷ T: a two-player zero-sum game tree with perfect recall
  2. 1walk T; list the sequences S1, S2 and the parent sequence σ_h of each information set h
  3. ▷ reject T if two nodes of one h have different sequences
  4. 2at each leaf ℓ: A[σ1(ℓ)][σ2(ℓ)] ← A[σ1(ℓ)][σ2(ℓ)] + c(ℓ) · u(ℓ) ▷ c(ℓ): chance probability
  5. 3build E, e for player 1 and F, f for player 2 ▷ one row for ∅ and one per information set
  6. 4constraints: F^T q - A^T x ≤ 0 (one row per sequence of player 2), E x = e, x ≥ 0, q free
  7. 5maximize q_∅ subject to L4 ▷ q_∅: the entry of q for the row of ∅ in F
  8. 6x ← the optimal x; y ← the dual prices of the rows of L4
  9. return (q_∅, x, y)

Line L4 has one inequality for each sequence τ\tau of player 2. On its left, τ=∅\tau = \emptyset gives q∅+∑qh′q_\emptyset + \sum q_{h'}, and a sequence that ends at an information set hh gives −qh+∑qh′-q_h + \sum q_{h'}, where the sums run over the information sets h′h' of player 2 whose parent sequence is τ\tau. On its right is (ATx)τ(A^{\mathsf T} x)_\tau, the payoff that player 1 gets, weighted by chance and by xx, from the leaves that player 2 reaches with τ\tau and no further own move. So −qh-q_h is a lower bound on what player 1 gets below hh, whatever player 2 does there, and the LP pushes these bounds up from the leaves to the root.

The dual of the LP of line L4 is player 2's LP: minimize p∅p_\emptyset subject to ETp−Ay≥0E^{\mathsf T} p - A y \ge 0, Fy=fF y = f, y≥0y \ge 0, pp free. So the dual prices of the inequality rows, which are yy, form an optimal realization plan of player 2. A behavior strategy is read from xx by β(h,a)=x(σha)/x(σh)\beta(h, a) = x(\sigma_h a) / x(\sigma_h) where x(σh)>0x(\sigma_h) > 0.

Example

Player 1 plays LL, which ends the game with payoff 1, or RR. After RR, player 2 picks aa or bb, and then player 1 picks cc or dd without seeing that choice. The payoffs to player 1 are 3 after RacR a c, 0 after RadR a d and RbcR b c, and 2 after RbdR b d. The sequences are S1=(∅,L,R,Rc,Rd)S_1 = (\emptyset, L, R, Rc, Rd) and S2=(∅,a,b)S_2 = (\emptyset, a, b), and the nonzero entries of AA are A(L,∅)=1A(L, \emptyset) = 1, A(Rc,a)=3A(Rc, a) = 3 and A(Rd,b)=2A(Rd, b) = 2.

Player 2 has one information set, p2p_2, so q=(q∅,qp2)q = (q_\emptyset, q_{p_2}), and the three rows of line L4 are

sequence of player 2 row of L4
∅\emptyset q∅+qp2≤x(L)q_\emptyset + q_{p_2} \le x(L)
aa −qp2≤3 x(Rc)-q_{p_2} \le 3\, x(Rc)
bb −qp2≤2 x(Rd)-q_{p_2} \le 2\, x(Rd)

with x(∅)=1x(\emptyset) = 1, x(L)+x(R)=1x(L) + x(R) = 1 and x(Rc)+x(Rd)=x(R)x(Rc) + x(Rd) = x(R). The best choice of qq gives q∅=x(L)+min⁡(3x(Rc),2x(Rd))q_\emptyset = x(L) + \min(3 x(Rc), 2 x(Rd)): player 2 picks the better of aa and bb against player 1's plan. The maximum is at x(L)=0x(L) = 0 and 3x(Rc)=2x(Rd)3 x(Rc) = 2 x(Rd), so

x=(1,0,1,2/5,3/5),v=q∅=6/5.x = (1, 0, 1, 2/5, 3/5), \qquad v = q_\emptyset = 6/5 .

The dual prices of the three rows are y=(1,2/5,3/5)y = (1, 2/5, 3/5): player 2 plays aa with probability 2/52/5. Against it, RR then cc gives 3⋅2/5=6/53 \cdot 2/5 = 6/5, RR then dd gives 2⋅3/5=6/52 \cdot 3/5 = 6/5, and LL gives 1<6/51 < 6/5, so player 1 cannot get more than 6/56/5. The game has 4 pure strategies for player 1, while the LP has 5 variables for player 1.

On Kuhn poker (three cards, one bet), each player has 6 information sets and 13 sequences, and the LP gives the value −1/18-1/18 for the first player.

Correctness

By LP duality, for each fixed x∈Xx \in X the maximum of q∅q_\emptyset over the qq with FTq≤ATxF^{\mathsf T} q \le A^{\mathsf T} x is min⁡y∈YxTAy\min_{y \in Y} x^{\mathsf T} A y, because YY is a nonempty polytope and the inner LP has an optimum. So the LP of lines L4 and L5 computes max⁡x∈Xmin⁡y∈YxTAy\max_{x \in X} \min_{y \in Y} x^{\mathsf T} A y, and its optimal xx is a maximin realization plan. Its dual is the same construction for player 2, and strong duality makes the two values equal. Under perfect recall every point of XX and of YY is the realization plan of a behavior strategy, and the payoff of a pair of strategies depends only on their realization plans, so the LP optimum is the value of the game and xx and yy give optimal strategies. The proof file has the details.

Proof: The sequence-form LP gives the value of a zero-sum game with perfect recall and optimal strategies for both playersfull

Let TT be a finite two-player zero-sum game tree with chance moves and perfect recall, with payoffs u(ℓ)u(\ell) to player 1. Let S1,S2S_1, S_2, E,eE, e, F,fF, f and AA be as built in lines L1 to L3, so that X={x:Ex=e,x≥0}X = \{x : E x = e, x \ge 0\} and Y={y:Fy=f,y≥0}Y = \{y : F y = f, y \ge 0\}. Write (P) for the LP of lines L4 and L5: maximize q∅=fTqq_\emptyset = f^{\mathsf T} q subject to FTq−ATx≤0F^{\mathsf T} q - A^{\mathsf T} x \le 0, Ex=eE x = e, x≥0x \ge 0, qq free.

Lemma 1 (realization plans). For every behavior strategy β\beta of player 1, the vector xβ(σ)=∏(h,a)∈σβ(h,a)x_\beta(\sigma) = \prod_{(h, a) \in \sigma} \beta(h, a) is in XX. Conversely, for every x∈Xx \in X there is a behavior strategy β\beta with xβ=xx_\beta = x.

Proof. xβ(∅)=1x_\beta(\emptyset) = 1 is the empty product. For h∈H1h \in H_1, ∑axβ(σha)=xβ(σh)∑aβ(h,a)=xβ(σh)\sum_a x_\beta(\sigma_h a) = x_\beta(\sigma_h) \sum_a \beta(h, a) = x_\beta(\sigma_h), and all entries are nonnegative. Conversely, given x∈Xx \in X, let β(h,a)=x(σha)/x(σh)\beta(h, a) = x(\sigma_h a) / x(\sigma_h) if x(σh)>0x(\sigma_h) > 0, and the uniform distribution otherwise. By the constraint of row hh, this is a distribution on A(h)A(h). We show xβ(σ)=x(σ)x_\beta(\sigma) = x(\sigma) by induction on the length of σ\sigma. It holds for ∅\emptyset. Let σ=σha\sigma = \sigma_h a, with xβ(σh)=x(σh)x_\beta(\sigma_h) = x(\sigma_h) by induction; here perfect recall is used, because σh\sigma_h is one sequence and the last pair of σ\sigma is (h,a)(h, a). If x(σh)>0x(\sigma_h) > 0, then xβ(σ)=x(σh)β(h,a)=x(σ)x_\beta(\sigma) = x(\sigma_h) \beta(h, a) = x(\sigma). If x(σh)=0x(\sigma_h) = 0, then x(σ)=0x(\sigma) = 0 because 0≤x(σha)≤∑a′x(σha′)=00 \le x(\sigma_h a) \le \sum_{a'} x(\sigma_h a') = 0, and xβ(σ)=0⋅β(h,a)=0x_\beta(\sigma) = 0 \cdot \beta(h, a) = 0. □\square

The same holds for player 2 and YY.

Lemma 2 (payoff). If player 1 plays a behavior strategy β1\beta_1 and player 2 plays β2\beta_2, the expected payoff to player 1 is xβ1TA yβ2x_{\beta_1}^{\mathsf T} A\, y_{\beta_2}.

Proof. The probability of reaching a leaf ℓ\ell is the product of the probabilities of the moves on its path. The chance moves give c(ℓ)c(\ell), the moves of player 1 give ∏(h,a)∈σ1(ℓ)β1(h,a)=xβ1(σ1(ℓ))\prod_{(h, a) \in \sigma_1(\ell)} \beta_1(h, a) = x_{\beta_1}(\sigma_1(\ell)), and those of player 2 give yβ2(σ2(ℓ))y_{\beta_2}(\sigma_2(\ell)). Here σi(ℓ)\sigma_i(\ell) is the sequence of player ii on the path, and the moves of player ii on the path are exactly the pairs of σi(ℓ)\sigma_i(\ell). So the expected payoff is ∑ℓc(ℓ) u(ℓ) x(σ1(ℓ)) y(σ2(ℓ))\sum_\ell c(\ell)\, u(\ell)\, x(\sigma_1(\ell))\, y(\sigma_2(\ell)), and grouping the leaves by the pair (σ1(ℓ),σ2(ℓ))(\sigma_1(\ell), \sigma_2(\ell)) gives ∑σ1,σ2x(σ1)A(σ1,σ2)y(σ2)\sum_{\sigma_1, \sigma_2} x(\sigma_1) A(\sigma_1, \sigma_2) y(\sigma_2), by the definition of AA in line L2. □\square

By Lemmas 1 and 2, every pair (x,y)∈X×Y(x, y) \in X \times Y is the pair of realization plans of a pair of behavior strategies with expected payoff xTAyx^{\mathsf T} A y. By Kuhn's theorem, in a game with perfect recall every mixed strategy has a behavior strategy with the same payoff against every strategy of the other player, so it suffices to consider behavior strategies. Hence x∈Xx \in X guarantees player 1 at least min⁡y∈YxTAy\min_{y \in Y} x^{\mathsf T} A y against every strategy of player 2, and the same for player 2.

Lemma 3 (inner problem). For each x∈Xx \in X, the largest q∅q_\emptyset over the qq with FTq≤ATxF^{\mathsf T} q \le A^{\mathsf T} x is min⁡y∈YxTAy\min_{y \in Y} x^{\mathsf T} A y.

Proof. The LP min⁡{(ATx)Ty:Fy=f,y≥0}\min \{(A^{\mathsf T} x)^{\mathsf T} y : F y = f, y \ge 0\} is feasible, because YY contains the plan of any pure strategy, and bounded, because YY is bounded: every entry of yy is at most 1, by induction along the sequences, since y(σha)≤y(σh)y(\sigma_h a) \le y(\sigma_h). So it has an optimum. Its dual is max⁡{fTq:FTq≤ATx}\max \{f^{\mathsf T} q : F^{\mathsf T} q \le A^{\mathsf T} x\} with qq free, and by strong duality the two optimal values are equal. □\square

Theorem. (P) has an optimal solution (q∗,x∗)(q^*, x^*). Its value v=q∅∗v = q^*_\emptyset is the value of the game, x∗x^* is an optimal realization plan of player 1, and the vector y∗y^* of dual prices of the inequality rows of (P) is an optimal realization plan of player 2.

Proof. By Lemma 3, (P) is max⁡x∈Xmin⁡y∈YxTAy\max_{x \in X} \min_{y \in Y} x^{\mathsf T} A y, the maximum of a continuous function on a nonempty compact set, so it has an optimum, and x∗x^* attains the maximin. The dual of (P) has a nonnegative variable yτy_\tau for each inequality row and a free variable pkp_k for each row of EE. The columns of qq, which are free, give the equations Fy=fF y = f. The columns of xx, which are nonnegative, give ETp−Ay≥0E^{\mathsf T} p - A y \ge 0. The objective is eTp=p∅e^{\mathsf T} p = p_\emptyset. So the dual is: minimize p∅p_\emptyset subject to ETp≥AyE^{\mathsf T} p \ge A y, y∈Yy \in Y, pp free. For a fixed yy, this is the dual of max⁡{(Ay)Tx:x∈X}\max \{(A y)^{\mathsf T} x : x \in X\}, so by the argument of Lemma 3 with the players exchanged, the dual of (P) computes min⁡y∈Ymax⁡x∈XxTAy\min_{y \in Y} \max_{x \in X} x^{\mathsf T} A y, and its optimal y∗y^* attains this minimax. By strong duality for (P), both values equal vv. So min⁡yx∗TAy=v=max⁡xxTAy∗\min_y x^{*\mathsf T} A y = v = \max_x x^{\mathsf T} A y^*: x∗x^* guarantees vv and y∗y^* holds player 1 to vv, which is the definition of the value and of optimal strategies. The dual prices returned by the solver satisfy the dual constraints and have value vv (the shared LP code returns duals with ∑ibi⋅duali\sum_i b_i \cdot \text{dual}_i equal to the value and ATdual≥cA^{\mathsf T} \text{dual} \ge c), so they are an optimal solution of the dual. □\square

Perfect recall check. Line L1 rejects a tree in which two nodes of one information set have different own sequences. Lemma 1 uses exactly this property, so the theorem holds for every tree that the code accepts.

Complexity

The LP has ∣S1∣+2(∣H2∣+1)|S_1| + 2 (|H_2| + 1) variables, counting qq split into two nonnegative parts, and ∣S2∣+∣H1∣+1|S_2| + |H_1| + 1 constraints, where ∣Si∣≤N|S_i| \le N and ∣Hi∣≤N|H_i| \le N for a tree with NN nodes. The matrix AA has at most one nonzero entry per leaf. Building it takes O(N)O(N) time plus the dense storage, O(N2)O(N^2) in the code. With a polynomial-time LP method (ellipsoid or interior point), the total time is polynomial in NN and the bit length LL of the numbers. The code uses the simplex method with exact rational arithmetic, which is fast on small games but has no polynomial bound.

The normal form of the same tree can have a number of pure strategies exponential in NN, so the LP for matrix games on it can be exponentially larger.

Properties

  • Exact. With rational payoffs and chance probabilities, the value and the plans are rational, and the code computes them exactly.
  • Both players at once. The primal gives player 1's plan and the dual gives player 2's.
  • Linear size. The LP has size linear in the tree, and the payoff matrix is sparse.
  • Needs perfect recall. Without it, sequences do not identify information sets, and finding optimal strategies of zero-sum games with imperfect recall is NP-hard in general (Koller and Megiddo).

Variants and improvements

  • General-sum games. For two-player games that are not zero-sum, the equilibrium conditions in sequence form are a linear complementarity problem of linear size, solved by a variant of Lemke's algorithm (Koller, Megiddo and von Stengel).
  • Large games. Games with millions of information sets are beyond exact LP. Counterfactual regret minimization and first-order methods on the polytopes of realization plans approximate the equilibrium of the same min-max problem.
  • Refinements. An optimal plan can be arbitrary at information sets that it reaches with probability 0. Refined solutions that also play well there need perturbed versions of the LP.

When to use it

Use it to solve a two-player zero-sum game tree with imperfect information exactly, when the tree fits in memory and an LP solver can handle a few times its size: small poker variants, endgames of bigger games, and search games. Use the LP for matrix games when the game is given in normal form. For trees too large for an LP, use an iterative method and accept an approximate equilibrium.

Pitfalls

  • Perfect recall. The code checks that all nodes of an information set have the same own sequence and rejects the tree otherwise. Without this check the LP is wrong without warning.
  • Unreached information sets. Where x(σh)=0x(\sigma_h) = 0, the behavior strategy is not determined by xx; any choice there keeps the plan optimal, but it can be a poor move if the opponent errs.
  • Dual signs. Player 2's plan is the vector of dual prices of the inequality rows, which must be nonnegative and satisfy Fy=fF y = f; a solver with a different sign convention returns −y-y.
  • Free variables. The vector qq has no sign condition, and its entries for player 2's information sets are usually negative when player 1 wins. Forcing q≥0q \ge 0 gives a wrong value.
  • Floating point. With a floating-point LP solver, check xx and yy by best responses in the tree and allow a tolerance.

Implementations

The Python code walks the tree once to build the sequences, the constraint matrices and the sequence payoff matrix (lines L1 to L3), then calls the shared exact simplex code on the LP of lines L4 and L5 and reads yy from its duals. It also converts realization plans to behavior strategies. The tests check the example above, Kuhn poker with value −1/18-1/18, and 40 random game trees with chance moves and hidden moves. For each one, xx must guarantee the value against every pure strategy of player 2, and yy must hold player 1 to it against every pure strategy of player 1, both computed in the tree. The value must also equal that of the normal-form game, solved by a separate LP over all pure strategies. Trees without perfect recall and inconsistent information sets must be rejected.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

agtlp.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact linear programming in Fraction, by the two-phase simplex method with Bland's rule.

lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None) maximizes c x subject to A_ub x <= b_ub,
A_eq x = b_eq and x >= 0. lp_min does the same for minimization. Free variables must be
split by the caller (x = x+ - x-). Every input number is converted to Fraction, so the
result is exact: there is no tolerance anywhere.

Both functions return (status, x, value, dual). status is "optimal", "infeasible" or
"unbounded". When status is not "optimal", x, value and dual are None. dual has one entry
per constraint, the A_ub rows first and then the A_eq rows. It is the vector of shadow
prices: the value is sum_i b_i dual_i (strong duality). For lp_max, dual_i >= 0 on the
A_ub rows and A^T dual >= c. For lp_min, dual_i <= 0 on the A_ub rows and A^T dual <= c.
The entries for the A_eq rows have no sign condition.

Bland's rule (the smallest improving column enters, and among the rows with the smallest
ratio the one with the smallest basic variable leaves) makes the method finite on every
input, degenerate inputs included. There is no game algorithm in this module.
"""

from fractions import Fraction


def _frac(v):
    return v if isinstance(v, Fraction) else Fraction(v)


def _pivot(T, obj, basis, r, j):
    p = T[r][j]
    row = [v / p for v in T[r]]
    T[r] = row
    for k in range(len(T)):
        f = T[k][j]
        if k != r and f != 0:
            T[k] = [a - f * b for a, b in zip(T[k], row)]
    f = obj[j]
    if f != 0:
        obj[:] = [a - f * b for a, b in zip(obj, row)]
    basis[r] = j


def _simplex(T, obj, basis, ncols):
    """Maximize. obj[j] is the reduced cost of column j and obj[-1] is minus the value."""
    while True:
        enter = next((j for j in range(ncols) if obj[j] > 0), None)
        if enter is None:
            return "optimal"
        best = None
        for r, row in enumerate(T):
            a = row[enter]
            if a > 0:
                key = (row[-1] / a, basis[r])
                if best is None or key < best[0]:
                    best = (key, r)
        if best is None:
            return "unbounded"
        _pivot(T, obj, basis, best[1], enter)


def _objective_row(cost, T, basis):
    obj = list(cost) + [Fraction(0)]
    for r, j in enumerate(basis):
        f = obj[j]
        if f != 0:
            obj = [a - f * b for a, b in zip(obj, T[r])]
    return obj


def _any_solution(M, rhs, nvars):
    """Return one solution y of M y = rhs (a consistent system), with the free variables 0."""
    rows = [list(M[k]) + [rhs[k]] for k in range(len(M))]
    pivots = []
    r = 0
    for col in range(nvars):
        p = next((k for k in range(r, len(rows)) if rows[k][col] != 0), None)
        if p is None:
            continue
        rows[r], rows[p] = rows[p], rows[r]
        pv = rows[r][col]
        rows[r] = [v / pv for v in rows[r]]
        for k in range(len(rows)):
            f = rows[k][col]
            if k != r and f != 0:
                rows[k] = [a - f * b for a, b in zip(rows[k], rows[r])]
        pivots.append(col)
        r += 1
        if r == len(rows):
            break
    y = [Fraction(0)] * nvars
    for k, col in enumerate(pivots):
        y[col] = rows[k][-1]
    return y


def _matrix(A, width, name):
    A = [[_frac(v) for v in row] for row in (A or [])]
    if any(len(row) != width for row in A):
        raise ValueError(name + " must have one column per variable")
    return A


def lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None):
    """Maximize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
    c = [_frac(v) for v in c]
    n = len(c)
    A_ub = _matrix(A_ub, n, "A_ub")
    A_eq = _matrix(A_eq, n, "A_eq")
    b_ub = [_frac(v) for v in (b_ub or [])]
    b_eq = [_frac(v) for v in (b_eq or [])]
    if len(b_ub) != len(A_ub) or len(b_eq) != len(A_eq):
        raise ValueError("b_ub and b_eq must have one entry per row")
    m1, m2 = len(A_ub), len(A_eq)
    m = m1 + m2
    width = n + m1
    # Rows in the original orientation, with a slack column for each A_ub row.
    orig = [A_ub[i] + [Fraction(int(k == i)) for k in range(m1)] for i in range(m1)]
    orig += [A_eq[i] + [Fraction(0)] * m1 for i in range(m2)]
    rhs = b_ub + b_eq
    # A row gets an artificial variable if it is an equation or if its right side is negative.
    need = [i >= m1 or rhs[i] < 0 for i in range(m)]
    nart = sum(need)
    T, basis = [], []
    a = 0
    for i in range(m):
        sign = -1 if rhs[i] < 0 else 1
        row = [sign * v for v in orig[i]] + [Fraction(0)] * nart + [sign * rhs[i]]
        if need[i]:
            row[width + a] = Fraction(1)
            basis.append(width + a)
            a += 1
        else:
            basis.append(n + i)
        T.append(row)
    if nart:
        # Phase 1: maximize minus the sum of the artificial variables.
        obj = _objective_row([Fraction(0)] * width + [Fraction(-1)] * nart, T, basis)
        _simplex(T, obj, basis, width + nart)
        if obj[-1] != 0:
            return "infeasible", None, None, None
        keep = []
        for r in range(m):
            if basis[r] >= width:
                j = next((j for j in range(width) if T[r][j] != 0), None)
                if j is None:
                    continue  # the row is a combination of the other rows
                _pivot(T, [Fraction(0)] * (width + nart + 1), basis, r, j)
            keep.append(r)
        T = [T[r][:width] + [T[r][-1]] for r in keep]
        basis = [basis[r] for r in keep]
    # Phase 2: the original objective, without the artificial columns.
    cost = c + [Fraction(0)] * m1
    obj = _objective_row(cost, T, basis)
    if _simplex(T, obj, basis, width) == "unbounded":
        return "unbounded", None, None, None
    x = [Fraction(0)] * n
    for r, j in enumerate(basis):
        if j < n:
            x[j] = T[r][-1]
    value = sum((ci * xi for ci, xi in zip(c, x)), Fraction(0))
    # The dual solves y^T A_B = c_B, where A_B holds the basic columns of the original rows.
    M = [[orig[i][j] for i in range(m)] for j in basis]
    dual = _any_solution(M, [cost[j] for j in basis], m)
    return "optimal", x, value, dual


def lp_min(c, A_ub, b_ub, A_eq=None, b_eq=None):
    """Minimize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
    status, x, value, dual = lp_max([-_frac(v) for v in c], A_ub, b_ub, A_eq, b_eq)
    if status != "optimal":
        return status, None, None, None
    return status, x, -value, [-v for v in dual]
sequence_form_linear_program.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sequence-form-linear-program/. The authors are listed in prov/7V6BC9.jsonl.
"""The sequence-form linear program for two-player zero-sum games in extensive form, in Fraction.

A game tree is made of tuples:
  ("leaf", u)                          u is the payoff to player 1; player 2 gets -u
  ("chance", [(p, child), ...])        the probabilities p sum to 1
  ("move", player, h, [(a, child), ...])  player is 1 or 2, h names the information set
All nodes with the same h must belong to the same player and have the same list of actions.
Perfect recall is checked: all nodes of an information set must have the same sequence of
own (information set, action) pairs above them.

A sequence of a player is () or a tuple of (h, a) pairs. A realization plan x gives each
sequence the probability that the player's own moves follow it; it satisfies x[()] = 1 and
x[s] = sum of x[s + ((h, a),)] over the actions a of each information set h with parent s.
"""

from fractions import Fraction

from agtlp import lp_max


class SequenceForm:
    """The sequences, information sets and sequence payoff matrix of a game tree."""

    def __init__(self, tree):
        self.seqs = [[()], [()]]          # seqs[p][k]: sequence number k of player p + 1
        self.index = [{(): 0}, {(): 0}]
        self.infosets = [{}, {}]          # h -> (parent sequence, list of actions)
        self.payoff = {}                  # (k1, k2) -> expected payoff to player 1
        self._walk(tree, Fraction(1), [(), ()])  # @line L1
        self.E = self._constraints(0)
        self.F = self._constraints(1)  # @line L3

    def _walk(self, node, prob, seq):
        kind = node[0]
        if kind == "leaf":
            key = (self.index[0][seq[0]], self.index[1][seq[1]])
            self.payoff[key] = self.payoff.get(key, Fraction(0)) + prob * Fraction(node[1])  # @line L2
        elif kind == "chance":
            for p, child in node[1]:
                self._walk(child, prob * Fraction(p), seq)
        elif kind == "move":
            _, player, h, moves = node
            p = player - 1
            if h in self.infosets[1 - p]:
                raise ValueError("information set %r belongs to both players" % (h,))
            actions = [a for a, _ in moves]
            known = self.infosets[p].setdefault(h, (seq[p], actions))
            if known[0] != seq[p]:
                raise ValueError("no perfect recall at information set %r" % (h,))
            if known[1] != actions:
                raise ValueError("information set %r has different actions" % (h,))
            for a, child in moves:
                s = seq[p] + ((h, a),)
                if s not in self.index[p]:
                    self.index[p][s] = len(self.seqs[p])
                    self.seqs[p].append(s)
                nxt = list(seq)
                nxt[p] = s
                self._walk(child, prob, nxt)
        else:
            raise ValueError("unknown node kind %r" % (kind,))

    def _constraints(self, p):
        """Rows of E x = e: x[()] = 1, then x[parent(h)] - sum_a x[parent(h) + (h, a)] = 0."""
        n = len(self.seqs[p])
        rows = [[Fraction(int(k == 0)) for k in range(n)]]
        for h, (parent, actions) in self.infosets[p].items():
            row = [Fraction(0)] * n
            row[self.index[p][parent]] = Fraction(1)
            for a in actions:
                row[self.index[p][parent + ((h, a),)]] = Fraction(-1)
            rows.append(row)
        return rows

    def matrix(self):
        """The sequence payoff matrix A, with A[k1][k2] the payoff to player 1."""
        A = [[Fraction(0)] * len(self.seqs[1]) for _ in self.seqs[0]]
        for (i, j), v in self.payoff.items():
            A[i][j] = v
        return A


def solve(tree):
    """Return (value, x, y): the value for player 1 and optimal realization plans as dicts.

    The LP has variables q (free, one per row of F) and x >= 0:
        maximize q[0]  subject to  F^T q - A^T x <= 0,  E x = e.
    The constraint of player 2's sequence j says that j costs player 1 at least the
    payoff that the subtree of j can guarantee; the duals of these rows are an optimal y.
    """
    sf = SequenceForm(tree)
    A = sf.matrix()
    E, F = sf.E, sf.F
    n1, n2, r2 = len(sf.seqs[0]), len(sf.seqs[1]), len(F)
    # Columns: q+ (r2), q- (r2), x (n1).
    c = [Fraction(int(k == 0)) for k in range(r2)] + [-Fraction(int(k == 0)) for k in range(r2)] + [Fraction(0)] * n1
    A_ub = [[F[k][j] for k in range(r2)] + [-F[k][j] for k in range(r2)] + [-A[i][j] for i in range(n1)]
            for j in range(n2)]  # @line L4
    A_eq = [[Fraction(0)] * (2 * r2) + E[k] for k in range(len(E))]
    status, sol, value, dual = lp_max(c, A_ub, [0] * n2, A_eq, [1] + [0] * (len(E) - 1))  # @line L5
    if status != "optimal":
        raise AssertionError("the sequence-form LP of a finite game always has an optimum")
    x = {s: sol[2 * r2 + k] for k, s in enumerate(sf.seqs[0])}
    y = {s: dual[j] for j, s in enumerate(sf.seqs[1])}  # @line L6
    return value, x, y


def behavior(sf, p, plan):
    """Turn a realization plan of player p + 1 into a behavior strategy: h -> {a: probability}.

    At an information set that the plan reaches with probability 0 the actions are uniform.
    """
    out = {}
    for h, (parent, actions) in sf.infosets[p].items():
        total = plan[parent]
        if total == 0:
            out[h] = {a: Fraction(1, len(actions)) for a in actions}
        else:
            out[h] = {a: plan[parent + ((h, a),)] / total for a in actions}
    return out
test_sequence_form_linear_program.py 212 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sequence-form-linear-program/. The authors are listed in prov/7V6BC9.jsonl.

import random
from fractions import Fraction
from itertools import permutations, product

from agtlp import lp_max
from sequence_form_linear_program import SequenceForm, behavior, solve

F = Fraction

# Player 1 plays L (payoff 1) or R; after R, player 2 picks a or b, and then player 1
# picks c or d without seeing that choice. Payoffs are to player 1.
PAGE_GAME = ("move", 1, "root", [
    ("L", ("leaf", 1)),
    ("R", ("move", 2, "p2", [
        ("a", ("move", 1, "late", [("c", ("leaf", 3)), ("d", ("leaf", 0))])),
        ("b", ("move", 1, "late", [("c", ("leaf", 0)), ("d", ("leaf", 2))])),
    ])),
])


def kuhn_poker():
    names = "JQK"
    deals = []
    for c1, c2 in permutations(range(3), 2):
        def show(stake, c1=c1, c2=c2):
            return ("leaf", stake if c1 > c2 else -stake)
        h1, h2 = names[c1], names[c2]
        root = ("move", 1, "1" + h1, [
            ("check", ("move", 2, "2" + h2 + "k", [
                ("check", show(1)),
                ("bet", ("move", 1, "1" + h1 + "kb", [("fold", ("leaf", -1)), ("call", show(2))])),
            ])),
            ("bet", ("move", 2, "2" + h2 + "b", [("fold", ("leaf", 1)), ("call", show(2))])),
        ])
        deals.append((F(1, 6), root))
    return ("chance", deals)


def expected(node, strat):
    """Expected payoff to player 1 when player p + 1 plays the behavior strategy strat[p]."""
    kind = node[0]
    if kind == "leaf":
        return F(node[1])
    if kind == "chance":
        return sum(F(p) * expected(child, strat) for p, child in node[1])
    _, player, h, moves = node
    probs = strat[player - 1][h]
    return sum(probs[a] * expected(child, strat) for a, child in moves if probs[a] != 0)


def pure_strategies(sf, p):
    hs = list(sf.infosets[p])
    for choice in product(*[sf.infosets[p][h][1] for h in hs]):
        yield {h: {a: F(int(a == c)) for a in sf.infosets[p][h][1]} for h, c in zip(hs, choice)}


def normal_form_value(tree, sf):
    """The value of the normal form of the tree, by an LP over the pure strategies."""
    rows = list(pure_strategies(sf, 0))
    cols = list(pure_strategies(sf, 1))
    M = [[expected(tree, (r, c)) for c in cols] for r in rows]
    m = len(rows)
    # maximize v+ - v- subject to v+ - v- - sum_i x_i M[i][j] <= 0, sum x = 1.
    c = [1, -1] + [0] * m
    A_ub = [[1, -1] + [-M[i][j] for i in range(m)] for j in range(len(cols))]
    status, _, value, _ = lp_max(c, A_ub, [0] * len(cols), [[0, 0] + [1] * m], [1])
    assert status == "optimal"
    return value


def check_plans(sf, x, y):
    for p, plan in ((0, x), (1, y)):
        rows = sf.E if p == 0 else sf.F
        vec = [plan[s] for s in sf.seqs[p]]
        assert all(v >= 0 for v in vec)
        assert [sum(a * b for a, b in zip(row, vec)) for row in rows] == [1] + [0] * (len(rows) - 1)


def check_optimal(tree, value, x, y):
    sf = SequenceForm(tree)
    check_plans(sf, x, y)
    bx, by = behavior(sf, 0, x), behavior(sf, 1, y)
    # x guarantees the value against every pure strategy of player 2, and y holds player 1 to it.
    assert min(expected(tree, (bx, s)) for s in pure_strategies(sf, 1)) == value
    assert max(expected(tree, (s, by)) for s in pure_strategies(sf, 0)) == value
    # The sequence form computes the same payoff as the tree.
    A = sf.matrix()
    xs = [x[s] for s in sf.seqs[0]]
    ys = [y[s] for s in sf.seqs[1]]
    assert sum(xs[i] * A[i][j] * ys[j] for i in range(len(xs)) for j in range(len(ys))) == value == expected(tree, (bx, by))
    return sf


def test_page_example():
    sf = SequenceForm(PAGE_GAME)
    assert sf.seqs[0] == [(), (("root", "L"),), (("root", "R"),),
                          (("root", "R"), ("late", "c")), (("root", "R"), ("late", "d"))]
    assert sf.seqs[1] == [(), (("p2", "a"),), (("p2", "b"),)]
    assert sf.E == [[1, 0, 0, 0, 0], [1, -1, -1, 0, 0], [0, 0, 1, -1, -1]]
    assert sf.matrix() == [[0, 0, 0], [1, 0, 0], [0, 0, 0], [0, 3, 0], [0, 0, 2]]
    value, x, y = solve(PAGE_GAME)
    assert value == F(6, 5)
    assert [x[s] for s in sf.seqs[0]] == [1, 0, 1, F(2, 5), F(3, 5)]
    assert [y[s] for s in sf.seqs[1]] == [1, F(2, 5), F(3, 5)]
    check_optimal(PAGE_GAME, value, x, y)


def test_kuhn_poker():
    tree = kuhn_poker()
    value, x, y = solve(tree)
    assert value == F(-1, 18)
    sf = check_optimal(tree, value, x, y)
    assert len(sf.seqs[0]) == 13 and len(sf.seqs[1]) == 13  # 1 + 6 information sets * 2 actions
    # In every equilibrium player 1 never bets with Q at the root, and always calls a bet with K.
    b1 = behavior(sf, 0, x)
    assert b1["1Q"]["bet"] == 0 and b1["1Kkb"]["call"] == 1


def random_game(rng, max_pure):
    while True:
        sizes = {}

        def build(depth, hist, own):
            if depth == 0 or (hist and rng.random() < 0.2):
                return ("leaf", rng.randint(-6, 6))
            if rng.random() < 0.15:
                p = F(rng.randint(1, 3), 4)
                return ("chance", [(p, build(depth - 1, hist + ("c0",), own)),
                                   (1 - p, build(depth - 1, hist + ("c1",), own))])
            # Mostly alternate, so that a player often moves after moves that are hidden.
            last = next((e[0] for e in reversed(hist) if isinstance(e, tuple)), rng.randint(1, 2))
            player = 3 - last if rng.random() < 0.8 else last
            # The player sees the whole history or only their own moves; both keep perfect recall.
            h = (player, own[player - 1], hist if rng.random() < 0.3 else None)
            k = sizes.setdefault(h, rng.randint(2, 3))
            moves = []
            for t in range(k):
                nxt = list(own)
                nxt[player - 1] = own[player - 1] + ((h, t),)
                moves.append((t, build(depth - 1, hist + ((player, t),), tuple(nxt))))
            return ("move", player, h, moves)

        tree = build(rng.randint(2, 4), (), ((), ()))
        sf = SequenceForm(tree)
        counts = [1, 1]
        for p in range(2):
            for _, actions in sf.infosets[p].values():
                counts[p] *= len(actions)
        if max(counts) <= max_pure:
            return tree


def test_random_games_against_normal_form():
    rng = random.Random(2718)
    hidden = 0
    for _ in range(40):
        tree = random_game(rng, 24)
        value, x, y = solve(tree)
        sf = check_optimal(tree, value, x, y)
        assert value == normal_form_value(tree, sf)
        # Some information set has more than one node exactly when there are fewer
        # nonempty sequences than edges out of decision nodes.
        hidden += len(sf.seqs[0]) + len(sf.seqs[1]) - 2 < count_move_edges(tree)
    assert hidden >= 10


def count_move_edges(node):
    if node[0] == "leaf":
        return 0
    children = [c for _, c in node[-1]]
    return (node[0] == "move") * len(children) + sum(count_move_edges(c) for c in children)


def test_sequence_counts_are_linear():
    # k parallel information sets after a chance move: 2^k pure strategies, 1 + 2k sequences.
    k = 6
    tree = ("chance", [(F(1, k), ("move", 1, i, [(0, ("move", 2, "q", [(0, ("leaf", i)), (1, ("leaf", -i))])),
                                                 (1, ("move", 2, "q", [(0, ("leaf", -1)), (1, ("leaf", 1))]))]))
                       for i in range(k)])
    sf = SequenceForm(tree)
    assert len(sf.seqs[0]) == 1 + 2 * k and len(sf.seqs[1]) == 3
    value, x, y = solve(tree)
    check_optimal(tree, value, x, y)


def test_rejects_imperfect_recall():
    # Player 1 forgets the first own move: the set "h" is reached after (L) and after (R).
    tree = ("move", 1, "first", [
        ("L", ("move", 1, "h", [("a", ("leaf", 1)), ("b", ("leaf", 0))])),
        ("R", ("move", 1, "h", [("a", ("leaf", 0)), ("b", ("leaf", 1))])),
    ])
    try:
        SequenceForm(tree)
    except ValueError:
        return
    raise AssertionError("expected ValueError")


def test_rejects_bad_information_sets():
    for tree in (
        ("move", 1, "h", [("a", ("move", 2, "h", [("x", ("leaf", 0))]))]),
        ("chance", [(F(1, 2), ("move", 1, "h", [("a", ("leaf", 0))])),
                    (F(1, 2), ("move", 1, "h", [("b", ("leaf", 0))]))]),
    ):
        try:
            SequenceForm(tree)
        except ValueError:
            continue
        raise AssertionError("expected ValueError")

History

Romanovskii (1962) reduced zero-sum games with perfect recall to linear programs of small size. Koller, Megiddo and von Stengel (1996), and von Stengel (1996) in a companion paper, introduced the sequence form under that name, gave the LP for zero-sum games and the LCP for general two-player games, and showed that the size is linear in the game tree.

References

  1. Daphne Koller, Nimrod Megiddo and Bernhard von Stengel, Efficient computation of equilibria for extensive two-person games, Games and Economic Behavior 14(2) (1996), 247-259, the LP for zero-sum games in sequence form and the LCP for general two-person games
  2. Efficient computation of behavior strategies, the sequence form, the LP of a zero-sum game with perfect recall, and the behavior strategies read from its solution
  3. Reduction of a game with complete memory to a matrix game, an earlier reduction of zero-sum games with perfect recall to a linear program of small size
  4. Yoav Shoham and Kevin Leyton-Brown, Multiagent Systems, Algorithmic, Game-Theoretic, and Logical Foundations, Cambridge University Press, 2009, Section 5.2.3 (Computing equilibria, the sequence form)
  5. Noam Nisan, Tim Roughgarden, Éva Tardos and Vijay V. Vazirani (eds.), Algorithmic Game Theory, Cambridge University Press, 2007, Chapter 3 (Bernhard von Stengel, Equilibrium computation for two-player games in strategic and extensive form), the sections on the sequence form

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example