Module contents
Lesson 27 of 37Advanced 110 min

AlphaGo and AlphaGo Zero: search as a policy improvement operator

Follow AlphaGo's combination of policy and value networks with MCTS and AlphaGo Zero's single residual network trained through self-play. Interpret network-guided search as policy improvement through visit targets, approximate policy iteration, expert iteration, and regularized optimization.

After this lesson you can

  • Describe the 2016 AlphaGo pipeline and the roles of its networks and rollouts.
  • Explain why MCTS visits define an improved policy relative to the network prior.
  • Write the AlphaGo Zero loss and justify its π and z targets.
  • Relate AlphaGo Zero to approximate policy iteration and expert iteration.
  • Implement expert iteration in tic-tac-toe and verify convergence to perfect play.

Before you start

Search to teach a network

In Go, a position may offer hundreds of moves and a game may last hundreds of moves. Exploring every continuation is infeasible. Approximate evaluation cuts depth, and a policy proposing promising moves helps allocate search budget. Neither removes the problem: a network can be wrong and too small a search may miss its error.

In 2016 AlphaGo combined supervised learning from human games, self-play, and Monte Carlo search. AlphaGo Zero replaced those stages with a joint network trained from self-play, using game rules but no human games. Both combine fast network decisions with search spending more compute on the current position.

InteractiveAlphaGo networks and data
Supervised policy

Data: Human positions and moves

Objective: Move log-likelihood

In the system: Prior for each search branch.

BlockSupervised policy
Select a version and block to follow its data, objective, and role.

The 2016 pipeline

The original AlphaGo architecture had specialized components:

  • A supervised policy learned to predict human moves using log likelihood. It trained on 30 million positions from the KGS server and supplied the search prior.
  • A second policy, initialized from the first, improved through policy gradient and self-play outcomes. Its objective was to win, not necessarily reproduce a human move.
  • A value network was fitted by regression to outcomes of games generated by the improved policy. A fast pattern-based policy completed rollouts from leaves.
  • MCTS mixed value-network evaluation with those rollout outcomes. The system distributed asynchronous simulations; search was not a simple network forward pass.

Consecutive positions in a game are similar and share a final outcome. The paper observed overfitting when naively training value on complete games: it reported mean squared error 0.19 on training versus 0.37 on test. To reduce correlation it generated another 30 million positions, one per self-play game; that experiment reported errors 0.226 and 0.234. These are results for specific setups and datasets, not a generalization guarantee.

The value network estimates outcome under policies generating the data, not exact minimax value by definition. Search can correct errors by examining continuations, but can also inherit them. A leaf evaluation overvaluing a line may attract visits; more simulations help only if search and evaluations eventually provide useful information.

Prior and value serve different functions. A high prior makes an action examined earlier or more often; it is not an outcome prediction. Value evaluates a position from a specific perspective; it does not directly say which move produces that outcome. Combined search can reverse prior ordering as continuation evidence accumulates. But if an important action has zero probability and no other mechanism explores it, it can be excluded entirely. The legality mask removes impossible actions; it must not remove legal moves merely because their prior is small.

One network, two objectives

AlphaGo Zero’s joint policy–value network takes the board and produces fθ(s)=(pθ(⋅∣s),vθ(s))f_\theta(s)=(p_\theta(\cdot\mid s),v_\theta(s)). Its residual trunk shares a representation with two heads: one distributes probability over legal moves and the other predicts outcome from the current player’s perspective. The fast rollout policy, human-supervised stage, and separate value network are removed. The network still depends on rules to generate legal successors and score the end.

In a simulation, PUCT selects an edge of the form

a=arg⁡max⁡b[Q(s,b)+cpuctP(s,b)1+∑jN(s,j)1+N(s,b)].a=\arg\max_b\left[Q(s,b)+c_{\rm puct}P(s,b)\frac{\sqrt{1+\sum_jN(s,j)}}{1+N(s,b)}\right].

Here PP is the network prior, NN counts visits, and QQ averages backed-up evaluations from the perspective of the player choosing the edge. 11 under the root is this lesson’s initialization convention. At a nonterminal leaf the network supplies prior and value; at a terminal the actual outcome is used. Backing up across an edge in a zero-sum game flips the sign. A terminal worth −1-1 to the player who would move is worth +1+1 to the player who just won.

After MM simulations, the search policy uses visits:

πτ(a∣s)=N(s,a)1/τ∑bN(s,b)1/τ,τ>0.\pi_\tau(a\mid s)=\frac{N(s,a)^{1/\tau}}{\sum_bN(s,b)^{1/\tau}},\qquad \tau>0.

