Algorithm Search⌘K

Algorithmadvanced

Blum-Mansour swap regret reduction

Also called external to swap regret reduction.

Builds a no-swap-regret algorithm from k copies of a no-external-regret algorithm by playing the stationary distribution of their advice.

Time
O(T k^3) worst
Space
O(k^2) extra
Where
T = the number of rounds; k = the number of actions
Properties
deterministicnot exactonlineiterative
Origin
Avrim Blum, Yishay Mansour, 2007

The Blum-Mansour reduction turns any algorithm with small external regret into one with small swap regret. External regret compares the learner with the best fixed action. Swap regret compares it with every rule δ\delta that replaces each action jj by an action δ(j)\delta(j), applied to all the rounds at once. The reduction runs kk copies of the external regret algorithm, one for each action, and in each round plays the stationary distribution of the Markov chain whose rows are the copies' proposals. With multiplicative weights as the copy, the swap regret after TT rounds is O(Tklog⁡k)O(\sqrt{T k \log k}). In a game, if every player uses it, the empirical distribution of play is an approximate correlated equilibrium, while external regret alone only gives a coarse correlated equilibrium (no-regret convergence to coarse correlated equilibria). Regret matching reaches the same set by a simpler rule with a slower rate; the general scheme is no-regret dynamics. This site has no separate page on swap regret, so it is defined below.

In plain words

A learner chooses among kk actions each day and then sees what each action would have cost. It wants a strong guarantee: for every way of renaming its choices, such as "each time I chose A, I should have chosen B", the renamed history must not be much cheaper. The trick is to hire kk advisers, one for each action. Adviser jj is only responsible for the days on which the learner picks jj, and is charged only for that share of the cost. Each adviser proposes a mix of actions. The learner then picks a mix that agrees with the advice: the chance of each action equals the total chance that the advisers, weighted by the mix itself, send it there. Each adviser only has to beat the best single action, which simple methods can do, and together they beat every renaming.

The problem

There are kk actions and TT rounds. In round tt the learner chooses a distribution ptp_t on the actions, then an adversary, who may know ptp_t, reveals a loss vector ℓt∈[0,1]k\ell_t \in [0, 1]^k, and the learner pays pt⋅ℓtp_t \cdot \ell_t. For a map δ:{1,…,k}→{1,…,k}\delta : \{1, \ldots, k\} \to \{1, \ldots, k\}, the regret against δ\delta is

RT(δ)=∑t=1T∑j=1kpt(j) [ℓt(j)−ℓt(δ(j))].R_T(\delta) = \sum_{t=1}^{T} \sum_{j=1}^{k} p_t(j)\,\big[\ell_t(j) - \ell_t(\delta(j))\big].

The external regret is the maximum over constant maps δ\delta, the internal regret is the maximum over maps that change one action jj into one other action ll, and the swap regret is the maximum over all kkk^k maps. The maximum over all maps splits into one choice for each jj, so

swap regret=∑j=1kmax⁡l∑t=1Tpt(j) [ℓt(j)−ℓt(l)],\text{swap regret} = \sum_{j=1}^{k} \max_{l} \sum_{t=1}^{T} p_t(j)\,\big[\ell_t(j) - \ell_t(l)\big],

and it is at most kk times the internal regret. The goal is an online algorithm with swap regret o(T)o(T) against every adversary.

The algorithm

  1. BLUM-MANSOUR(A, k, T) ▷ A is an algorithm with small external regret
  2. 1create k copies A_1, ..., A_k of A, each on the k actions
  3. 2for t ← 1 to T
  4. 3q_j ← the distribution that A_j proposes, for each j
  5. 4Q ← the k by k matrix whose row j is q_j
  6. 5p ← a distribution with p = p Q
  7. 6play p and observe the loss vector l^t
  8. 7give A_j the loss vector p(j) l^t, for each j

Line L1 creates one copy of the base algorithm for each action jj; copy jj advises the learner what to play instead of jj. Lines L3 and L4 collect the advice into a row-stochastic matrix QQ, the transition matrix of a Markov chain on the actions. Line L5 picks a stationary distribution of that chain; it exists for every stochastic matrix, and it can be computed by Gaussian elimination on the system p(Q−I)=0p(Q - I) = 0, ∑jp(j)=1\sum_j p(j) = 1. When every entry of QQ is positive, as with multiplicative weights, it is unique. Line L7 charges copy jj only for its share p(j)p(j) of the round, so copy jj sees losses in [0,p(j)][0, p(j)].

The stationary condition gives two views of the same round. On one side, p⋅ℓ=∑ip(i)ℓ(i)p \cdot \ell = \sum_i p(i) \ell(i). On the other side, p(i)=∑jp(j)qj(i)p(i) = \sum_j p(j) q_j(i), so p⋅ℓ=∑jqj⋅(p(j) ℓ)p \cdot \ell = \sum_j q_j \cdot (p(j)\,\ell), which is the sum of the losses that the copies are charged. This identity is the whole reduction.

Example

