Algorithm Search⌘K

Algorithmcore

Regret matching

Also called Hart-Mas-Colell regret matching.

Switches from the last action to each other action with probability proportional to its positive conditional regret. The empirical play converges to the correlated equilibria.

Time
O(n k T) worst
Space
O(n k^2) extra
Where
T = the number of rounds; k = the largest number of pure strategies of a player; n = the number of players
Properties
randomizednot exactonlineiterative
Origin
Sergiu Hart, Andreu Mas Colell, 2000

Regret matching is a learning rule for a repeated finite game. A player who played jj in the last round switches to another strategy ll with probability proportional to the positive part of the conditional regret D(j,l)D(j, l): how much more the player would have earned so far by playing ll in every round in which it played jj. Hart and Mas-Colell (2000) proved that if every player uses it, the empirical distribution of play converges almost surely to the set of correlated equilibria. The rule is simpler than the Blum-Mansour reduction, which reaches the same set through no swap regret with a stationary distribution in each round. Its unconditional version, which plays each action with probability proportional to its positive external regret, only reaches coarse correlated equilibria; it is the learner inside counterfactual regret minimization. The general scheme behind both is no-regret dynamics, and the proof uses Blackwell approachability.

In plain words

A game is played again and again. After each round, a player looks back at the rounds in which it made its last choice. For every other choice, it asks: had I made that other choice in all those rounds, how much more would I have earned? These amounts are regrets. The player then switches to another choice with a chance that grows with its regret, and stays with the last choice otherwise. Choices that would not have helped get no chance. A fixed constant keeps the total chance of switching below one. When everybody plays this way, the record of how often each combination of choices appeared settles into a pattern that a mediator could recommend and nobody would want to disobey.

The problem

The input is a finite game with players N={1,…,n}N = \{1, \ldots, n\}, pure strategy sets SiS_i with ki=∣Si∣≤kk_i = |S_i| \le k, and utilities ui:S→Qu_i : S \to \mathbb{Q}, maximized. Let Δi=max⁡sui(s)−min⁡sui(s)\Delta_i = \max_s u_i(s) - \min_s u_i(s) be the payoff range of player ii. The game is played for TT rounds; st∈Ss^t \in S is the profile of round tt. The empirical distribution is zT(s)=∣{t≤T:st=s}∣/Tz_T(s) = |\{t \le T : s^t = s\}| / T.

For player ii and strategies j≠lj \ne l in SiS_i, the cumulative conditional regret after round tt is

Dit(j,l)=∑τ≤t, siτ=j[ui(l,s−iτ)−ui(sτ)].D^t_i(j, l) = \sum_{\tau \le t,\ s^\tau_i = j} \big[u_i(l, s^\tau_{-i}) - u_i(s^\tau)\big].

A distribution zz on SS is a correlated ε\varepsilon-equilibrium if ∑s:si=jz(s) [ui(l,s−i)−ui(s)]≤ε\sum_{s : s_i = j} z(s)\,[u_i(l, s_{-i}) - u_i(s)] \le \varepsilon for all ii and j≠lj \ne l. The goal is a sequence of play whose empirical distribution zTz_T is a correlated εT\varepsilon_T-equilibrium with εT→0\varepsilon_T \to 0. Each player sees the past profiles and knows its own utility; it does not need the utilities of the others.

The algorithm

Each player ii uses an inertia constant μ>(ki−1)Δi\mu > (k_i - 1)\Delta_i; one μ\mu above all these bounds serves every player.

  1. REGRET-MATCHING(G, mu, T) ▷ every player i uses the same rule
  2. 1D_i(j, l) ← 0 for every player i and every pair j ≠ l in S_i
  3. 2draw s^1, each s^1_i uniform in S_i
  4. 3for t = 1, 2, ..., T
  5. 4for each player i
  6. 5j ← s^t_i ▷ the strategy just played
  7. 6for each l ≠ j: D_i(j, l) ← D_i(j, l) + u_i(l, s^t_-i) - u_i(s^t)
  8. 7for each l ≠ j: p_i(l) ← max(D_i(j, l), 0) / (t mu)
  9. 8p_i(j) ← 1 - Σ_{l ≠ j} p_i(l) ▷ inertia: stay with j
  10. 9draw s^{t+1}, each s^{t+1}_i from p_i, independently
  11. 10return z_T, the uniform distribution on s^1, ..., s^T, and D