For τ=1\tau=1 counts are normalized; lower temperature concentrates the distribution. In the limit τ→0\tau\to0 an action with maximum count is chosen with an explicit tie rule. Illegal actions have zero probability. Without simulations the denominator is zero and alternative behavior must be defined, such as using the legal prior.

InteractiveSearch sharpens a policy
  • Prior
  • Temperature-scaled visits
  • Optimal minimax
1.00
Legal squares3, 6, 7, 8, 9
Visits94 / 1 / 3 / 1 / 1
Probability of winning now0.940
Compare an incorrect prior with PUCT visits and the minimax solution for a position.

The position is X X empty / O O empty / empty empty empty, with X to move. Five legal actions are squares 3, 6, 7, 8, and 9, numbered by row. Playing 3 wins immediately; 6 permits a draw with perfect response; the others lose against perfect play. The hand-assigned prior wrongly favors square 7. The figure runs PUCT at the root using exact minimax values of successors: a controlled depth-one example, not a trained network or real Go game. In full search QQ is estimated and can change.

More visits often yield a better-informed policy, but strict improvement is not guaranteed for every state, prior, and finite budget. An erroneous network, near-zero prior, biased value, ties, or small budget can reverse the comparison. Temperature changes how counts become targets; it does not change counts already obtained.

Distinguish three distributions. The prior comes from the network before search. The visit distribution summarizes where simulations were spent and, after temperature, can serve as a training target. Finally the executed action is a sample or maximum of that distribution, depending on phase and rule. Saving only that action discards information about alternatives that also received support. Fitting directly to visits does not turn proportions into exact win probabilities: they also reflect prior, exploration bonus, and search budget.

Self-play and policy iteration

In self-play, each position sts_t generates search distribution πt\pi_t. An action is played, the game continues, and final outcome ztz_t is assigned to that position from the player-to-move perspective. Training data contain triples (st,πt,zt)(s_t,\pi_t,z_t), not just the sampled move. In a zero-sum game, consecutive turns see the outcome with opposite signs.

The AlphaGo Zero loss for a position is

L(θ)=(z−vθ(s))2−∑a∈A(s)π(a∣s)log⁡pθ(a∣s)+c∥θ∥22.\mathcal L(\theta)=(z-v_\theta(s))^2-\sum_{a\in\mathcal A(s)}\pi(a\mid s)\log p_\theta(a\mid s)+c\|\theta\|_2^2.

The first term fits value to the observed winner and the second distills visit distribution. The legal mask applies before normalizing logits. Outcome zz is a noisy sample under self-play policies, not automatically minimax value. Bootstrapping from search value or mixtures can be studied, but is no longer the original equation’s objective. Changing value weight also changes the shared network’s tradeoff.

The analogy with policy iteration is useful: search acts as approximate improvement and self-play outcomes supply evaluation samples. Network fitting is an imperfect projection onto a limited family. Expert iteration, proposed by Anthony and colleagues, separates the searching expert from a learner that imitates and generalizes; as the learner improves, the next expert may improve. The loop can stall or cycle due to insufficient data, value bias, forgetting, or lack of opponent diversity.

Self-play agent strength is also relative to available opponents. Two policies may draw often against each other while sharing a weakness exploited by a third. To detect this, save previous versions and run a tournament with balanced turns and colors. The Zero version in the paper evaluated candidate networks against the best network and accepted those meeting the tournament criterion. This reduces risk of replacing a strong version with one worse against that opponent, but does not prove improvement against every opponent.

InteractiveAn expert iteration loop
  • Apprentice
  • Expert with search
30
3.0
Final apprentice0.884
Final expert1.000
Exact optimum1
Change expert compute and the learner’s representation limit.

This simulation uses one position with five fixed minimax values (1,0,−1,−1,−1)(1,0,-1,-1,-1). Depth-one search actually runs PUCT and produces counts; the learner updates logits by cross-entropy gradient and clips them to a configurable bound. Plotted strength is exact expected value under each distribution, not Elo, a Go-trained network, or an improvement guarantee. The bound illustrates that a learner unable to represent a highly concentrated policy may leave a gap from the expert.

The interpretation by Grill and colleagues relates PUCT to regularized policy optimization. For fixed search values, a full-support prior, and smoothed visit distribution, it studies a solution maximizing expected value minus a KL in direction KL(P∥y)\mathrm{KL}(P\|y). Effective regularization depends on visits. This interpretation has specific assumptions; it does not mean every finite search exactly solves that problem or estimated value is perfect.

Results and cost