Take k=2k = 2 actions and multiplicative weights with η=1\eta = 1 in each copy: copy jj proposes qj(a)∝e−Lj(a)q_j(a) \propto e^{-L_j(a)}, where Lj(a)L_j(a) is the total scaled loss of action aa given to copy jj. For two actions the stationary distribution of line L5 is p(1)=q2(1)/(q1(2)+q2(1))p(1) = q_2(1) / (q_1(2) + q_2(1)). The losses are (1,0)(1, 0), (1,0)(1, 0) and then (0,1)(0, 1). The numbers are rounded to four places.

round q1q_1 q2q_2 pp (line L5) loss copy 1 gets copy 2 gets
1 (0.5, 0.5) (0.5, 0.5) (0.5, 0.5) (1, 0) (0.5, 0) (0.5, 0)
2 (0.3775, 0.6225) (0.3775, 0.6225) (0.3775, 0.6225) (1, 0) (0.3775, 0) (0.6225, 0)
3 (0.2937, 0.7063) (0.2456, 0.7544) (0.258, 0.742) (0, 1) (0, 0.258) (0, 0.742)
4 (0.3499, 0.6501) (0.406, 0.594) (0.3844, 0.6156)

In the first two rounds both copies see the same losses up to a factor, but copy 2 is charged more in round 2 because p(2)>p(1)p(2) > p(1), so after round 2 the copies differ. In round 3, p(1)=0.2456/(0.7063+0.2456)=0.258p(1) = 0.2456 / (0.7063 + 0.2456) = 0.258, and one checks pQ=pp Q = p: 0.258⋅0.2937+0.742⋅0.2456=0.2580.258 \cdot 0.2937 + 0.742 \cdot 0.2456 = 0.258.

Correctness

Theorem. Let RjR^j be the external regret of copy jj on the losses pt(j)ℓtp_t(j)\ell_t that it receives. Then for every map δ\delta, RT(δ)≤∑jRjR_T(\delta) \le \sum_j R^j. If each copy is multiplicative weights with rate η\eta, the swap regret is at most kln⁡k/η+ηT/2k \ln k / \eta + \eta T / 2, which is 2Tkln⁡k\sqrt{2 T k \ln k} for η=2kln⁡k/T\eta = \sqrt{2 k \ln k / T}.

Proof sketch. By the identity above, the learner's total loss is ∑j∑tqt,j⋅(pt(j)ℓt)\sum_j \sum_t q_{t,j} \cdot (p_t(j)\ell_t), the sum of the copies' losses. The total loss under δ\delta is ∑j∑tpt(j)ℓt(δ(j))\sum_j \sum_t p_t(j)\ell_t(\delta(j)), and for each jj this is the loss of the fixed action δ(j)\delta(j) on the losses of copy jj. Subtract: the difference for each jj is at most the external regret of copy jj. For multiplicative weights on losses in [0,ct][0, c_t], the regret is at most ln⁡k/η+(η/2)∑tct2\ln k / \eta + (\eta / 2) \sum_t c_t^2; with ct=pt(j)c_t = p_t(j) and ∑jpt(j)2≤1\sum_j p_t(j)^2 \le 1 the sum over the copies gives the bound. The full proof is in the proof file.

In a game, let every player ii run the reduction on the losses ℓt(a)=(max⁡ui−ui(a,σt,−i))/Δi\ell_t(a) = (\max u_i - u_i(a, \sigma_{t,-i})) / \Delta_i, where σt\sigma_t is the profile of the distributions in round tt and Δi\Delta_i is the range of uiu_i. Let z=1T∑tσt,1×⋯×σt,nz = \frac{1}{T}\sum_t \sigma_{t,1} \times \cdots \times \sigma_{t,n}. Then, for each player, the largest gain from a swap under zz is exactly Δi\Delta_i times the swap regret divided by TT, so zz is a correlated ε\varepsilon-equilibrium as soon as every player has swap regret at most εT/Δi\varepsilon T / \Delta_i. With multiplicative weights this takes T=O(klog⁡k/ε2)T = O(k \log k / \varepsilon^2) rounds for payoffs in [0,1][0, 1].

Proof: The swap regret of the Blum-Mansour reduction is at most the sum of the external regrets of its copies, and at most k ln k / eta + eta T / 2 with Hedge copiesfull

There are kk actions and TT rounds, and the loss vectors are ℓ1,…,ℓT∈[0,1]k\ell_1, \ldots, \ell_T \in [0, 1]^k, chosen by an adversary who may see the current distribution. In round tt, copy jj proposes qt,jq_{t,j} (line L3), the learner plays ptp_t with pt=ptQtp_t = p_t Q_t (line L5), where row jj of QtQ_t is qt,jq_{t,j}, and copy jj receives the loss vector mt,j=pt(j) ℓtm_{t,j} = p_t(j)\,\ell_t (line L7). Let Rj=∑tqt,j⋅mt,j−min⁡a∑tmt,j(a)R^j = \sum_t q_{t,j} \cdot m_{t,j} - \min_a \sum_t m_{t,j}(a) be the external regret of copy jj.

Claim 1 (line L5 is well defined). Every row-stochastic matrix QQ has a distribution pp with p=pQp = pQ. If all entries of QQ are positive, pp is unique.

Proof. The map p↦pQp \mapsto pQ sends the simplex of distributions to itself and is continuous, so it has a fixed point by Brouwer's theorem; a direct proof is that Q−IQ - I has zero row sums, so Q⊤−IQ^\top - I is singular, and the Perron-Frobenius theorem gives a nonnegative null vector. If all entries are positive, the chain with transition matrix QQ is irreducible, and an irreducible finite chain has exactly one stationary distribution. □\square