Line L6 updates only the row jj of the regret matrix of player ii, the row of the strategy just played, so after round tt the entry Di(j,l)D_i(j, l) equals Dit(j,l)D^t_i(j, l). Line L7 is the switching probability Rt(j,l)/μR_t(j, l) / \mu of Hart and Mas-Colell, where Rt=max⁡(Dt/t,0)R_t = \max(D^t / t, 0) is the average positive regret. Each Dit(j,l)/tD^t_i(j, l)/t is at most Δi\Delta_i, so the sum in line L8 is at most (ki−1)Δi/μ<1(k_i - 1)\Delta_i / \mu < 1, and pip_i is a probability distribution with pi(j)>0p_i(j) > 0. The constant μ\mu is what makes the rule conditional: the probability of jj is not a regret but the remainder, so a player with small regrets mostly repeats itself.

The unconditional version keeps one cumulative external regret Ri(l)=∑τ≤t[ui(l,s−iτ)−ui(sτ)]R_i(l) = \sum_{\tau \le t} [u_i(l, s^\tau_{-i}) - u_i(s^\tau)] per strategy and plays pi(l)=Ri(l)+/∑l′Ri(l′)+p_i(l) = R_i(l)^+ / \sum_{l'} R_i(l')^+, or any distribution when all regrets are at most 0. It needs no μ\mu and does not depend on the last strategy.

Example

Take chicken with strategies D (dare) and C (chicken) and payoffs (D, D) = (0, 0), (D, C) = (7, 2), (C, D) = (2, 7) and (C, C) = (6, 6). Here ki=2k_i = 2 and Δi=7\Delta_i = 7, so μ=8\mu = 8 works. Suppose the first profile is (C, C) and the first draw sends the row player to D.

tt sts^t D1(C,D)D_1(\text{C}, \text{D}) D1(D,C)D_1(\text{D}, \text{C}) D2(C,D)D_2(\text{C}, \text{D}) row player at t+1t + 1 column player at t+1t + 1
1 (C, C) 7 - 6 = 1 0 1 D with prob. 1/8 (drawn) D with prob. 1/8 (not drawn)
2 (D, C) 1 6 - 7 = -1 1 + (0 - 2) = -1 C with prob. 0 D with prob. 0
3 (D, C) 1 -2 -3 C with prob. 0 D with prob. 0
4 (D, C) 1 -3 -5 C with prob. 0 D with prob. 0

From round 2 on, both regrets of the strategies being played are negative, so nobody switches, and (D, C), a pure Nash equilibrium, repeats for ever. After TT rounds, zTz_T puts 1/T1/T on (C, C) and (T−1)/T(T - 1)/T on (D, C). The only positive regret is D1(C,D)=1D_1(\text{C}, \text{D}) = 1, and indeed zTz_T is a correlated ε\varepsilon-equilibrium exactly for ε≥1/T\varepsilon \ge 1/T: the row player, told C, gains zT(C,C)⋅(7−6)=1/Tz_T(\text{C}, \text{C}) \cdot (7 - 6) = 1/T by playing D. Other draws give longer runs, and in general the limit points of zTz_T need not be products. The uniform distribution on (D, C), (C, D) and (C, C), with payoff 5 each, is a correlated equilibrium of this game that no product distribution gives.

Correctness

The proof has an exact part and a probabilistic part.

The exact part is an identity. For every ii and j≠lj \ne l,

∑s:si=jzT(s) [ui(l,s−i)−ui(s)]=DiT(j,l)T,\sum_{s : s_i = j} z_T(s)\,\big[u_i(l, s_{-i}) - u_i(s)\big] = \frac{D^T_i(j, l)}{T},

because both sides add the same terms, one for each round tt with sit=js^t_i = j, divided by TT. So zTz_T is a correlated ε\varepsilon-equilibrium if and only if max⁡i,j,lDiT(j,l)≤εT\max_{i, j, l} D^T_i(j, l) \le \varepsilon T, and the algorithm knows its own exact error. The same identity with the external regrets says that the empirical distribution is a coarse correlated ε\varepsilon-equilibrium if and only if every external regret is at most εT\varepsilon T.

The probabilistic part is the theorem of Hart and Mas-Colell: if every player uses lines L5 to L9 with μ>(ki−1)Δi\mu > (k_i - 1)\Delta_i, then max⁡(DiT(j,l),0)/T→0\max(D^T_i(j, l), 0)/T \to 0 almost surely for all ii, jj and ll, so zTz_T converges almost surely to the set of correlated equilibria. Their proof follows the squared distance of the average regret vector to the negative orthant and shows that it falls in expectation, with an extra argument for the inertia. For the unconditional version there is a short deterministic bound, proved in the proof file: if the regret is updated with the expected payoff of pip_i, then the external regret after tt rounds is at most Δikit\Delta_i \sqrt{k_i t} against any opponents. The proof file has the identity, the bound and the well-definedness of line L8.

Proof: Regret matching is well defined, its regrets are the exact equilibrium gaps of the empirical distribution, and the unconditional version has regret at most delta sqrt(k t)full

