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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 to player 1 at the leaves; player 2 gets . Output: the value of the game and realization plans and , so that guarantees player 1 at least against every strategy of player 2 and holds player 1 to at most against every strategy of player 1.
In the sequence form, player 1's plans are and player 2's are , where and ; the expected payoff is with the sequence payoff matrix . The problem is
For a fixed , the inner problem is a linear program, and by LP duality its value is with free. Putting the two maximizations together gives one LP.
The algorithm
SEQUENCE-FORM-LP(T) ▷ T: a two-player zero-sum game tree with perfect recall- 1
walk T; list the sequences S1, S2 and the parent sequence σ_h of each information set h ▷ reject T if two nodes of one h have different sequences- 2
at each leaf ℓ: A[σ1(ℓ)][σ2(ℓ)] ← A[σ1(ℓ)][σ2(ℓ)] + c(ℓ) · u(ℓ) ▷ c(ℓ): chance probability - 3
build E, e for player 1 and F, f for player 2 ▷ one row for ∅ and one per information set - 4
constraints: F^T q - A^T x ≤ 0 (one row per sequence of player 2), E x = e, x ≥ 0, q free - 5
maximize q_∅ subject to L4 ▷ q_∅: the entry of q for the row of ∅ in F - 6
x ← the optimal x; y ← the dual prices of the rows of L4 return (q_∅, x, y)
Line L4 has one inequality for each sequence of player 2. On its left, gives , and a sequence that ends at an information set gives , where the sums run over the information sets of player 2 whose parent sequence is . On its right is , the payoff that player 1 gets, weighted by chance and by , from the leaves that player 2 reaches with and no further own move. So is a lower bound on what player 1 gets below , 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 subject to , , , free. So the dual prices of the inequality rows, which are , form an optimal realization plan of player 2. A behavior strategy is read from by where .
Example
Player 1 plays , which ends the game with payoff 1, or . After , player 2 picks or , and then player 1 picks or without seeing that choice. The payoffs to player 1 are 3 after , 0 after and , and 2 after . The sequences are and , and the nonzero entries of are , and .
Player 2 has one information set, , so , and the three rows of line L4 are
| sequence of player 2 | row of L4 |
|---|---|
with , and . The best choice of gives : player 2 picks the better of and against player 1's plan. The maximum is at and , so
The dual prices of the three rows are : player 2 plays with probability . Against it, then gives , then gives , and gives , so player 1 cannot get more than . 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 for the first player.
Correctness
By LP duality, for each fixed the maximum of over the with is , because is a nonempty polytope and the inner LP has an optimum. So the LP of lines L4 and L5 computes , and its optimal 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 and of 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 and 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 be a finite two-player zero-sum game tree with chance moves and perfect recall, with payoffs to player 1. Let , , and be as built in lines L1 to L3, so that and . Write (P) for the LP of lines L4 and L5: maximize subject to , , , free.
Lemma 1 (realization plans). For every behavior strategy of player 1, the vector is in . Conversely, for every there is a behavior strategy with .
Proof. is the empty product. For , , and all entries are nonnegative. Conversely, given , let if , and the uniform distribution otherwise. By the constraint of row , this is a distribution on . We show by induction on the length of . It holds for . Let , with by induction; here perfect recall is used, because is one sequence and the last pair of is . If , then . If , then because , and .
The same holds for player 2 and .
Lemma 2 (payoff). If player 1 plays a behavior strategy and player 2 plays , the expected payoff to player 1 is .
Proof. The probability of reaching a leaf is the product of the probabilities of the moves on its path. The chance moves give , the moves of player 1 give , and those of player 2 give . Here is the sequence of player on the path, and the moves of player on the path are exactly the pairs of . So the expected payoff is , and grouping the leaves by the pair gives , by the definition of in line L2.
By Lemmas 1 and 2, every pair is the pair of realization plans of a pair of behavior strategies with expected payoff . 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 guarantees player 1 at least against every strategy of player 2, and the same for player 2.
Lemma 3 (inner problem). For each , the largest over the with is .
Proof. The LP is feasible, because contains the plan of any pure strategy, and bounded, because is bounded: every entry of is at most 1, by induction along the sequences, since . So it has an optimum. Its dual is with free, and by strong duality the two optimal values are equal.
Theorem. (P) has an optimal solution . Its value is the value of the game, is an optimal realization plan of player 1, and the vector of dual prices of the inequality rows of (P) is an optimal realization plan of player 2.
Proof. By Lemma 3, (P) is , the maximum of a continuous function on a nonempty compact set, so it has an optimum, and attains the maximin. The dual of (P) has a nonnegative variable for each inequality row and a free variable for each row of . The columns of , which are free, give the equations . The columns of , which are nonnegative, give . The objective is . So the dual is: minimize subject to , , free. For a fixed , this is the dual of , so by the argument of Lemma 3 with the players exchanged, the dual of (P) computes , and its optimal attains this minimax. By strong duality for (P), both values equal . So : guarantees and holds player 1 to , 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 (the shared LP code returns duals with equal to the value and ), so they are an optimal solution of the dual.
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 variables, counting split into two nonnegative parts, and constraints, where and for a tree with nodes. The matrix has at most one nonzero entry per leaf. Building it takes time plus the dense storage, in the code. With a polynomial-time LP method (ellipsoid or interior point), the total time is polynomial in and the bit length 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 , 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 , the behavior strategy is not determined by ; 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 ; a solver with a different sign convention returns .
- Free variables. The vector has no sign condition, and its entries for player 2's information sets are usually negative when player 1 wins. Forcing gives a wrong value.
- Floating point. With a floating-point LP solver, check and 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 from its duals. It also converts realization plans to behavior strategies. The tests check the example above, Kuhn poker with value , and 40 random game trees with chance moves and hidden moves. For each one, must guarantee the value against every pure strategy of player 2, and 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.
# 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
- 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
- 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7V6BC9 Edit this page History Report an error Markdown