In the three-day experiment described by the 2017 paper, AlphaGo Zero generated 4.9 million games with 1600 simulations per move and a 20-residual-block network. The work also studied a 40-block network trained for 40 days. Elo curves were estimated from games between versions under defined search controls; an isolated Elo figure is not universal outside that set and conditions.

The paper reports a 100–0 victory against AlphaGo Lee in the described match: Zero used one machine with four TPUs during play, while AlphaGo Lee used a distributed configuration with 48 TPUs. That inference figure does not describe total training cost. Game analysis showed the system rediscovered known patterns and also used different sequences; observing a known opening does not prove human-like reasoning or identify how it arose.

Lab: expert iteration in tic-tac-toe

Implement a game from scratch, a small NumPy network with policy and value heads, PUCT search, self-play, and training with square symmetries. State is always expressed from the player to move: applying a move swaps signs. Each value target changes sign according to turns separating the position from terminal. Policy targets retain full visit counts and illegal moves are masked.

Evaluation traverses all 4520 reachable nonterminal positions and computes the fraction of deterministic network decisions matching any minimax-optimal move. It also explores every opponent response from an empty board and shows the learner’s worst result playing first and second. Zero in both proves that deterministic policy does not lose from the start, but not that it is optimal at every possible position. A negative result reveals a counterexample, not just defeat against a chosen opponent.

The default quick run uses two iterations, three games per iteration, 25 simulations per move, and five updates per iteration. To explore further, set ORYON_QUICK=0 locally or change run parameters; use 20 iterations, 20 games, 100 simulations, and 80 updates per iteration. These are small budgets and do not guarantee convergence. Our run of that setup, seed 0, ended with 0.654 optimal decisions across 4520 states and worst result −1 playing both first and second: the learner can still lose. Do not confuse this failed check with perfect play.

The full run also evaluates the expert formed by the same network and 300 simulations per move, with deterministic tie-breaking and no noise. In the indicated test, worst result was 0 playing both first and second against all possible responses from the start: that expert plays perfectly from an empty board in the sense of guaranteeing at least a draw. With 100 simulations the same test found a loss when playing second. This does not prove learner convergence or optimal expert decisions at all 4520 positions; it shows what search adds under that budget and seed.

[ ]Self-play, PUCT, and minimax in NumPyBrowser
import os, math, json, time
from functools import lru_cache
import numpy as np

LINES=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
@lru_cache(None)
def outcome(s):
    for i,j,k in LINES:
        if s[i] and s[i]==s[j]==s[k]:return s[i]
    return 0 if 0 not in s else None

def move(s,a):
    if s[a]!=0 or outcome(s) is not None:raise ValueError('Jugada ilegal')
    b=list(s);b[a]=1;return tuple(-v for v in b)

@lru_cache(None)
def minimax(s):
    result=outcome(s)
    if result is not None:return result
    return max(-minimax(move(s,a)) for a in range(9) if s[a]==0)

@lru_cache(None)
def reachable():
    seen=set()
    def walk(s):
        if s in seen:return
        seen.add(s)
        if outcome(s) is None:
            for a in range(9):
                if s[a]==0:walk(move(s,a))
    walk((0,)*9)
    return tuple(s for s in seen if outcome(s) is None)

def softmax(logits,mask):
    x=np.where(mask,logits,-1e9);e=np.exp(x-x.max(axis=-1,keepdims=True))*mask
    return e/e.sum(axis=-1,keepdims=True)

class Net:
    def __init__(self,width,rng):
        self.rng=rng
        self.w1=rng.normal(0,1/math.sqrt(9),(9,width));self.b1=np.zeros(width)
        self.wp=rng.normal(0,.08,(width,9));self.bp=np.zeros(9)
        self.wv=rng.normal(0,.08,(width,1));self.bv=np.zeros(1)
    def forward(self,x):
        x=np.asarray(x,dtype=float);h=np.tanh(x@self.w1+self.b1)
        p=softmax(h@self.wp+self.bp,x==0);v=np.tanh(h@self.wv+self.bv)
        return h,p,v
    def learn(self,x,target,z,lr=.03,value_weight=1.,decay=1e-4):
        h,p,v=self.forward(x);n=len(x);z=z[:,None]
        lp=-np.mean(np.sum(target*np.log(np.maximum(p,1e-12)),axis=1));lv=np.mean((v-z)**2)
        dp=(p-target)/n;dv=value_weight*2*(v-z)*(1-v*v)/n
        gp=h.T@dp+2*decay*self.wp;gbp=dp.sum(0)
        gv=h.T@dv+2*decay*self.wv;gbv=dv.sum(0)
        dh=(dp@self.wp.T+dv@self.wv.T)*(1-h*h)
        g1=x.T@dh+2*decay*self.w1;gb1=dh.sum(0)
        for w,g in ((self.w1,g1),(self.b1,gb1),(self.wp,gp),(self.bp,gbp),(self.wv,gv),(self.bv,gbv)):w-=lr*g
        return float(lp),float(lv)