Let GG be a finite game with players 1,…,n1, \ldots, n, pure strategy sets SiS_i with ki=∣Si∣k_i = |S_i|, utilities uiu_i (maximized) and payoff ranges Δi=max⁡sui(s)−min⁡sui(s)\Delta_i = \max_s u_i(s) - \min_s u_i(s). Let s1,s2,…s^1, s^2, \ldots be the profiles that the algorithm plays, and Dit(j,l)=∑τ≤t, siτ=j[ui(l,s−iτ)−ui(sτ)]D^t_i(j, l) = \sum_{\tau \le t,\ s^\tau_i = j} [u_i(l, s^\tau_{-i}) - u_i(s^\tau)] for j≠lj \ne l. This file proves four claims. The almost sure convergence of the regrets of the conditional rule to 0 is the Main Theorem of Hart and Mas-Colell (2000); its proof is in their Appendix 1 and is not repeated here.

Claim 1 (the invariant). After line L6 of round tt, the stored value Di(j,l)D_i(j, l) equals Dit(j,l)D^t_i(j, l) for every player ii and every j≠lj \ne l.

Proof. By induction on tt. Before round 1 all stored values are 0 (line L1), and Di0(j,l)D^0_i(j, l) is an empty sum. Suppose the claim holds after round t−1t - 1. In round tt, line L6 adds ui(l,s−it)−ui(st)u_i(l, s^t_{-i}) - u_i(s^t) to Di(j,l)D_i(j, l) for j=sitj = s^t_i and every l≠jl \ne j, and changes no other entry. By definition, Dit(j,l)−Dit−1(j,l)D^t_i(j, l) - D^{t-1}_i(j, l) is exactly this term when j=sitj = s^t_i and 0 otherwise. □\square

Claim 2 (line L8 gives a distribution). If μ>(ki−1)Δi\mu > (k_i - 1)\Delta_i, then in every round the vector pip_i of lines L7 and L8 is a probability distribution on SiS_i with pi(j)>0p_i(j) > 0, where j=sitj = s^t_i.

Proof. Each term of Dit(j,l)D^t_i(j, l) is a difference of two payoffs of player ii, so it is at most Δi\Delta_i, and there are at most tt terms. So 0≤max⁡(Dit(j,l),0)/(tμ)≤Δi/μ0 \le \max(D^t_i(j, l), 0) / (t\mu) \le \Delta_i / \mu for each l≠jl \ne j, and by Claim 1 these are the values pi(l)p_i(l) of line L7. Their sum is at most (ki−1)Δi/μ<1(k_i - 1)\Delta_i / \mu < 1, so pi(j)=1−∑l≠jpi(l)>0p_i(j) = 1 - \sum_{l \ne j} p_i(l) > 0, and all entries are nonnegative and sum to 1. □\square

Claim 3 (the exact gap). Let zTz_T be the empirical distribution returned in line L10. For every player ii and j≠lj \ne l,

∑s∈S:si=jzT(s) [ui(l,s−i)−ui(s)]=DiT(j,l)T.\sum_{s \in S : s_i = j} z_T(s)\,\big[u_i(l, s_{-i}) - u_i(s)\big] = \frac{D^T_i(j, l)}{T}.

So zTz_T is a correlated ε\varepsilon-equilibrium if and only if DiT(j,l)≤εTD^T_i(j, l) \le \varepsilon T for all ii and j≠lj \ne l; in particular it is a correlated equilibrium if and only if all these regrets are at most 0. The same computation with EiT(l)=∑τ≤T[ui(l,s−iτ)−ui(sτ)]E^T_i(l) = \sum_{\tau \le T} [u_i(l, s^\tau_{-i}) - u_i(s^\tau)] shows that zTz_T is a coarse correlated ε\varepsilon-equilibrium if and only if EiT(l)≤εTE^T_i(l) \le \varepsilon T for all ii and ll.

Proof. By definition zT(s)=1T∣{τ≤T:sτ=s}∣z_T(s) = \frac{1}{T} |\{\tau \le T : s^\tau = s\}|. So

∑s:si=jzT(s) [ui(l,s−i)−ui(s)]=1T∑s:si=j ∑τ≤T:sτ=s[ui(l,s−iτ)−ui(sτ)]=1T∑τ≤T:siτ=j[ui(l,s−iτ)−ui(sτ)],\sum_{s : s_i = j} z_T(s)\,[u_i(l, s_{-i}) - u_i(s)] = \frac{1}{T} \sum_{s : s_i = j} \ \sum_{\tau \le T : s^\tau = s} [u_i(l, s^\tau_{-i}) - u_i(s^\tau)] = \frac{1}{T} \sum_{\tau \le T : s^\tau_i = j} [u_i(l, s^\tau_{-i}) - u_i(s^\tau)],

