Game theory for learning agents: equilibria, dynamics and CFR
Study normal-form and Markov games, Nash and correlated equilibria, the minimax theorem, learning dynamics, and their relationship with equilibria. Extend to imperfect-information extensive-form games and counterfactual regret minimization in poker.
After this lesson you can
- Calculate Nash equilibria in small games and solve zero-sum games by linear programming.
- Prove that no-regret self-play dynamics converge on average to a zero-sum equilibrium.
- Formulate Markov games and apply minimax-Q.
- Implement CFR and CFR+ in Kuhn and Leduc poker and measure exploitability.
- Explain why subgame search fails under imperfect information.
Before you start
When the environment also decides
In an MDP, the transition belongs to the environment; in a game, another agent may choose it strategically. A defense that defeats a fixed attacker can be vulnerable to another that has observed its rule. It is therefore useful to ask how much an adaptive opponent can gain, as well as measuring wins against a particular set of opponents.
A finite normal-form game defines players, actions, and payoffs . A mixed strategy is a distribution over actions. An action is strictly dominated if another gives a higher payoff against every opponent choice; eliminating it preserves equilibria but does not itself say what happens in a game without dominance. In a Nash equilibrium no unilateral deviation improves expected payoff. The definition does not guarantee social welfare, uniqueness, or convergence of a learning dynamic.
In two-player zero-sum games, and the minimax theorem equates the value guaranteed by the maximizer with the worst value the minimizer can impose:
The maximizer can solve the linear program subject to , , and . The dual program gives the minimizer’s strategy and the same value. This equality is a property of zero-sum games, not a method for declaring a single value in any general game.
The horizontal coordinate is the probability of the first row and the vertical coordinate that of the first column. The difference between the expected payoffs of the two rows is linear in ; depending on its sign, the best response uses one pure row, while zero allows any mixture. The same logic applies to for the other player. The interior point of matching pennies is . A line or region of indifference requires examining the full set, not counting marked points as if they were all equilibria.
A correlated equilibrium allows a mediator to sample a joint recommendation. Each player must prefer to obey it, conditioned on their own recommendation. A joint distribution can be correlated even though each individual action is random. Low external regret generally leads to a coarse correlated equilibrium of joint frequencies; correlated equilibrium requires controlling deviations conditioned on the recommendation, such as internal regret. Hart and Mas-Colell study a regret-matching dynamic for the latter case.
Consider a coordination game with row payoffs and column payoffs . A mediator simultaneously recommends the first action to both players with probability and the second to both with probability . On receiving a recommendation, each player knows the other received the corresponding one; changing their action unilaterally reduces their payoff to zero. The diagonal distribution is therefore a correlated equilibrium and gives expected payoff to each player. Multiplying its uniform marginals as if decisions were independent also introduces the two uncoordinated outcomes: this changes the distribution and no longer evaluates the same device.
The difference between external and internal regret is visible in repeated recommendations. The former compares what happened with always playing one fixed action, independently of the recommendation. The latter allows comparison with a rule such as “when recommended left, play right; otherwise obey.” A deviation depending on the signal can be profitable even when no fixed action is. To verify a finite correlated equilibrium, check for each player and each action pair that the sum of joint probability times the advantage of obeying over replacing with is nonnegative. Checking only the aggregate average payoff is insufficient.
Regret and average strategies
At each round , the maximizing player uses and the minimizing player uses . Their accumulated external regrets are
Adding and dividing by gives the best-response gap of the average strategies :
If each average regret is at most , the gap is at most . Each unilateral gain is also bounded by that gap. This describes the average, not necessarily the last strategy: iterations can keep cycling, as in variants of rock-paper-scissors. In general-sum games, the players’ marginal averages do not automatically inherit the same Nash guarantee.
A zero gap characterizes a minimax pair in the zero-sum game. If the gap is small, both deviations are controlled simultaneously: the best row response does not exceed by much the worst result columns can impose on the average row strategy. By contrast, observing an average reward close to the game value is not enough. A pair of strategies can produce that payoff because two errors cancel, while an opponent detecting one of them gains substantially. Calculating best responses turns this intuition into a verifiable measure.
Fictitious play responds optimally to the opponent’s historical frequency. Hedge updates weights exponentially using accumulated payoffs, while regret matching uses the positive part of each action’s regret and falls back to a uniform distribution if all are nonpositive. The rate and update method matter; plotting one trajectory does not prove convergence of all dynamics. In particular, empirical correlated equilibrium and convergence of averages in zero-sum games are different claims.
The figure uses an antisymmetric matrix, so it is zero-sum even when changing the payoff of a matchup. The gap of the averages sums the maximizer’s best gain against the opponent average and the worst loss against the other average. The red point is the next strategy, while orange averages the strategies played. A trajectory visually approaching the center does not replace calculating that gap; nor does it guarantee convergence for another step size.
From states to private histories
A Markov game has state , joint actions , transition , and reward per player. In the fully observed zero-sum case, minimax-Q updates a table toward , where is the minimax value of the continuation matrix. The matrix game is solved again at each state. In general-sum games there may be multiple equilibria with different values; a selection rule is part of the algorithm and does not automatically inherit zero-sum guarantees. Littman introduced Markov games in this context.
With tabular and discounting, an observed transition produces temporal error and update . To obtain , solve the game with matrix ; do not simply take the maximum of all entries, since the opponent chooses its own action. At a terminal state the continuation value is zero. Tabular convergence requires appropriate coverage, learning-rate, and stationarity conditions; neural networks and changing opponents do not automatically satisfy these assumptions.
Nash-Q replaces the minimax value with expected payoffs at an equilibrium of the estimated stage game. In general-sum games, however, the same state can have several equilibria with different payoffs, and selection can jump when estimates change slightly. An explicit tie-breaking procedure avoids implementation ambiguity but does not by itself prove stability. It is also necessary to specify whether players observe the same state and act simultaneously or sequentially: each contract defines a different problem.
An extensive-form game represents actions in a tree with chance nodes, decisions, and terminal payoffs. An information set groups histories a player cannot distinguish: the same action distribution must be used for all of them. In poker, one cannot solve a supposed subgame by observing only the public board as if private cards and reach probabilities were known. Earlier bets change the distribution of the opponent’s hands; isolating the tree without preserving ranges and continuation values can create an exploitable strategy.
Counterfactual regret and CFR
Counterfactual regret minimization (CFR) assigns regret per action to each information set. To calculate it, each history is weighted by the probability of chance and the other players’ actions, excluding the reach probability of the player being updated. This exclusion asks what would have happened if that player had reached the set, even when their current policy almost never visits it. Regret matching turns positive regrets into probabilities; accumulated strategies are weighted by the player’s own reach probability.
Suppose in one iteration the counterfactual value of checking is and of betting is , while the current mixture assigns probability to checking. The mixture value is : regret increments are for checking and for betting, before applying the corresponding counterfactual weight. If those were the only positive accumulated regrets, regret matching would choose to bet. This does not prove betting is optimal in the full game: the example represents one set and one iteration against the opponent’s current strategy.
The average strategy for a set is not an unweighted arithmetic average of its probabilities. When the player almost never reaches that set under one iteration, that iteration should contribute little to the realization strategy there. CFR weights by the player’s own reach; chance probabilities constant within one set can cancel on normalization, as in the tabular examples. Opponent reach serves another role: it weights value differences that generate regret. Confusing these weights can produce apparently plausible results that fail when measuring a best response.
In finite two-player zero-sum games with perfect recall, counterfactual regret controls global regret and the average strategy converges toward equilibrium in the best-response-gap sense. Zinkevich and colleagues develop the idea. CFR+ clips negative accumulated regret to zero at each update and often uses iteration-weighted averages; different variants alternate players or delay averaging, so the version must be specified. MCCFR samples parts of the tree to reduce cost per iteration, introducing sampling noise.
Exploitability is measured using best responses that respect information sets, without allowing opponents to see hidden cards. NashConv sums both players’ unilateral deviation gains. In a two-player zero-sum game, a common convention calls NashConv divided by two exploitability; always state the convention used. In Kuhn, the first player has equilibrium value under the following rules. A strategy can beat a beginner and still have large NashConv.
The text map shows the initial player’s first information set. With J, betting is a bluff; the algorithm decides its frequency in interaction with the opponent’s responses. Regrets in that set do not describe the whole strategy and the NashConv curve can rise on individual iterations. Switching between CFR and CFR+ resets the run to avoid mixing accumulators.
Poker and search at scale
Libratus, DeepStack, and Pluribus combined approximate game solving with search adapted to imperfect information; their rules, budgets, and numbers of players differ. DeepStack uses continual reasoning with approximate continuation values; Pluribus studies multiplayer poker, where two-player zero-sum guarantees do not directly carry over. Deep CFR approximates regret values with networks, and NFSP combines response learning with an average policy. No observed match result substitutes for an exploitability bound.
Lab: CFR from scratch
Before moving to the tree, let us solve a matrix and measure the gap of average strategies. The first cell uses scipy.optimize.linprog, which solves a linear program; the dynamics are implemented explicitly. The rock-paper-scissors matrix has zero value and uniform equilibrium. The external regret measurement does not claim to prove convergence to an ordinary correlated equilibrium in general-sum games.
import numpy as np
from scipy.optimize import linprog
def minimax(A):
A=np.asarray(A,float);m,n=A.shape
result=linprog(np.r_[np.zeros(m),-1.],A_ub=np.c_[-A.T,np.ones(n)],b_ub=np.zeros(n),
A_eq=[np.r_[np.ones(m),0.]],b_eq=[1.],bounds=[(0,None)]*m+[(None,None)],method='highs')
if not result.success:raise RuntimeError(result.message)
return result.x[:m],result.x[-1]
def dynamics(A,method,T,eta=.1):
A=np.asarray(A,float);m,n=A.shape
x=np.ones(m)/m;y=np.ones(n)/n
if m==n==3:x=np.array([.7,.2,.1]);y=np.array([.2,.6,.2])
sx=np.zeros(m);sy=np.zeros(n);gx=np.zeros(m);gy=np.zeros(n)
regret_x=np.zeros(m);regret_y=np.zeros(n)
def softmax(z):
z=z-z.max();p=np.exp(z);return p/p.sum()
def matched(r):
z=np.maximum(r,0);return z/z.sum() if z.sum()>0 else np.ones(len(z))/len(z)
for t in range(1,T+1):
px=A@y;py=x@A;u=x@px;sx+=x;sy+=y
regret_x+=px-u;regret_y+=u-py
gx+=px;gy-=py
if method=='hedge':x=softmax(eta*gx);y=softmax(eta*gy)
elif method=='regret':x=matched(regret_x);y=matched(regret_y)
elif method=='ficticio':
x=np.eye(m)[np.argmax(A@(sy/t))];y=np.eye(n)[np.argmin((sx/t)@A)]
else:raise ValueError(method)
bx,by=sx/T,sy/T
return {'media_filas':bx,'media_columnas':by,'brecha':float(np.max(A@by)-np.min(bx@A)),
'regret_filas':float(max(regret_x)/T),'regret_columnas':float(max(regret_y)/T)}A=np.array([[0,-1,1],[1,0,-1],[-1,1,0]],float)
x,v=minimax(A);print('LP',x.round(4),v)
for method in ('ficticio','hedge','regret'):
print(method,dynamics(A,method,10000))Kuhn uses three ordered cards, two players, and a one-chip bet. Each player contributes one initial chip; two checks end at showdown, a bet can be folded to or called, and a check followed by a bet gives the initial player one final decision. The code enumerates all deals and updates regrets simultaneously. CFR+ clips at the end of each iteration and weights the average by iteration number; this is a particular variant, not an implementation identical to every library.
For example, if the initial player has J and bets, the opponent can fold and concede one net chip, or call and win two net chips with Q or K. A bluff can be useful because folding is possible, but always betting with J would be easy to exploit. With K the reverse holds: as the highest card, calling an opponent’s bet never loses in this tie-free game. These observations alone do not fix all equilibrium probabilities: the opponent adjusts responses to the complete mixture of hands.
There are six equally likely ordered deals. For the first player, “I have J and nobody has acted yet” groups two histories, depending on whether the other player received Q or K. A best response choosing differently in those histories would be looking at a hidden card. The best-response code enumerates one action per information set and evaluates all 64 possible pure strategies for each player. Searching pure strategies suffices for a best response to a fixed opponent strategy in this finite game; a mixture cannot exceed the maximum of its components.
"""CFR simultáneo en póker de Kuhn con respuesta óptima por información."""
import itertools
import numpy as np
CARDS=(0,1,2)
DEALS=list(itertools.permutations(CARDS,2))
INFO=[(player,card,h) for player,hs in ((0,('', 'pb')),(1,('p','b'))) for card in CARDS for h in hs]
def terminal(cards,h):
if h in ('pp','bc','pbc'):
magnitude=1 if h=='pp' else 2
return magnitude if cards[0]>cards[1] else -magnitude
if h=='bf':return 1
if h=='pbf':return -1
return None
def player(h):return len(h)%2
def actions(h):return ('p','b') if h in ('','p') else ('f','c')
def matched(r):
p=np.maximum(r,0);return p/p.sum() if p.sum()>0 else np.array([.5,.5])
class CFR:
def __init__(self,plus=False):
self.plus=plus;self.regrets={k:np.zeros(2) for k in INFO};self.sums={k:np.zeros(2) for k in INFO};self.iteration=0
def step(self):
delta={k:np.zeros(2) for k in INFO};average={k:np.zeros(2) for k in INFO}
def traverse(cards,h,reach):
outcome=terminal(cards,h)
if outcome is not None:return float(outcome)
p=player(h);key=(p,cards[p],h);strategy=matched(self.regrets[key]);a=actions(h);values=np.zeros(2)
for i,move in enumerate(a):
new=list(reach);new[p]*=strategy[i];values[i]=traverse(cards,h+move,new)
node=values@strategy;delta[key]+=(1 if p==0 else -1)*(values-node)*reach[1-p]/6
average[key]+=strategy*reach[p]/6
return node
for cards in DEALS:traverse(cards,'',[1.,1.])
self.iteration+=1
for k in INFO:
self.regrets[k]+=delta[k]
if self.plus:self.regrets[k]=np.maximum(self.regrets[k],0)
self.sums[k]+=(self.iteration if self.plus else 1)*average[k]
def strategy(self):return {k:(v/v.sum() if v.sum()>0 else np.array([.5,.5])) for k,v in self.sums.items()}
def value(strategy,overrides=None):
overrides=overrides or {}
def rec(cards,h):
end=terminal(cards,h)
if end is not None:return float(end)
p=player(h);key=(p,cards[p],h);sigma=overrides.get(key,strategy[key]);return sum(sigma[i]*rec(cards,h+a) for i,a in enumerate(actions(h)))
return sum(rec(c,'') for c in DEALS)/6
def nashconv(strategy):
base=value(strategy);improvements=[]
for p in (0,1):
keys=[k for k in INFO if k[0]==p];best=-np.inf
for bits in itertools.product((0,1),repeat=len(keys)):
overrides={k:np.eye(2)[bit] for k,bit in zip(keys,bits)};val=value(strategy,overrides);best=max(best,val if p==0 else -val)
improvements.append(best-(base if p==0 else -base))
return sum(improvements)kuhn=CFR();kuhn_plus=CFR(plus=True)
for _ in range(1000):
kuhn.step();kuhn_plus.step()
for label,algorithm in (("CFR",kuhn),("CFR+",kuhn_plus)):
print(label,"valor",value(algorithm.strategy()),"NashConv",nashconv(algorithm.strategy()))Leduc has six cards, two per rank, one public card, and two rounds. Each player contributes one chip; raises are two chips in the first round and four in the second, with at most two raises per round. A pair with the public card beats an unpaired hand; if there are no pairs, the highest private rank wins. Strategies group cards of equal rank; all physical cards are enumerated for chance. The best response groups histories by information and weights them by chance and opponent reach, not by the opponent’s private cards.
The deal is enumerated as 120 ordered triples of distinct physical cards: two private and one public. The public card is determined in advance for easier enumeration, but before the second round it is not part of the information key and the policy cannot use it. This distinction is essential: knowing the future in the simulator does not authorize the agent to observe it. In each round, “call” with no pending bet is a check; the round ends when both check or a pending bet is called. If someone folds, the other obtains the folding player’s net contribution.
The best-response algorithm traverses information sets from end to start. For a given player, it calculates each history’s counterfactual reach using chance and opponent probabilities. It then chooses one action maximizing the weighted sum of values across all histories in the set. Repeat for both players and subtract their best-response values expressed from the first player’s perspective. The result is NashConv. This implementation’s 288 information keys exploit suit symmetry; there are fewer than in a representation distinguishing equivalent physical cards.
"""Leduc de dos jugadores: antes 1, subidas 2/4, máximo dos por ronda."""
import itertools,time
import numpy as np
DEALS=list(itertools.permutations(range(6),3))
def legal(raises,to_call):return (('f','c','r') if raises<2 else ('f','c')) if to_call else (('c','r') if raises<2 else ('c',))
def advance(cards,board,hists,roundno,p,stakes,raises,action):
cost=list(stakes);need=max(cost)-cost[p];hist=list(hists);hist[roundno]+=action
if action=='f':return ('terminal', -cost[0] if p==0 else cost[1])
if action=='r':
cost[p]+=need+(2 if roundno==0 else 4)
return ('node',tuple(hist),roundno,1-p,tuple(cost),raises+1)
cost[p]+=need
prev=hists[roundno]
if need>0 or (len(prev)>0 and prev[-1]=='c'):
if roundno==0:return ('node',tuple(hist),1,0,tuple(cost),0)
rank=[cards[0]//2,cards[1]//2];public=board//2
strengths=[(int(r==public),r) for r in rank]
return ('terminal',cost[1] if strengths[0]>strengths[1] else -cost[0] if strengths[0]<strengths[1] else 0)
return ('node',tuple(hist),roundno,1-p,tuple(cost),raises)
def key(cards,board,hists,roundno,p):return (p,cards[p]//2,board//2 if roundno else -1,hists[0],hists[1])
def build_tree():
keys={}; nodes=[];roots=[]
def visit(cards,board,hists,roundno,p,stakes,raises):
k=key(cards,board,hists,roundno,p);acts=legal(raises,max(stakes)-stakes[p]);
if k not in keys:keys[k]=(len(keys),acts)
ident,existing=keys[k];assert existing==acts
children=[]
for action in acts:
result=advance(cards,board,hists,roundno,p,stakes,raises,action)
children.append(('t',result[1]) if result[0]=='terminal' else ('n',visit(cards,board,*result[1:])))
i=len(nodes);nodes.append((ident,p,children));return i
for a,b,board in DEALS:roots.append(visit((a,b),board,('',''),0,0,(1,1),0))
return keys,nodes,roots
class LeducCFR:
def __init__(self,plus=False):
self.keys,self.nodes,self.roots=build_tree();self.plus=plus;self.regrets=[np.zeros(len(v[1])) for v in self.keys.values()];self.sums=[np.zeros(len(v[1])) for v in self.keys.values()];self.iteration=0
def step(self):
strategies=[]
for r in self.regrets:
pos=np.maximum(r,0);strategies.append(pos/pos.sum() if pos.sum()>0 else np.ones(len(r))/len(r))
d=[np.zeros_like(r) for r in self.regrets];avg=[np.zeros_like(r) for r in self.regrets]
def walk(i,r0,r1):
key,p,children=self.nodes[i];s=strategies[key];v=np.empty(len(children))
for j,(kind,child) in enumerate(children):v[j]=child if kind=='t' else walk(child,r0*s[j] if p==0 else r0,r1*s[j] if p==1 else r1)
total=v@s;d[key]+=(1 if p==0 else -1)*(v-total)*(r1 if p==0 else r0)/len(self.roots);avg[key]+=s*(r0 if p==0 else r1)/len(self.roots)
return total
for root in self.roots:walk(root,1.,1.)
self.iteration+=1
for i in range(len(d)):
self.regrets[i]+=d[i]
if self.plus:self.regrets[i]=np.maximum(self.regrets[i],0)
self.sums[i]+=(self.iteration if self.plus else 1)*avg[i]
def strategy(self):
return {k:(self.sums[i]/self.sums[i].sum() if self.sums[i].sum() else np.ones(len(acts))/len(acts)) for k,(i,acts) in self.keys.items()}
def best_response_value(game,strategy,responder):
# Pesos contrafactuales: azar y rival, sin probabilidades propias.
sig=[strategy[k] for k in game.keys];weights=np.zeros(len(game.nodes));groups={i:[] for i in range(len(game.keys))}
def mark(i,w):
ident,p,children=game.nodes[i];weights[i]+=w
for j,(kind,child) in enumerate(children):
if kind=='n':mark(child,w*(sig[ident][j] if p!=responder else 1.))
for root in game.roots:mark(root,1/len(game.roots))
for i,(ident,p,_) in enumerate(game.nodes):
if p==responder:groups[ident].append(i)
choices={};memo={}
def val(i):
if i in memo:return memo[i]
ident,p,children=game.nodes[i];v=np.array([child if kind=='t' else val(child) for kind,child in children])
result=v[choices[ident]] if p==responder else v@sig[ident]
memo[i]=result;return result
ordered=sorted(((len(k[3])+len(k[4]),ident) for k,(ident,_) in game.keys.items() if k[0]==responder),reverse=True)
for _,ident in ordered:
acts=np.zeros(len(sig[ident]))
for node in groups[ident]:
for j,(kind,child) in enumerate(game.nodes[node][2]):acts[j]+=weights[node]*(child if kind=='t' else val(child))
choices[ident]=int(np.argmax(acts) if responder==0 else np.argmin(acts))
memo.clear();return sum(val(root) for root in game.roots)/len(game.roots)
def nashconv(game,strategy):
return best_response_value(game,strategy,0)-best_response_value(game,strategy,1)leduc=LeducCFR();leduc_plus=LeducCFR(plus=True)
print("Nodos",len(leduc.nodes),"conjuntos de información",len(leduc.keys))for _ in range(20):
leduc.step();leduc_plus.step()
print("iteraciones",leduc.iteration)for _ in range(20):
leduc.step();leduc_plus.step()
print("iteraciones",leduc.iteration)for _ in range(20):
leduc.step();leduc_plus.step()
print("iteraciones",leduc.iteration)for _ in range(20):
leduc.step();leduc_plus.step()
print("iteraciones",leduc.iteration)for _ in range(20):
leduc.step();leduc_plus.step()
print("iteraciones",leduc.iteration)for label,algorithm in (("CFR",leduc),("CFR+",leduc_plus)):
print(label,"NashConv",nashconv(algorithm,algorithm.strategy()))In our Pyodide run, the LP returns the uniform distribution and zero value. After 10,000 iterations, average-strategy gaps are 0.01881 for fictitious play, 0.01630 for Hedge, and 0.01953 for regret matching. These three numbers do not imply a general ranking of methods. In Kuhn, after 1000 iterations, CFR gives value −0.055557 and NashConv 0.014538, while CFR+ gives −0.055597 and 0.005656. In Leduc, after 100 iterations, NashConv values are 0.346069 and 0.088024 respectively. These values belong to the specified implementations and averages.
The next two local cells recreate their algorithms so they can run independently of the browser. Install OpenSpiel 2.0.2, NumPy, and SciPy in your local environment. For each game, CFR and CFR+ are run and NashConv is calculated with the custom best response and with OpenSpiel on the same average policy; this compares evaluators, not two supposedly identical training sequences.
"""CFR simultáneo en póker de Kuhn con respuesta óptima por información."""
import itertools
import numpy as np
CARDS=(0,1,2)
DEALS=list(itertools.permutations(CARDS,2))
INFO=[(player,card,h) for player,hs in ((0,('', 'pb')),(1,('p','b'))) for card in CARDS for h in hs]
def terminal(cards,h):
if h in ('pp','bc','pbc'):
magnitude=1 if h=='pp' else 2
return magnitude if cards[0]>cards[1] else -magnitude
if h=='bf':return 1
if h=='pbf':return -1
return None
def player(h):return len(h)%2
def actions(h):return ('p','b') if h in ('','p') else ('f','c')
def matched(r):
p=np.maximum(r,0);return p/p.sum() if p.sum()>0 else np.array([.5,.5])
class CFR:
def __init__(self,plus=False):
self.plus=plus;self.regrets={k:np.zeros(2) for k in INFO};self.sums={k:np.zeros(2) for k in INFO};self.iteration=0
def step(self):
delta={k:np.zeros(2) for k in INFO};average={k:np.zeros(2) for k in INFO}
def traverse(cards,h,reach):
outcome=terminal(cards,h)
if outcome is not None:return float(outcome)
p=player(h);key=(p,cards[p],h);strategy=matched(self.regrets[key]);a=actions(h);values=np.zeros(2)
for i,move in enumerate(a):
new=list(reach);new[p]*=strategy[i];values[i]=traverse(cards,h+move,new)
node=values@strategy;delta[key]+=(1 if p==0 else -1)*(values-node)*reach[1-p]/6
average[key]+=strategy*reach[p]/6
return node
for cards in DEALS:traverse(cards,'',[1.,1.])
self.iteration+=1
for k in INFO:
self.regrets[k]+=delta[k]
if self.plus:self.regrets[k]=np.maximum(self.regrets[k],0)
self.sums[k]+=(self.iteration if self.plus else 1)*average[k]
def strategy(self):return {k:(v/v.sum() if v.sum()>0 else np.array([.5,.5])) for k,v in self.sums.items()}
def value(strategy,overrides=None):
overrides=overrides or {}
def rec(cards,h):
end=terminal(cards,h)
if end is not None:return float(end)
p=player(h);key=(p,cards[p],h);sigma=overrides.get(key,strategy[key]);return sum(sigma[i]*rec(cards,h+a) for i,a in enumerate(actions(h)))
return sum(rec(c,'') for c in DEALS)/6
def nashconv(strategy):
base=value(strategy);improvements=[]
for p in (0,1):
keys=[k for k in INFO if k[0]==p];best=-np.inf
for bits in itertools.product((0,1),repeat=len(keys)):
overrides={k:np.eye(2)[bit] for k,bit in zip(keys,bits)};val=value(strategy,overrides);best=max(best,val if p==0 else -val)
improvements.append(best-(base if p==0 else -base))
return sum(improvements)
import pyspiel
from open_spiel.python import policy
from open_spiel.python.algorithms import exploitability
class KuhnPolicy(policy.Policy):
def __init__(self,game,strategies):super().__init__(game,[0,1]);self.strategies=strategies
def action_probabilities(self,state,player_id=None):
p=state.current_player();info=state.information_state_string(p);card=int(info[0]);h=info[1:];h=h.replace('pb','pb')
v=self.strategies[(p,card,h)];return {0:float(v[0]),1:float(v[1])}
game=pyspiel.load_game('kuhn_poker')
for plus in (False,True):
c=CFR(plus)
for _ in range(1000):c.step()
s=c.strategy();p=KuhnPolicy(game,s);a=nashconv(s);b=exploitability.nash_conv(game,p);print('CFR+',plus,'own',a,'OpenSpiel',b,'difference',abs(a-b));assert abs(a-b)<1e-10
npm run lab and open the connection link."""Leduc de dos jugadores: antes 1, subidas 2/4, máximo dos por ronda."""
import itertools,time
import numpy as np
DEALS=list(itertools.permutations(range(6),3))
def legal(raises,to_call):return (('f','c','r') if raises<2 else ('f','c')) if to_call else (('c','r') if raises<2 else ('c',))
def advance(cards,board,hists,roundno,p,stakes,raises,action):
cost=list(stakes);need=max(cost)-cost[p];hist=list(hists);hist[roundno]+=action
if action=='f':return ('terminal', -cost[0] if p==0 else cost[1])
if action=='r':
cost[p]+=need+(2 if roundno==0 else 4)
return ('node',tuple(hist),roundno,1-p,tuple(cost),raises+1)
cost[p]+=need
prev=hists[roundno]
if need>0 or (len(prev)>0 and prev[-1]=='c'):
if roundno==0:return ('node',tuple(hist),1,0,tuple(cost),0)
rank=[cards[0]//2,cards[1]//2];public=board//2
strengths=[(int(r==public),r) for r in rank]
return ('terminal',cost[1] if strengths[0]>strengths[1] else -cost[0] if strengths[0]<strengths[1] else 0)
return ('node',tuple(hist),roundno,1-p,tuple(cost),raises)
def key(cards,board,hists,roundno,p):return (p,cards[p]//2,board//2 if roundno else -1,hists[0],hists[1])
def build_tree():
keys={}; nodes=[];roots=[]
def visit(cards,board,hists,roundno,p,stakes,raises):
k=key(cards,board,hists,roundno,p);acts=legal(raises,max(stakes)-stakes[p]);
if k not in keys:keys[k]=(len(keys),acts)
ident,existing=keys[k];assert existing==acts
children=[]
for action in acts:
result=advance(cards,board,hists,roundno,p,stakes,raises,action)
children.append(('t',result[1]) if result[0]=='terminal' else ('n',visit(cards,board,*result[1:])))
i=len(nodes);nodes.append((ident,p,children));return i
for a,b,board in DEALS:roots.append(visit((a,b),board,('',''),0,0,(1,1),0))
return keys,nodes,roots
class LeducCFR:
def __init__(self,plus=False):
self.keys,self.nodes,self.roots=build_tree();self.plus=plus;self.regrets=[np.zeros(len(v[1])) for v in self.keys.values()];self.sums=[np.zeros(len(v[1])) for v in self.keys.values()];self.iteration=0
def step(self):
strategies=[]
for r in self.regrets:
pos=np.maximum(r,0);strategies.append(pos/pos.sum() if pos.sum()>0 else np.ones(len(r))/len(r))
d=[np.zeros_like(r) for r in self.regrets];avg=[np.zeros_like(r) for r in self.regrets]
def walk(i,r0,r1):
key,p,children=self.nodes[i];s=strategies[key];v=np.empty(len(children))
for j,(kind,child) in enumerate(children):v[j]=child if kind=='t' else walk(child,r0*s[j] if p==0 else r0,r1*s[j] if p==1 else r1)
total=v@s;d[key]+=(1 if p==0 else -1)*(v-total)*(r1 if p==0 else r0)/len(self.roots);avg[key]+=s*(r0 if p==0 else r1)/len(self.roots)
return total
for root in self.roots:walk(root,1.,1.)
self.iteration+=1
for i in range(len(d)):
self.regrets[i]+=d[i]
if self.plus:self.regrets[i]=np.maximum(self.regrets[i],0)
self.sums[i]+=(self.iteration if self.plus else 1)*avg[i]
def strategy(self):
return {k:(self.sums[i]/self.sums[i].sum() if self.sums[i].sum() else np.ones(len(acts))/len(acts)) for k,(i,acts) in self.keys.items()}
def best_response_value(game,strategy,responder):
# Pesos contrafactuales: azar y rival, sin probabilidades propias.
sig=[strategy[k] for k in game.keys];weights=np.zeros(len(game.nodes));groups={i:[] for i in range(len(game.keys))}
def mark(i,w):
ident,p,children=game.nodes[i];weights[i]+=w
for j,(kind,child) in enumerate(children):
if kind=='n':mark(child,w*(sig[ident][j] if p!=responder else 1.))
for root in game.roots:mark(root,1/len(game.roots))
for i,(ident,p,_) in enumerate(game.nodes):
if p==responder:groups[ident].append(i)
choices={};memo={}
def val(i):
if i in memo:return memo[i]
ident,p,children=game.nodes[i];v=np.array([child if kind=='t' else val(child) for kind,child in children])
result=v[choices[ident]] if p==responder else v@sig[ident]
memo[i]=result;return result
ordered=sorted(((len(k[3])+len(k[4]),ident) for k,(ident,_) in game.keys.items() if k[0]==responder),reverse=True)
for _,ident in ordered:
acts=np.zeros(len(sig[ident]))
for node in groups[ident]:
for j,(kind,child) in enumerate(game.nodes[node][2]):acts[j]+=weights[node]*(child if kind=='t' else val(child))
choices[ident]=int(np.argmax(acts) if responder==0 else np.argmin(acts))
memo.clear();return sum(val(root) for root in game.roots)/len(game.roots)
def nashconv(game,strategy):
return best_response_value(game,strategy,0)-best_response_value(game,strategy,1)
import re
import pyspiel
from open_spiel.python import policy
from open_spiel.python.algorithms import exploitability
class LeducPolicy(policy.Policy):
def __init__(self,game,strategies,keys):super().__init__(game,[0,1]);self.strategies=strategies;self.keys=keys
def action_probabilities(self,state,player_id=None):
p=state.current_player();info=state.information_state_string(p);private=int(re.search(r'\[Private: (\d+)\]',info).group(1));public=re.search(r'\[Public: (\d+)\]',info)
def hist(round):
match=re.search(r'\[Round'+str(round)+r': ([0-9 ]*)\]',info);return ''.join({'0':'f','1':'c','2':'r'}[x] for x in match.group(1).split())
k=(p,private//2,int(public.group(1))//2 if public else -1,hist(1),hist(2));v=self.strategies[k];acts=self.keys[k][1];ids={'f':0,'c':1,'r':2};return {ids[a]:float(v[i]) for i,a in enumerate(acts)}
game=pyspiel.load_game('leduc_poker')
for plus in (False,True):
c=LeducCFR(plus)
for _ in range(25):c.step()
strategy=c.strategy()
own_score=nashconv(c,strategy)
reference=exploitability.nash_conv(game,LeducPolicy(game,strategy,c.keys))
print('CFR+',plus,'propio',own_score,'OpenSpiel',reference,'error',abs(own_score-reference))
npm run lab and open the connection link.To check the calculation, custom strategies were locally compared with OpenSpiel 2.0.2 best responses: at 25 Leduc iterations they agree to 5 × 10⁻¹⁶, and in Kuhn at 1000 iterations to 5 × 10⁻¹⁷. In addition, all legal actions and terminal payoffs in Leduc were compared at 4320 decision nodes and 5880 terminals. OpenSpiel distinguishes physical cards in its information states; the custom policy treats the two cards of one rank alike. The comparison respects that symmetry when translating policies, and does not mean the implementations necessarily perform the same updates or have equal cost.
Exercises
Step 1 of 3. What results from adding both regrets?
regret_matching_plus(regret, delta) and cfr_iteration(root, regrets, sums, iteration). The tree uses dictionaries: a terminal has value (player 0 payoff); chance has chance with a list of pairs (probabilidad, hijo) (probability, child); a decision has player, info, and children. The regrets and sums dictionaries contain lists as long as the actions of each set. During the iteration use regrets from the start, accumulate deltas weighted by chance and the other player’s reach, sum strategies weighted by chance, own reach, and iteration, and only at the end clip accumulated regrets to zero. Return the tree value for player 0 and modify both dictionaries.def regret_matching_plus(regret, delta):
pass
def cfr_iteration(root, regrets, sums, iteration):
pass