Claim 2 (the split). In every round, pt⋅ℓt=∑jqt,j⋅mt,jp_t \cdot \ell_t = \sum_{j} q_{t,j} \cdot m_{t,j}.

Proof. By line L5, pt(a)=∑jpt(j) qt,j(a)p_t(a) = \sum_j p_t(j)\, q_{t,j}(a) for every action aa. So pt⋅ℓt=∑a∑jpt(j) qt,j(a) ℓt(a)=∑j∑aqt,j(a) mt,j(a)p_t \cdot \ell_t = \sum_a \sum_j p_t(j)\, q_{t,j}(a)\, \ell_t(a) = \sum_j \sum_a q_{t,j}(a)\, m_{t,j}(a). □\square

Claim 3 (the reduction). For every map δ\delta from actions to actions, RT(δ)=∑t∑jpt(j) [ℓt(j)−ℓt(δ(j))]≤∑jRjR_T(\delta) = \sum_t \sum_j p_t(j)\,[\ell_t(j) - \ell_t(\delta(j))] \le \sum_j R^j. So the swap regret is at most ∑jRj\sum_j R^j.

Proof. By Claim 2, ∑tpt⋅ℓt=∑j∑tqt,j⋅mt,j\sum_t p_t \cdot \ell_t = \sum_j \sum_t q_{t,j} \cdot m_{t,j}. Also ∑t∑jpt(j) ℓt(δ(j))=∑j∑tmt,j(δ(j))\sum_t \sum_j p_t(j)\,\ell_t(\delta(j)) = \sum_j \sum_t m_{t,j}(\delta(j)), and for each jj this inner sum is the total loss of the fixed action δ(j)\delta(j) on the losses of copy jj, so it is at least min⁡a∑tmt,j(a)\min_a \sum_t m_{t,j}(a). Subtract the two lines: RT(δ)≤∑j(∑tqt,j⋅mt,j−min⁡a∑tmt,j(a))=∑jRjR_T(\delta) \le \sum_j \big(\sum_t q_{t,j} \cdot m_{t,j} - \min_a \sum_t m_{t,j}(a)\big) = \sum_j R^j. □\square

Claim 4 (Hedge on bounded losses). Let Hedge with rate η>0\eta > 0 play qt(a)∝e−ηLt−1(a)q_t(a) \propto e^{-\eta L_{t-1}(a)}, where Lt−1(a)=∑τ<tmτ(a)L_{t-1}(a) = \sum_{\tau < t} m_\tau(a), on losses mt∈[0,ct]km_t \in [0, c_t]^k. Then its external regret is at most ln⁡k/η+(η/2)∑tct2\ln k / \eta + (\eta / 2)\sum_t c_t^2.

Proof. Let Wt=∑ae−ηLt(a)W_t = \sum_a e^{-\eta L_t(a)}, so W0=kW_0 = k. For x≥0x \ge 0, e−x≤1−x+x2/2e^{-x} \le 1 - x + x^2/2. So

WtWt−1=∑aqt(a) e−ηmt(a)≤1−η qt⋅mt+η22∑aqt(a) mt(a)2≤exp⁡(−η qt⋅mt+η2ct22),\frac{W_t}{W_{t-1}} = \sum_a q_t(a)\, e^{-\eta m_t(a)} \le 1 - \eta\, q_t \cdot m_t + \frac{\eta^2}{2} \sum_a q_t(a)\, m_t(a)^2 \le \exp\Big(-\eta\, q_t \cdot m_t + \frac{\eta^2 c_t^2}{2}\Big),

using 1+y≤ey1 + y \le e^y. Multiply over t=1,…,Tt = 1, \ldots, T: WT≤kexp⁡(−η∑tqt⋅mt+(η2/2)∑tct2)W_T \le k \exp(-\eta \sum_t q_t \cdot m_t + (\eta^2/2)\sum_t c_t^2). Also WT≥e−ηLT(a)W_T \ge e^{-\eta L_T(a)} for every aa. Take logarithms and divide by η\eta: ∑tqt⋅mt−LT(a)≤ln⁡k/η+(η/2)∑tct2\sum_t q_t \cdot m_t - L_T(a) \le \ln k/\eta + (\eta/2)\sum_t c_t^2 for every aa. □\square

Claim 5 (the bound with Hedge copies). If every copy is Hedge with rate η\eta, then after every round TT the swap regret is at most kln⁡k/η+ηT/2k \ln k / \eta + \eta T / 2. For η=2kln⁡k/T\eta = \sqrt{2 k \ln k / T} this is 2Tkln⁡k\sqrt{2 T k \ln k}.

Proof. Copy jj gets losses in [0,pt(j)][0, p_t(j)], so by Claim 4, Rj≤ln⁡k/η+(η/2)∑tpt(j)2R^j \le \ln k / \eta + (\eta/2)\sum_t p_t(j)^2. Sum over jj and use ∑jpt(j)2≤∑jpt(j)=1\sum_j p_t(j)^2 \le \sum_j p_t(j) = 1: ∑jRj≤kln⁡k/η+ηT/2\sum_j R^j \le k \ln k / \eta + \eta T / 2. Claim 3 finishes the bound. With the given η\eta, both terms equal Tkln⁡k/2\sqrt{T k \ln k / 2}. □\square