because each round τ\tau with siτ=js^\tau_i = j appears exactly once, under s=sτs = s^\tau. The last sum is DiT(j,l)D^T_i(j, l). The correlated ε\varepsilon-equilibrium condition is that the left side is at most ε\varepsilon for all ii and j≠lj \ne l, which proves the equivalence. For the coarse version, the left side becomes ∑szT(s)[ui(l,s−i)−ui(s)]\sum_s z_T(s)[u_i(l, s_{-i}) - u_i(s)], and the same exchange of sums gives EiT(l)/TE^T_i(l)/T. □\square

Claim 4 (the unconditional bound). Fix a player with kk actions. In each round tt an adversary picks a payoff vector ut∈Rku_t \in \mathbb{R}^k whose entries lie in an interval of length Δ\Delta. The player plays pt(l)=Rt−1(l)+/∑l′Rt−1(l′)+p_t(l) = R_{t-1}(l)^+ / \sum_{l'} R_{t-1}(l')^+, or the uniform distribution if all Rt−1(l)≤0R_{t-1}(l) \le 0, and then sets Rt=Rt−1+rtR_t = R_{t-1} + r_t with rt(l)=ut(l)−⟨pt,ut⟩r_t(l) = u_t(l) - \langle p_t, u_t \rangle and R0=0R_0 = 0. Then for every tt,

max⁡lRt(l)=max⁡l∑τ≤tuτ(l)−∑τ≤t⟨pτ,uτ⟩≤Δkt.\max_l R_t(l) = \max_l \sum_{\tau \le t} u_\tau(l) - \sum_{\tau \le t} \langle p_\tau, u_\tau \rangle \le \Delta \sqrt{k t}.

Proof. Write x=Rt−1x = R_{t-1} and r=rtr = r_t. First, (xl+rl)+≤∣xl++rl∣(x_l + r_l)^+ \le |x_l^+ + r_l| for each ll: if xl≥0x_l \ge 0 then xl+=xlx_l^+ = x_l and (xl+rl)+≤∣xl+rl∣(x_l + r_l)^+ \le |x_l + r_l|; if xl<0x_l < 0 then (xl+rl)+≤rl+≤∣rl∣=∣xl++rl∣(x_l + r_l)^+ \le r_l^+ \le |r_l| = |x_l^+ + r_l|. Squaring and adding over ll,

∥Rt+∥2≤∥x++r∥2=∥x+∥2+2⟨x+,r⟩+∥r∥2.\|R_t^+\|^2 \le \|x^+ + r\|^2 = \|x^+\|^2 + 2\langle x^+, r \rangle + \|r\|^2 .

Second, ⟨x+,r⟩=0\langle x^+, r \rangle = 0. If x+=0x^+ = 0 this is clear. Otherwise pt=x+/cp_t = x^+ / c with c=∑lxl+>0c = \sum_l x_l^+ > 0, and ⟨x+,r⟩=∑lxl+ut(l)−c⟨pt,ut⟩=c⟨pt,ut⟩−c⟨pt,ut⟩=0\langle x^+, r \rangle = \sum_l x_l^+ u_t(l) - c \langle p_t, u_t \rangle = c\langle p_t, u_t \rangle - c\langle p_t, u_t \rangle = 0. Third, ⟨pt,ut⟩\langle p_t, u_t \rangle is an average of the entries of utu_t, so it lies in the same interval of length Δ\Delta, and ∣rl∣≤Δ|r_l| \le \Delta; so ∥r∥2≤kΔ2\|r\|^2 \le k\Delta^2. Together, ∥Rt+∥2≤∥Rt−1+∥2+kΔ2\|R_t^+\|^2 \le \|R_{t-1}^+\|^2 + k\Delta^2, and by induction from R0=0R_0 = 0, ∥Rt+∥2≤tkΔ2\|R_t^+\|^2 \le t k \Delta^2. Finally max⁡lRt(l)≤max⁡lRt(l)+≤∥Rt+∥≤Δkt\max_l R_t(l) \le \max_l R_t(l)^+ \le \|R_t^+\| \le \Delta\sqrt{kt}. □\square

Corollary (self-play with expected payoffs). Suppose every player ii runs the rule of Claim 4 with ut(l)=ui(l,σ−it)u_t(l) = u_i(l, \sigma^t_{-i}), where σt\sigma^t is the profile of mixed strategies of round tt, so that ⟨pt,ut⟩=ui(σt)\langle p_t, u_t \rangle = u_i(\sigma^t). Let νT=1T∑t≤Tσ1t×⋯×σnt\nu_T = \frac{1}{T}\sum_{t \le T} \sigma^t_1 \times \cdots \times \sigma^t_n. Then νT\nu_T is a coarse correlated ε\varepsilon-equilibrium with ε=max⁡iΔiki/T\varepsilon = \max_i \Delta_i \sqrt{k_i / T}.