class Node:
    def __init__(self,s,net):
        self.s=s;self.end=outcome(s);self.n=np.zeros(9,dtype=int);self.w=np.zeros(9);self.children={}
        if self.end is None:
            _,p,v=net.forward(np.array(s)[None,:]);self.prior=p[0];self.value=float(v[0,0])
        else:self.prior=np.zeros(9);self.value=float(self.end)
    def visit(self,net,c):
        q=np.divide(self.w,self.n,out=np.zeros(9),where=self.n>0)
        score=q+c*self.prior*math.sqrt(1+self.n.sum())/(1+self.n)
        score=np.where(np.array(self.s)==0,score,-np.inf);a=int(np.argmax(score))
        if a not in self.children:
            child=Node(move(self.s,a),net);self.children[a]=child;v=child.value
        else:
            child=self.children[a];v=child.value if child.end is not None else child.visit(net,c)
        v=-v;self.n[a]+=1;self.w[a]+=v
        return v

def search(s,net,simulations,c=1.5,noise=0.,rng=None):
    root=Node(s,net)
    if root.end is not None:raise ValueError('Posición terminal')
    legal=np.flatnonzero(np.array(s)==0)
    if noise:
        root.prior[legal]=(1-noise)*root.prior[legal]+noise*rng.dirichlet(np.full(len(legal),.3))
    for _ in range(simulations):root.visit(net,c)
    return root.n.copy()

def visit_policy(n,tau):
    if tau<=0:
        p=np.zeros(9);p[int(np.argmax(n))]=1.;return p
    x=n.astype(float)**(1/tau)
    if not x.sum():raise ValueError('No hay visitas')
    return x/x.sum()

def symmetries(s,p):
    x=np.array(s).reshape(3,3);y=np.array(p).reshape(3,3)
    for k in range(4):
        for flip in (False,True):
            a=np.rot90(x,k);b=np.rot90(y,k)
            if flip:a=np.fliplr(a);b=np.fliplr(b)
            yield a.ravel().copy(),b.ravel().copy()

def selfplay(net,sims,rng):
    s=(0,)*9;trajectory=[];turn=0
    while outcome(s) is None:
        n=search(s,net,sims,noise=.25,rng=rng);target=visit_policy(n,1.)
        trajectory.append((s,target,turn));p=target if turn<4 else visit_policy(n,0.)
        a=int(rng.choice(9,p=p));s=move(s,a);turn+=1
    result=outcome(s)
    records=[]
    for state,pi,t in trajectory:
        z=result*((-1)**(turn-t))
        for x,y in symmetries(state,pi):records.append((x,y,z))
    return records,result

def evaluate(net):
    states=reachable();x=np.asarray(states);_,p,_=net.forward(x);acts=p.argmax(axis=1)
    optimal=np.array([-minimax(move(s,int(a)))==minimax(s) for s,a in zip(states,acts)])
    choice={s:int(a) for s,a in zip(states,acts)}
    @lru_cache(None)
    def worst(s,own_turn):
        end=outcome(s)
        if end is not None:return end if own_turn else -end
        if own_turn:return worst(move(s,choice[s]),False)
        return min(worst(move(s,a),True) for a in range(9) if s[a]==0)
    root=(0,)*9
    return {'optimal_fraction':float(optimal.mean()),'states':len(states),
            'worst_first':worst(root,True),'worst_second':worst(root,False)}

def evaluate_expert(net,simulations):
    # Se exploran todas las respuestas del rival desde el tablero vacío.
    @lru_cache(None)
    def worst(s,own_turn):
        end=outcome(s)
        if end is not None:return end if own_turn else -end
        if own_turn:
            a=int(np.argmax(search(s,net,simulations)))
            return worst(move(s,a),False)
        return min(worst(move(s,a),True) for a in range(9) if s[a]==0)
    root=(0,)*9
    return {'simulations':simulations,'worst_first':worst(root,True),
            'worst_second':worst(root,False),'states_explored':worst.cache_info().currsize}