Claim 6 (correlated equilibria in self-play). Let a finite game be played for TT rounds, let σt\sigma_t be the profile of the distributions in round tt, and let player ii, with utility range Δi>0\Delta_i > 0 and maximum utility MiM_i, receive the losses ℓt(a)=(Mi−ui(a,σt,−i))/Δi\ell_{t}(a) = (M_i - u_i(a, \sigma_{t,-i}))/\Delta_i. Let z=1T∑tσt,1×⋯×σt,nz = \frac{1}{T}\sum_t \sigma_{t,1} \times \cdots \times \sigma_{t,n}. Then for every map δ\delta on the strategies of ii,

∑sz(s) [ui(δ(si),s−i)−ui(s)]=ΔiT RTi(δ).\sum_s z(s)\,\big[u_i(\delta(s_i), s_{-i}) - u_i(s)\big] = \frac{\Delta_i}{T}\, R^i_T(\delta).

So if every player has swap regret at most εT/Δi\varepsilon T / \Delta_i, then zz is a correlated ε\varepsilon-equilibrium.

Proof. Under the product σt\sigma_t, the strategy of player ii is independent of the others, so ∑sσt(s) [ui(δ(si),s−i)−ui(s)]=∑jσt,i(j) [ui(δ(j),σt,−i)−ui(j,σt,−i)]=Δi∑jσt,i(j) [ℓt(j)−ℓt(δ(j))]\sum_s \sigma_t(s)\,[u_i(\delta(s_i), s_{-i}) - u_i(s)] = \sum_j \sigma_{t,i}(j)\,[u_i(\delta(j), \sigma_{t,-i}) - u_i(j, \sigma_{t,-i})] = \Delta_i \sum_j \sigma_{t,i}(j)\,[\ell_t(j) - \ell_t(\delta(j))]. Average over tt. □\square

Conclusion. The distributions of lines L3 to L5 are well defined (Claim 1), the swap regret is at most the sum of the copies' external regrets (Claim 3), and with Hedge copies it is at most 2Tkln⁡k\sqrt{2 T k \ln k} (Claim 5). In self-play, the empirical distribution is a correlated ε\varepsilon-equilibrium with ε=max⁡iΔi2kln⁡k/T\varepsilon = \max_i \Delta_i \sqrt{2 k \ln k / T}, where kk is the largest number of strategies (Claim 6). ■\blacksquare

Complexity

Each round computes kk distributions of the copies, which takes O(k2)O(k^2) time for multiplicative weights, solves a kk by kk linear system in O(k3)O(k^3) time, and updates kk copies in O(k2)O(k^2) time. The total is O(Tk3)O(T k^3) time, or O(Tk2)O(T k^2) per round plus the cost of the stationary distribution if an iterative method such as power iteration is accurate enough. The memory is O(k2)O(k^2): kk copies of kk weights and the matrix QQ. For an ε\varepsilon-correlated equilibrium of a game with payoffs in [0,1][0, 1], the number of rounds is O(klog⁡k/ε2)O(k \log k / \varepsilon^2), and each round also needs the expected losses of each player, which costs O(nkn)O(n k^n) for a game in normal form.

Properties

  • Generic. Any external regret algorithm can be plugged in. The swap regret bound is the sum of the copies' bounds, on scaled losses.
  • Deterministic distributions. Given the losses, the distributions ptp_t are fixed; a learner that must play pure actions samples from ptp_t, and the regret bounds then hold in expectation.
  • Full information. Each copy needs the whole loss vector. Without it, the copies must be bandit algorithms such as Exp3, with a worse dependence on kk.
  • Stronger than external regret. Small swap regret implies small external regret, since constant maps are swaps. The converse fails: if the learner plays action 1 against the losses (1,0)(1, 0) and then action 2 against (0,1)(0, 1), each fixed action loses 1 and the learner loses 2, but the swap of the two actions loses 0.

Variants and improvements

  • Other base algorithms. With weighted majority, follow the leader with perturbations, or any algorithm for the expert problem, the bound changes accordingly. With regret matching as the base, the whole method uses no exponentials.
  • Internal regret. Foster and Vohra and Hart and Mas-Colell (2000) gave earlier procedures with no internal regret. Since swap regret is at most kk times internal regret, these also give no swap regret, with a worse dependence on kk.
  • Many actions. For swap regret εT\varepsilon T, the bound of this reduction needs TT of order klog⁡k/ε2k \log k / \varepsilon^2 rounds, linear in kk. In 2024, Dagan, Daskalakis, Fishelson and Golowich, and independently Peng and Rubinstein, gave a different reduction whose number of rounds for swap regret εT\varepsilon T is polylogarithmic in kk but exponential in 1/ε1/\varepsilon.
  • Faster rates in games. Anagnostides, Daskalakis, Farina, Fishelson, Golowich and Sandholm (2022) ran optimistic Hedge inside the copies and showed that, when all players learn this way, the swap regret of each player grows only polylogarithmically in TT.

When to use it