Proof. The entries of utu_t are averages of payoffs of player ii, so they lie in an interval of length Δi\Delta_i. By linearity of expectation, Es∼νT[ui(b,s−i)−ui(s)]=1T∑t≤T[ui(b,σ−it)−ui(σt)]=RT(b)/T\mathbb{E}_{s \sim \nu_T}[u_i(b, s_{-i}) - u_i(s)] = \frac{1}{T} \sum_{t \le T} [u_i(b, \sigma^t_{-i}) - u_i(\sigma^t)] = R_T(b) / T, which is at most ΔikiT/T\Delta_i \sqrt{k_i T} / T by Claim 4. ■\blacksquare

Complexity

In each round, line L6 costs ki−1k_i - 1 payoff lookups and additions for player ii, lines L7 and L8 cost O(ki)O(k_i), and line L9 costs O(ki)O(k_i) to draw. So a round costs O(nk)O(n k) and TT rounds cost O(nkT)O(n k T), plus the cost of recording the profiles. The regret matrices take O(nk2)O(n k^2) space; the empirical distribution takes space for its support, at most min⁡(T,∣S∣)\min(T, |S|) profiles.

The speed is slow. For their stationary-distribution variant, Hart and Mas-Colell note that the expected regrets are of order 1/t1/\sqrt{t}, so an ε\varepsilon-equilibrium takes on the order of 1/ε21/\varepsilon^2 rounds, with constants that depend on kk and the payoffs, and no procedure can do better in general when the others play fixed mixed strategies. In the unconditional version, the bound ΔkT\Delta \sqrt{k T} gives an ε\varepsilon-coarse correlated equilibrium, for payoffs in [0,1][0, 1], after T=k/ε2T = k / \varepsilon^2 rounds; multiplicative weights needs only O(log⁡k/ε2)O(\log k / \varepsilon^2) rounds, but regret matching has no step size to tune.

Properties

  • Uncoupled and simple. A player needs only its own payoffs and the past play; there is no step size and no stationary distribution to compute.
  • Not universal. The conditional rule (lines L5 to L9) does not guarantee small regrets against arbitrary opponents; Hart and Mas-Colell give adversaries that keep its regrets positive. The guarantee needs all players to use it. The unconditional version and the stationary-distribution variant are universal.
  • Time averages, not play. Only the empirical distribution converges, and it converges to a set, not to a point. In the example it settles on a pure Nash equilibrium, but in general it can keep moving inside the set of correlated equilibria.
  • Zero probability for bad replies. A strategy with no positive regret gets probability 0, unlike smooth fictitious play, which plays every strategy with positive probability.

Variants and improvements

  • Unconditional regret matching. Probabilities proportional to the positive external regrets give no external regret (Hart and Mas-Colell, Theorem B), so the empirical distribution converges to the coarse correlated equilibria, a larger set. With expected payoffs the bound is deterministic.
  • Regret matching plus. Clip the cumulative regrets at 0 after each round, and average the strategies with weights that grow with tt. This variant, used in counterfactual regret minimization for poker, converges much faster in practice in zero-sum games.
  • Stationary-distribution version. Play the invariant distribution of the matrix of positive regrets (Hart and Mas-Colell, Theorem A). It has no swap regret against any opponents, like the Blum-Mansour reduction.
  • Counterfactual regret minimization. In an extensive-form game, run unconditional regret matching at every information set, on counterfactual values; in two-player zero-sum games the average strategies converge to a Nash equilibrium.

When to use it

Use it when players should learn a correlated equilibrium with no knowledge of the others' payoffs and no step size, or as a simple model of adaptive behavior. To compute a correlated equilibrium of a game given in normal form, the linear program is exact and faster. For guarantees against arbitrary opponents, use the unconditional version (for external regret) or the Blum-Mansour reduction (for swap regret). In large zero-sum games, use regret matching plus inside counterfactual regret minimization.

Pitfalls

  • A too small inertia. With μ≤(ki−1)Δi\mu \le (k_i - 1)\Delta_i in line L7, the sum in line L8 can exceed 1, and pi(j)p_i(j) becomes negative. Choose μ\mu above the bound.
  • Dividing by the wrong count. Line L7 divides by tt, the number of rounds, not by the number of rounds in which jj was played; with the latter the procedure is a different one, and the theorem does not cover it.
  • Updating the wrong row. Line L6 changes only the row of the strategy just played. Adding the round to every row turns every row into the external regrets, the theorem no longer applies, and small external regrets certify only a coarse correlated equilibrium.
  • Expecting the play to converge. The mixed strategies of line L8 can cycle for ever; only the empirical distribution of line L10 approaches the set of correlated equilibria.
  • Using it alone against an adversary. The conditional rule has no guarantee for one player against arbitrary opponents (Section 4(d) of Hart and Mas-Colell).