def run(width=64,sims=50,iterations=20,games=20,updates=80,seed=0):
    rng=np.random.default_rng(seed);net=Net(width,rng);buffer=[];history=[]
    for it in range(iterations+1):
        if it:
            for _ in range(games):buffer.extend(selfplay(net,sims,rng)[0])
            for _ in range(updates):
                idx=rng.integers(0,len(buffer),size=min(128,len(buffer)))
                batch=[buffer[j] for j in idx]
                x=np.stack([r[0] for r in batch]);target=np.stack([r[1] for r in batch]);z=np.array([r[2] for r in batch])
                lp,lv=net.learn(x,target,z)
        measure=evaluate(net);measure.update(iteration=it,examples=len(buffer))
        if it:measure.update(policy_loss=lp,value_loss=lv)
        history.append(measure);print('iteración',it,measure,flush=True)
    return net,buffer,history

if __name__=='__main__':
    quick=os.getenv('ORYON_QUICK','1')=='1'
    net,buffer,history=run(width=int(os.getenv('ORYON_WIDTH','64')),sims=int(os.getenv('ORYON_SIMS','25' if quick else '100')),
        iterations=int(os.getenv('ORYON_ITERATIONS','2' if quick else '20')),games=int(os.getenv('ORYON_GAMES','3' if quick else '20')),
        updates=int(os.getenv('ORYON_UPDATES','5' if quick else '80')),seed=int(os.getenv('ORYON_SEED','0')))
    print('Resultado',history[-1])
    if not quick:print('Experto desde el inicio',evaluate_expert(net,300))

Replay retains every position augmented by eight symmetries, including repeated symmetric positions. Exhaustive evaluation does not participate in fitting. Games are generated with root Dirichlet noise for exploration and, after initial turns, the most visited action is used; training uses the visit distribution without additional noise. Training does not automatically select a best network by tournament. A fuller experiment could retain previous opponents and periodically evaluate against a best version, with multiple seeds and budgets.

Lab: separate the losses

The next cell takes actual positions, distributions, and outcomes generated above. It compares the same network state with different temperatures and value weights; it does not retrain. Regularization includes weight matrices, not biases. Alternative temperature raises saved frequencies to 1/τ1/\tau and renormalizes; without positive counts that transformation would be invalid.

[ ]Temperature and value weightBrowser
# Usa partidas reales producidas por la celda anterior, sin consultar minimax.
if not buffer:raise RuntimeError('Ejecuta primero el autojuego')
subset=buffer[:min(128,len(buffer))]
x=np.stack([row[0] for row in subset]);pi=np.stack([row[1] for row in subset]);z=np.array([row[2] for row in subset])
_,p,v=net.forward(x)
regularizer=sum(float(np.sum(w*w)) for w in (net.w1,net.wp,net.wv))
for tau in (1.,.5):
    target=pi**(1/tau);target/=target.sum(axis=1,keepdims=True)
    policy_loss=float(-np.sum(target*np.log(np.maximum(p,1e-12)),axis=1).mean())
    value_loss=float(np.mean((v[:,0]-z)**2))
    for weight in (.25,1.,2.):
        total=policy_loss+weight*value_loss+1e-4*regularizer
        print('temperatura',tau,'peso valor',weight,'política',policy_loss,'valor',value_loss,'total',total)
print('Se comparan los mismos parámetros y estados; cambiar τ no reentrena la red.')

Cross-entropy can change even with identical network weights because the target distribution changes. Giving value more weight changes its contribution, but that comparison alone does not establish how learning would change; that requires training from the same conditions and evaluating new policies. Separating policy loss, value loss, and regularization helps interpret the total.

Exercises

ProofConcentration of visits
Prove: At a node with finitely many actions, each action value is exact and fixed after its first visit; every action prior is positive and c > 0. Prove PUCT asymptotically concentrates visits on optimal actions.
0
Use index Q(a)+c P(a)√(1+N)/(1+N(a)) and finite initial values. There may be multiple optima.

Step 1 of 4. Why can an action with positive prior not remain visited only finitely many times?

NumericTemperature and counts
A root has visits (8, 2, 0). What probability does the first action receive with τ = 0.5?
QuizThe value target
Why does the original loss use the game’s final outcome z for the value head?
QuizFrom AlphaGo to Zero
Which original AlphaGo components disappear in AlphaGo Zero?
CodeLoss with legal mask
Implement alphazero_loss(policy_logits, value, target_pi, target_z, legal_mask, params, c). Policy inputs are N×K matrices; value and target_z are N-vectors. The Boolean mask identifies legal moves. Return the per-example mean cross-entropy plus squared error and add c times the sum of squares of all arrays in params. Require one legal move per row and normalized, nonnegative policy targets with no illegal mass. Use stable softmax over legal moves.
import numpy as np
def alphazero_loss(policy_logits, value, target_pi, target_z, legal_mask, params, c):
  pass
Shift+Enter to run
Key idea
Search can create better-informed policy targets than the prior, but quality depends on evaluations, budget, and data; self-play should be checked against independent opponents and solutions.