Use it when a learner must have no swap regret, for example to reach correlated rather than coarse correlated equilibria by repeated play, or when a forecast must be calibrated against each recommendation. If the game is small and given as a table, the correlated equilibrium LP gives an exact answer instead. If only external regret matters, a single copy is enough and is kk times cheaper.

Pitfalls

  • Unscaled losses in line L7. If every copy gets the full loss vector ℓt\ell_t, all copies see the same inputs, propose the same distribution, and the method is the base algorithm with only external regret. Copy jj must get pt(j)ℓtp_t(j)\ell_t.
  • The wrong distribution in line L5. Playing the average of the rows of QQ, or the row of the last action, breaks the identity p⋅ℓ=∑jqj⋅(p(j)ℓ)p \cdot \ell = \sum_j q_j \cdot (p(j)\ell), and the bound fails. Only a fixed point p=pQp = pQ works.
  • Power iteration in line L5. If a copy can propose distributions with zeros, such as follow the leader, the chain may be periodic and power iteration may not converge. Solve the linear system instead, or mix QQ with a small amount of the uniform matrix and account for the extra regret.
  • Comparing the wrong regrets. Swap regret is a sum over jj of separate maxima. Taking a single maximum over pairs (j,l)(j, l) gives the internal regret, which can be smaller by a factor up to kk.

Implementations

The Python code implements multiplicative weights (Hedge), the stationary distribution by Gaussian elimination with partial pivoting, and the reduction of lines L1 to L7, in floating point. The tests check the stationary step on random positive stochastic matrices, the identity that splits the learner's loss among the copies, the swap regret bound kln⁡k/η+ηt/2k \ln k / \eta + \eta t / 2 after every round against random, adaptive and periodic adversaries, and, in self-play in chicken, rock-paper-scissors and a random three-player game, that the correlated equilibrium gap of the empirical distribution equals the scaled swap regret.

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.

agtgame.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Finite games in normal form, with exact payoffs and exact equilibrium checks.

A game is a pair (sizes, pay). sizes is a tuple (k_1, ..., k_n) of the numbers of pure
strategies of the n players; the pure strategies of player i are 0, ..., k_i - 1. pay is a
dict that maps each profile, a tuple s = (s_1, ..., s_n), to a tuple of n Fraction
utilities, which each player maximizes. A cost game passes the utilities u = -c.

A mixed profile sigma is a list of n lists; sigma[i][a] is the probability, a Fraction,
that player i plays a. A distribution on profiles (for correlated and coarse correlated
equilibria) is a dict from profiles to Fraction; missing profiles have probability 0.