Implementations

The Python code runs lines L1 to L10 for all players with exact rational regrets, so the correlated equilibrium gap of the empirical distribution is exact. It also has a class for the unconditional version in floating point, and a deterministic self-play with expected payoffs. The tests check the exact identity between the regrets and the correlated equilibrium inequalities of zTz_T on random games, the trace of the example, convergence on chicken and on the prisoner's dilemma with fixed seeds, the bound Δkt\Delta \sqrt{k t} against random adversaries at every round, and the coarse correlated equilibrium inequalities of the averaged self-play.

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
regret_matching.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regret-matching/. The authors are listed in prov/FJGSGJ.jsonl.
"""Regret matching in a repeated finite game.

regret_matching runs the procedure of Hart and Mas-Colell (2000) for all players at once: a
player who played j last switches to l with probability proportional to the positive part
of the conditional regret D_i(j, l), with an inertia constant mu. Its empirical distribution
of play converges almost surely to the set of correlated equilibria. The regrets are kept
exactly, in Fraction, so the correlated equilibrium gap of the empirical distribution is
known exactly.

RegretMatcher is the unconditional version: it plays each action with probability
proportional to its positive external regret. It is the learner that counterfactual regret
minimization uses, and its external regret after t rounds is at most delta sqrt(k t), where
delta is the payoff range and k the number of actions. It works in float.

The game is a pair (sizes, pay) as in the shared helper agtgame; players maximize.
"""

import math
from fractions import Fraction


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


def _draw(rng, p):
    """Draw an index from the distribution p (a list of Fraction that sums to 1)."""
    x = rng.random()
    acc = Fraction(0)
    for a, q in enumerate(p):
        acc += q
        if x < acc:
            return a
    return max(a for a, q in enumerate(p) if q > 0)


def payoff_range(game, i):
    """Return max_s u_i(s) - min_s u_i(s)."""
    vals = [u[i] for u in game[1].values()]
    return max(vals) - min(vals)


def regret_matching(game, T, rng, mu=None):
    """Play T rounds of conditional regret matching for every player.

    Return (z, D). z is the empirical distribution of the T profiles played, a dict from
    profiles to Fraction. D[i][j][l] is the exact sum over the rounds t with s_i^t = j of
    u_i(l, s_-i^t) - u_i(s^t); D[i][j][j] is 0.

    Precondition: T >= 1, and mu > (k_i - 1) delta_i for every player i, where delta_i is
    the payoff range of player i. The default mu is the smallest integer above all these
    bounds. rng is a random.Random. Cost: O(n k) payoff lookups and Fraction operations per
    round, where k is the largest number of strategies; O(n k^2) space for D, plus the
    support of z.
    """
    sizes, pay = game
    n = len(sizes)
    bounds = [(sizes[i] - 1) * payoff_range(game, i) for i in range(n)]
    mu = Fraction(math.floor(max(bounds)) + 1) if mu is None else Fraction(mu)
    if any(mu <= b for b in bounds):
        raise ValueError("mu must exceed (k_i - 1) times the payoff range of every player")
    if T < 1:
        raise ValueError("T must be at least 1")
    D = [[[Fraction(0)] * k for _ in range(k)] for k in sizes]  # @line L1
    s = tuple(rng.randrange(k) for k in sizes)  # @line L2
    counts = {}
    for t in range(1, T + 1):  # @line L3
        counts[s] = counts.get(s, 0) + 1
        nxt = []
        for i in range(n):  # @line L4
            k = sizes[i]
            j = s[i]  # @line L5
            here = pay[s][i]
            for l in range(k):
                if l != j:
                    D[i][j][l] += pay[_replace(s, i, l)][i] - here  # @line L6
            p = [max(D[i][j][l], Fraction(0)) / (t * mu) if l != j else Fraction(0) for l in range(k)]  # @line L7
            p[j] = 1 - sum(p, Fraction(0))  # @line L8
            nxt.append(_draw(rng, p))  # @line L9
        s = tuple(nxt)
    z = {prof: Fraction(c, T) for prof, c in counts.items()}  # @line L10
    return z, D


def ce_gap(D, T):
    """Return max(0, max_{i, j, l} D[i][j][l]) / T, the correlated equilibrium gap of z."""
    top = max((v for Di in D for row in Di for v in row), default=Fraction(0))
    return max(top, Fraction(0)) / T