All checks are exact: there is no tolerance anywhere. There is no LP and no equilibrium
algorithm in this module.
"""

from fractions import Fraction
from itertools import product


def profiles(sizes):
    """Return the list of all pure profiles, in lexicographic order."""
    return list(product(*(range(k) for k in sizes)))


def from_bimatrix(A, B):
    """Return the game of the bimatrix (A, B): the row player gets A[r][c], the column player B[r][c]."""
    m, n = len(A), len(A[0])
    if len(B) != m or any(len(row) != n for row in A) or any(len(row) != n for row in B):
        raise ValueError("A and B must be m by n matrices of the same shape")
    pay = {(r, c): (Fraction(A[r][c]), Fraction(B[r][c])) for r in range(m) for c in range(n)}
    return (m, n), pay


def random_game(rng, sizes, lo, hi):
    """Return a game with integer utilities drawn uniformly from lo to hi (inclusive), as Fraction."""
    sizes = tuple(sizes)
    pay = {s: tuple(Fraction(rng.randint(lo, hi)) for _ in sizes) for s in profiles(sizes)}
    return sizes, pay


def _replace(s, i, a):
    return s[:i] + (a,) + s[i + 1:]


def _weight(sigma, s, skip=None):
    w = Fraction(1)
    for k, a in enumerate(s):
        if k != skip:
            w *= sigma[k][a]
            if w == 0:
                return w
    return w


def expected_utility(game, i, sigma):
    """Return u_i(sigma), the expected utility of player i when the players draw independently."""
    sizes, pay = game
    return sum((_weight(sigma, s) * pay[s][i] for s in profiles(sizes)), Fraction(0))


def deviation_payoffs(game, i, sigma):
    """Return the list of u_i(a, sigma_-i) for every pure strategy a of player i."""
    sizes, pay = game
    out = [Fraction(0)] * sizes[i]
    for s in profiles(sizes):
        w = _weight(sigma, s, skip=i)
        if w:
            out[s[i]] += w * pay[s][i]
    return out


def pure_best_responses(game, i, sigma):
    """Return the sorted list of the pure strategies of player i that maximize u_i(a, sigma_-i)."""
    d = deviation_payoffs(game, i, sigma)
    best = max(d)
    return [a for a, v in enumerate(d) if v == best]


def max_gain(game, sigma):
    """Return the largest gain of any player from a pure deviation: max_i (max_a u_i(a, sigma_-i) - u_i(sigma)).

    The result is never negative, because u_i(sigma) is an average of the deviation payoffs.
    """
    sizes, _ = game
    gain = Fraction(0)
    for i in range(len(sizes)):
        d = deviation_payoffs(game, i, sigma)
        u = sum((p * v for p, v in zip(sigma[i], d)), Fraction(0))
        gain = max(gain, max(d) - u)
    return gain


def is_distribution(p):
    """Return True if p (a sequence, or a dict of probabilities) is nonnegative and sums to exactly 1."""
    vals = list(p.values()) if isinstance(p, dict) else list(p)
    return all(v >= 0 for v in vals) and sum(vals, Fraction(0)) == 1


def _is_mixed_profile(game, sigma):
    sizes, _ = game
    return len(sigma) == len(sizes) and all(
        len(sigma[i]) == k and is_distribution(sigma[i]) for i, k in enumerate(sizes))


def is_nash(game, sigma):
    """Return True if sigma is a mixed Nash equilibrium: no pure deviation gains for any player."""
    return _is_mixed_profile(game, sigma) and max_gain(game, sigma) == 0


def is_epsilon_nash(game, sigma, eps):
    """Return True if no player gains more than eps by a pure deviation (the additive form)."""
    return _is_mixed_profile(game, sigma) and max_gain(game, sigma) <= eps


def _check_dist(game, dist):
    sizes, _ = game
    allowed = set(profiles(sizes))
    return all(s in allowed for s in dist) and is_distribution(dist)


def is_correlated(game, dist):
    """Return True if dist is a correlated equilibrium.

    For every player i and every pair a, b of its pure strategies, the sum over the profiles s
    with s_i = a of dist(s) (u_i(s) - u_i(b, s_-i)) is at least 0.
    """
    sizes, pay = game
    if not _check_dist(game, dist):
        return False
    for i, k in enumerate(sizes):
        for a in range(k):
            rows = [(q, s) for s, q in dist.items() if s[i] == a and q]
            for b in range(k):
                if b != a and sum((q * (pay[s][i] - pay[_replace(s, i, b)][i]) for q, s in rows), Fraction(0)) < 0:
                    return False
    return True


def is_coarse_correlated(game, dist):
    """Return True if dist is a coarse correlated equilibrium.

    For every player i and every pure strategy b, E_{s ~ dist} u_i(s) >= E_{s ~ dist} u_i(b, s_-i).
    """
    sizes, pay = game
    if not _check_dist(game, dist):
        return False
    for i, k in enumerate(sizes):
        here = sum((q * pay[s][i] for s, q in dist.items()), Fraction(0))
        for b in range(k):
            if sum((q * pay[_replace(s, i, b)][i] for s, q in dist.items()), Fraction(0)) > here:
                return False
    return True


def pure_nash_brute(game):
    """Return the list of all pure Nash equilibria, found by checking every profile."""
    sizes, pay = game
    out = []
    for s in profiles(sizes):
        if all(pay[s][i] >= pay[_replace(s, i, b)][i] for i in range(len(sizes)) for b in range(sizes[i])):
            out.append(s)
    return out
blum_mansour_reduction.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/blum-mansour-reduction/. The authors are listed in prov/FWT8FT.jsonl.
"""The Blum-Mansour reduction from swap regret to external regret, with Hedge copies.