class RegretMatcher:
    """Unconditional regret matching for one player with k actions (float).

    strategy() returns the current mixed strategy, proportional to the positive parts of
    the cumulative external regrets (uniform when all are at most 0). update(u) takes the
    payoff u[l] that each action l would have earned this round, and adds u[l] minus the
    expected payoff of the current strategy to the regret of l. Cost: O(k) per call.
    """

    def __init__(self, k):
        if k < 1:
            raise ValueError("k must be at least 1")
        self.regret = [0.0] * k

    def strategy(self):
        pos = [max(r, 0.0) for r in self.regret]
        total = sum(pos)
        if total <= 0.0:
            return [1.0 / len(pos)] * len(pos)
        return [r / total for r in pos]

    def update(self, u):
        p = self.strategy()
        value = sum(q * x for q, x in zip(p, u))
        for l, x in enumerate(u):
            self.regret[l] += x - value
        return value


def expected_self_play(game, T):
    """Let every player run RegretMatcher on expected payoffs for T rounds (deterministic).

    Return the list of the T mixed profiles played (lists of float). The uniform average of
    their product distributions is an epsilon-coarse correlated equilibrium with epsilon at
    most max_i delta_i sqrt(k_i / T). Cost: O(T n |S|) float operations.
    """
    sizes, pay = game
    n = len(sizes)
    fpay = {s: [float(v) for v in u] for s, u in pay.items()}
    learners = [RegretMatcher(k) for k in sizes]
    history = []
    for _ in range(T):
        sigma = [m.strategy() for m in learners]
        history.append(sigma)
        dev = [[0.0] * k for k in sizes]
        for s, u in fpay.items():
            for i in range(n):
                w = 1.0
                for k2, a in enumerate(s):
                    if k2 != i:
                        w *= sigma[k2][a]
                dev[i][s[i]] += w * u[i]
        for i in range(n):
            learners[i].update(dev[i])
    return history
test_regret_matching.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regret-matching/. The authors are listed in prov/FJGSGJ.jsonl.
"""Tests of conditional and unconditional regret matching."""

import math
import random
from fractions import Fraction

import pytest

from agtgame import from_bimatrix, is_coarse_correlated, is_correlated, profiles, random_game
from regret_matching import RegretMatcher, ce_gap, expected_self_play, payoff_range, regret_matching

F = Fraction
CHICKEN = from_bimatrix([[0, 7], [2, 6]], [[0, 2], [7, 6]])  # strategy 0 is D, 1 is C


def ce_terms(game, z):
    """Return the CE inequality terms sum_{s: s_i = j} z(s) (u_i(l, s_-i) - u_i(s)), from z only."""
    sizes, pay = game
    out = []
    for i, k in enumerate(sizes):
        rows = [[F(0)] * k for _ in range(k)]
        for s, q in z.items():
            for l in range(k):
                if l != s[i]:
                    rows[s[i]][l] += q * (pay[s[:i] + (l,) + s[i + 1:]][i] - pay[s][i])
        out.append(rows)
    return out


def test_identity_regrets_equal_ce_terms_on_random_games():
    rng = random.Random(9001)
    for _ in range(40):
        sizes = tuple(rng.randint(2, 3) for _ in range(rng.randint(2, 3)))
        game = random_game(rng, sizes, -4, 4)
        T = rng.randint(1, 120)
        z, D = regret_matching(game, T, rng)
        assert sum(z.values()) == 1 and all(q > 0 for q in z.values())
        terms = ce_terms(game, z)
        for i, k in enumerate(sizes):
            for j in range(k):
                for l in range(k):
                    assert terms[i][j][l] == D[i][j][l] / T
        gap = ce_gap(D, T)
        assert (gap == 0) == is_correlated(game, z)


def test_chicken_converges():
    for seed in (1, 2, 3):
        T = 1500
        z, D = regret_matching(CHICKEN, T, random.Random(seed))
        gap = ce_gap(D, T)
        assert gap <= F(1, 50)  # measured: below 1/300 for these seeds
        assert max(ce_terms(CHICKEN, z)[i][j][l] for i in range(2) for j in range(2) for l in range(2)) == gap


def test_prisoners_dilemma_reaches_defection():
    pd = from_bimatrix([[3, 0], [5, 1]], [[3, 5], [0, 1]])  # strategy 1 is defect
    for seed in (5, 6):
        z, _ = regret_matching(pd, 400, random.Random(seed))
        assert z.get((1, 1), 0) >= F(9, 10)


def test_page_trace_is_absorbing():
    # From (C, C) with mu = 8: one regret of 1 each, then (D, C) is never left.
    class Draws:
        def __init__(self, xs):
            self.xs = list(xs)

        def randrange(self, k):
            return 1

        def random(self):
            return self.xs.pop(0) if self.xs else 0.5

    z, D = regret_matching(CHICKEN, 4, Draws([0.05, 0.95]), mu=8)
    assert z == {(1, 1): F(1, 4), (0, 1): F(3, 4)}
    assert D[0][1][0] == 1 and D[0][0][1] == -3
    assert D[1][1][0] == 1 - 2 * 3
    assert ce_gap(D, 4) == F(1, 4)


def test_mu_must_be_large_enough():
    with pytest.raises(ValueError):
        regret_matching(CHICKEN, 10, random.Random(1), mu=7)
    with pytest.raises(ValueError):
        regret_matching(CHICKEN, 0, random.Random(1))
    assert payoff_range(CHICKEN, 0) == 7
    z, D = regret_matching(CHICKEN, 1, random.Random(1))
    assert len(z) == 1 and list(z.values()) == [1]


def test_unconditional_bound_against_adversary_every_round():
    rng = random.Random(31337)
    for _ in range(30):
        k = rng.randint(1, 5)
        lo, hi = -rng.randint(0, 3), rng.randint(1, 4)
        m = RegretMatcher(k)
        cum, got = [0.0] * k, 0.0
        for t in range(1, 401):
            u = [rng.uniform(lo, hi) if rng.random() < 0.7 else float(rng.choice((lo, hi))) for _ in range(k)]
            p = m.strategy()
            assert abs(sum(p) - 1.0) < 1e-12 and min(p) >= 0.0
            got += m.update(u)
            cum = [c + x for c, x in zip(cum, u)]
            assert max(cum) - got <= (hi - lo) * math.sqrt(k * t) + 1e-9


def test_expected_self_play_gives_cce():
    rng = random.Random(2718)
    for _ in range(6):
        sizes = tuple(rng.randint(2, 3) for _ in range(rng.randint(2, 3)))
        game = random_game(rng, sizes, 0, 5)
        T = 150
        hist = expected_self_play(game, T)
        n = len(sizes)
        eps_coef = max(float(payoff_range(game, i)) * math.sqrt(sizes[i]) for i in range(n))
        avg = {s: 0.0 for s in profiles(sizes)}
        for t, sigma in enumerate(hist, start=1):
            for s in avg:
                w = 1.0
                for i, a in enumerate(s):
                    w *= sigma[i][a]
                avg[s] += w
            if t % 25 == 0:
                # Check every CCE inequality of the average distribution directly.
                for i in range(n):
                    here = sum(q * float(game[1][s][i]) for s, q in avg.items()) / t
                    for b in range(sizes[i]):
                        dev = sum(q * float(game[1][s[:i] + (b,) + s[i + 1:]][i]) for s, q in avg.items()) / t
                        assert dev - here <= eps_coef / math.sqrt(t) + 1e-9


def test_rps_cce_but_not_ce_check():
    # The helper checks agree with the page claim: the uniform off-diagonal RPS distribution
    # is a CCE and not a CE, so external regret alone does not certify a CE.
    rps = from_bimatrix([[0, -1, 1], [1, 0, -1], [-1, 1, 0]], [[0, 1, -1], [-1, 0, 1], [1, -1, 0]])
    z = {(a, b): F(1, 6) for a in range(3) for b in range(3) if a != b}
    assert is_coarse_correlated(rps, z) and not is_correlated(rps, z)

History

Hannan (1957) and Blackwell (1956) gave the first procedures with no external regret. Foster and Vohra (1997) showed that players who best-respond to calibrated forecasts reach correlated equilibria. Hart and Mas-Colell (2000) found the simple regret matching rule, proved its convergence to correlated equilibria with Blackwell's approachability theorem as a guide, and gave the unconditional version. Zinkevich and coauthors (2007) used unconditional regret matching at each information set in counterfactual regret minimization, which became the basis of poker programs.

References

  1. Sergiu Hart and Andreu Mas-Colell, A simple adaptive procedure leading to correlated equilibrium, Econometrica 68(5) (2000), 1127-1150, Section 2, the procedure (2.2) with the inertia condition of footnote 5 and the Main Theorem (proof in Appendix 1); Section 3, the Proposition linking regrets and correlated epsilon-equilibria; Section 4(c), the unconditional procedure (4.2) and Theorem B; Section 4(d), the procedure (2.2) is not universally calibrated
  2. David Blackwell, An analog of the minimax theorem for vector payoffs, Pacific Journal of Mathematics 6(1) (1956), 1-8, the approachability theorem that Hart and Mas-Colell use in Section 3
  3. Nicolo Cesa-Bianchi and Gabor Lugosi, Prediction, Learning, and Games, Cambridge University Press, 2006, Chapter 2 (the polynomially weighted average forecaster, of which unconditional regret matching is the quadratic case) and Chapter 7 (internal regret and correlated equilibria)
  4. Tim Roughgarden, Twenty Lectures on Algorithmic Game Theory, Cambridge University Press, 2016, Lecture 18 (swap regret and correlated equilibria)

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