There are k actions and losses in [0, 1]. The learner keeps k copies of Hedge. In each
round, copy j proposes a distribution q_j; the learner plays a distribution p with p = p Q,
where row j of Q is q_j, and after it sees the loss vector it gives copy j the scaled loss
vector p(j) * loss. The swap regret of the learner is at most the sum of the external
regrets of the copies. Arithmetic is in float.
"""

import math


class Hedge:
    """Hedge (exponential weights) on k actions with a fixed learning rate eta > 0."""

    def __init__(self, k, eta):
        if k < 1 or eta <= 0:
            raise ValueError("need k >= 1 and eta > 0")
        self.eta = eta
        self.cum = [0.0] * k  # cumulative loss of each action

    def distribution(self):
        low = min(self.cum)  # shift for numerical safety; it cancels in the ratio
        w = [math.exp(-self.eta * (c - low)) for c in self.cum]
        total = sum(w)
        return [x / total for x in w]

    def update(self, loss):
        for a, v in enumerate(loss):
            self.cum[a] += v


def stationary(Q):
    """Return the distribution p with p = p Q for a row-stochastic k by k matrix Q with
    positive entries (then p is unique). Gaussian elimination with partial pivoting."""
    k = len(Q)
    # Equations: sum_j p_j (Q[j][i] - [i == j]) = 0 for i < k - 1, and sum_j p_j = 1.
    M = [[Q[j][i] - (1.0 if i == j else 0.0) for j in range(k)] + [0.0] for i in range(k - 1)]
    M.append([1.0] * k + [1.0])
    for col in range(k):
        piv = max(range(col, k), key=lambda r: abs(M[r][col]))
        M[col], M[piv] = M[piv], M[col]
        pv = M[col][col]
        for r in range(k):
            if r != col and M[r][col] != 0.0:
                f = M[r][col] / pv
                M[r] = [a - f * b for a, b in zip(M[r], M[col])]
    p = [max(M[i][k] / M[i][i], 0.0) for i in range(k)]
    total = sum(p)
    return [x / total for x in p]


class BlumMansour:
    """A no-swap-regret learner on k actions built from k copies of Hedge."""

    def __init__(self, k, eta):
        self.k = k
        self.copies = [Hedge(k, eta) for _ in range(k)]  # @line L1
        self.p = None
        self.Q = None

    def distribution(self):
        rows = [c.distribution() for c in self.copies]  # @line L3
        self.Q = rows  # @line L4
        self.p = stationary(self.Q)  # @line L5
        return self.p

    def update(self, loss):
        for j, c in enumerate(self.copies):  # @line L7
            c.update([self.p[j] * v for v in loss])


def run(k, T, eta, adversary):
    """Run the learner for T rounds. adversary(t, p) returns the loss vector of round t; it
    may look at the current distribution p. Return the lists of the distributions played,
    the loss vectors and the matrices Q."""
    learner = BlumMansour(k, eta)
    ps, losses, Qs = [], [], []
    for t in range(T):  # @line L2
        p = learner.distribution()
        loss = adversary(t, p)  # @line L6
        learner.update(loss)
        ps.append(p)
        losses.append(loss)
        Qs.append(learner.Q)
    return ps, losses, Qs


def swap_regret(ps, losses):
    """Return max over maps delta of sum_t sum_j p_t(j) (loss_t(j) - loss_t(delta(j))).
    The maximum splits over j: each j is sent to the action with the least weighted loss."""
    k = len(ps[0]) if ps else 0
    total = 0.0
    for j in range(k):
        here = sum(p[j] * l[j] for p, l in zip(ps, losses))
        best = min(sum(p[j] * l[a] for p, l in zip(ps, losses)) for a in range(k))
        total += here - best
    return total


def external_regret(ps, losses):
    """Return sum_t p_t . loss_t minus the least total loss of a fixed action."""
    k = len(ps[0]) if ps else 0
    here = sum(sum(x * v for x, v in zip(p, l)) for p, l in zip(ps, losses))
    return here - min(sum(l[a] for l in losses) for a in range(k)) if ps else 0.0


def regret_bound(k, T, eta):
    """The bound k ln k / eta + eta T / 2 on the swap regret after T rounds (losses in [0, 1])."""
    return k * math.log(k) / eta + eta * T / 2
test_blum_mansour_reduction.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/blum-mansour-reduction/. The authors are listed in prov/FWT8FT.jsonl.
"""Tests of the Blum-Mansour reduction: the stationary step, the regret decomposition, the
swap regret bound at every round against several adversaries, and self-play in games."""

import math
import random

import pytest

from agtgame import deviation_payoffs, from_bimatrix, profiles, random_game
from blum_mansour_reduction import BlumMansour, Hedge, external_regret, regret_bound, run, stationary, swap_regret


def tuned_eta(k, T):
    return math.sqrt(2 * k * math.log(k) / T) if k > 1 else 1.0


def test_stationary_distribution():
    rng = random.Random(11)
    for _ in range(200):
        k = rng.randint(1, 6)
        Q = []
        for _ in range(k):
            row = [rng.random() + 1e-3 for _ in range(k)]
            s = sum(row)
            Q.append([x / s for x in row])
        p = stationary(Q)
        assert all(x >= 0 for x in p) and abs(sum(p) - 1) < 1e-12
        for i in range(k):
            assert abs(sum(p[j] * Q[j][i] for j in range(k)) - p[i]) < 1e-12


def test_hedge_distribution_and_validation():
    h = Hedge(3, 0.5)
    assert h.distribution() == [1 / 3] * 3
    h.update([1.0, 0.0, 2.0])
    d = h.distribution()
    assert abs(d[1] / d[0] - math.exp(0.5)) < 1e-12 and abs(d[0] / d[2] - math.exp(0.5)) < 1e-12
    with pytest.raises(ValueError):
        Hedge(0, 1.0)
    with pytest.raises(ValueError):
        Hedge(2, 0.0)


def test_decomposition_into_copies():
    """The loss of the learner is the sum of the losses of the copies, and its swap regret is at
    most the sum of their external regrets on the scaled losses."""
    rng = random.Random(3)
    for k in (2, 3, 5):
        ps, losses, Qs = run(k, 150, 0.3, lambda t, p: [rng.random() for _ in range(k)])
        mine = sum(sum(x * v for x, v in zip(p, l)) for p, l in zip(ps, losses))
        theirs = 0.0
        copy_regret = 0.0
        for j in range(k):
            scaled = [[p[j] * v for v in l] for p, l in zip(ps, losses)]
            qs = [Q[j] for Q in Qs]
            theirs += sum(sum(x * v for x, v in zip(q, l)) for q, l in zip(qs, scaled))
            copy_regret += external_regret(qs, scaled)
        assert abs(mine - theirs) < 1e-9
        assert swap_regret(ps, losses) <= copy_regret + 1e-9
        assert external_regret(ps, losses) <= swap_regret(ps, losses) + 1e-9


def adversaries(rng, k):
    yield lambda t, p: [rng.random() for _ in range(k)]
    yield lambda t, p: [1.0 if a == max(range(k), key=lambda b: p[b]) else 0.0 for a in range(k)]
    # A sequence that rewards a shifted copy of the last action: good for swaps, bad for Hedge alone.
    yield lambda t, p: [0.0 if a == (t // 7) % k else (1.0 if a == (t // 7 + 1) % k else 0.5) for a in range(k)]
    yield lambda t, p: [float((a + t) % 2) for a in range(k)]


def test_swap_regret_bound_at_every_round():
    rng = random.Random(2024)
    T = 400
    for k in (1, 2, 3, 4):
        eta = tuned_eta(k, T)
        for adv in adversaries(rng, k):
            learner = BlumMansour(k, eta)
            W = [[0.0] * k for _ in range(k)]  # W[j][a] = sum_t p_t(j) loss_t(a)
            for t in range(1, T + 1):
                p = learner.distribution()
                loss = adv(t, p)
                learner.update(loss)
                for j in range(k):
                    for a in range(k):
                        W[j][a] += p[j] * loss[a]
                swap = sum(W[j][j] - min(W[j]) for j in range(k))
                bound = regret_bound(k, t, eta) if k > 1 else 0.0
                assert swap <= bound + 1e-9
        if k > 1:
            assert abs(regret_bound(k, T, eta) - math.sqrt(2 * T * k * math.log(k))) < 1e-9


def test_one_action():
    ps, losses, _ = run(1, 20, 1.0, lambda t, p: [0.3])
    assert all(p == [1.0] for p in ps) and swap_regret(ps, losses) == 0


def self_play(game, T, eta):
    sizes, pay = game
    n = len(sizes)
    lo = [min(pay[s][i] for s in pay) for i in range(n)]
    hi = [max(pay[s][i] for s in pay) for i in range(n)]
    span = [float(hi[i] - lo[i]) or 1.0 for i in range(n)]
    learners = [BlumMansour(k, eta) for k in sizes]
    history = []
    z = {s: 0.0 for s in profiles(sizes)}
    for _ in range(T):
        sigma = [L.distribution() for L in learners]
        for s in z:
            w = 1.0
            for i, a in enumerate(s):
                w *= sigma[i][a]
            z[s] += w / T
        losses = []
        for i in range(n):
            d = deviation_payoffs(game, i, sigma)
            losses.append([(float(hi[i]) - float(v)) / span[i] for v in d])
        for L, l in zip(learners, losses):
            L.update(l)
        history.append((sigma, losses))
    return z, history, span


def ce_gap(game, z, i):
    sizes, pay = game
    gap = 0.0
    for j in range(sizes[i]):
        best = 0.0
        for l in range(sizes[i]):
            g = sum(q * float(pay[s[:i] + (l,) + s[i + 1:]][i] - pay[s][i]) for s, q in z.items() if s[i] == j)
            best = max(best, g)
        gap += best
    return gap


def test_self_play_gives_an_approximate_correlated_equilibrium():
    chicken = from_bimatrix([[0, 7], [2, 6]], [[0, 2], [7, 6]])
    rps = from_bimatrix([[0, -1, 1], [1, 0, -1], [-1, 1, 0]], [[0, 1, -1], [-1, 0, 1], [1, -1, 0]])
    three = random_game(random.Random(8), (2, 2, 3), -2, 2)
    for game, T in ((chicken, 300), (rps, 300), (three, 120)):
        k = max(game[0])
        eta = tuned_eta(k, T)
        z, history, span = self_play(game, T, eta)
        for i in range(len(game[0])):
            ps = [sigma[i] for sigma, _ in history]
            losses = [l[i] for _, l in history]
            swap = swap_regret(ps, losses)
            # The swap regret in losses is the correlated equilibrium gap of z, scaled.
            assert abs(ce_gap(game, z, i) - span[i] * swap / T) < 1e-9
            assert swap <= regret_bound(game[0][i], T, eta) + 1e-9
            assert ce_gap(game, z, i) <= span[i] * regret_bound(k, T, eta) / T + 1e-9


def test_regret_definitions_on_small_cases():
    ps = [[1.0, 0.0], [0.0, 1.0]]
    losses = [[1.0, 0.0], [1.0, 0.0]]
    # The swap 0 -> 1 saves 1 in round 1, and the learner already plays action 1 in round 2.
    assert swap_regret(ps, losses) == 1.0 and external_regret(ps, losses) == 1.0
    losses = [[1.0, 0.0], [0.0, 1.0]]
    # The learner loses 2 and each fixed action loses 1, but the swap 0 <-> 1 loses 0.
    assert external_regret(ps, losses) == 1.0 and swap_regret(ps, losses) == 2.0

History

Foster and Vohra (1997) showed that players who best respond to calibrated forecasts reach correlated equilibria, and procedures with no internal regret followed. Hart and Mas-Colell (2000) gave regret matching. Blum and Mansour gave the general reduction from external to swap regret; the conference version appeared at COLT in 2005 and the journal version in 2007. Roughgarden's lecture notes made it the standard proof that no-swap-regret dynamics converge to correlated equilibria.

References

  1. From external to internal regret, the generic reduction from swap regret to external regret, and its bound O(sqrt(T k log k)) with multiplicative weights
  2. Tim Roughgarden, Twenty Lectures on Algorithmic Game Theory, Cambridge University Press, 2016, Lecture 18 (swap regret, the reduction, and no-swap-regret dynamics converging to correlated equilibria)
  3. Sergiu Hart and Andreu Mas-Colell, A simple adaptive procedure leading to correlated equilibrium, Econometrica 68(5) (2000), 1127-1150, Section 3 (regrets and correlated epsilon-equilibria)
  4. Nicolo Cesa-Bianchi and Gabor Lugosi, Prediction, Learning, and Games, Cambridge University Press, 2006, the treatment of internal and swap regret

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