AlphaZero from scratch: self-play, batched MCTS and training on the local GPU
Build AlphaZero for Connect Four at local-machine scale: implement the game, training search, multiprocess actors and learner with batched RTX 4060 inference, a symmetry-augmented buffer, and Elo and perfect-solver evaluation. Examine realistic throughput budgets and debugging methods.
After this lesson you can
- Implement complete Connect Four AlphaZero with multiprocess self-play and batched GPU evaluation.
- Choose Dirichlet noise, temperature, and buffer size on principled grounds.
- Measure pipeline throughput and remove inference bottlenecks.
- Evaluate strength using Bradley–Terry Elo and a perfect solver.
- Debug AlphaZero using test positions, loss curves, and opening diversity.
Before you start
- 22Policy-value networkSearch as a policy improvement operatorSelf-playAlphaGo Zero lossExpert iterationRobust aggregate metrics
- 10Parallel MCTS and virtual lossPUCT selection with priors
- 09Threads, processes and the GILJIT compilation with Numba
- 20Bradley-Terry model
- 21Mixed-precision training
- 00Automatic mixed precision in PyTorch
A small end-to-end system
AlphaZero combines self-play, search, and training a network sharing representation between policy and value. This lesson builds a small Connect Four version. The game retains gravity and alternating turns; the network runs on available GPU and actors generate games in separate processes. It is a reproducible experiment, not a reproduction of published systems’ budget or strength.
AlphaGo Zero evaluated candidates against a best network and used Go symmetries. Later AlphaZero work studied more continuous updating and different games; not all Go symmetries are legal in chess or shogi. In Connect Four horizontal reflection is valid, but rotating the board changes gravity’s direction.
The agent uses a lab-generated checkpoint: seed 0, two rounds, four games, and eight simulations per self-play move. The figure uses 30 simulations per response without noise; do not expect a strong opponent from such a short test. Blue pieces are yours and orange are the agent’s. The figure’s solver activates only with six or fewer spaces to bound browser computation. Exact value and network value refer to the position before the agent’s move, from its perspective.
Board, perspective, and exploration
A 7-column by 6-row board fits in two integers. The code reserves seven bits per column, one a sentinel; this prevents shifts across columns from confusing a diagonal or row. A mask marks all pieces and the other integer marks those of the player to move. After a move the mask updates and perspective swaps. Four-in-a-row detection uses vertical, horizontal, and diagonal shifts. The implementation was checked against an independent array over 200 games; that does not replace a formal proof for all positions.
Network input has two planes, one per player from the current turn. This lab’s network uses a small residual trunk with dense layers and two heads, not a large convolutional ResNet. Illegal actions are excluded before softmax. A terminal result is stored from the player who would move; backing up one level in a zero-sum game flips its sign.
This convention allows the same network for both colors. If the current player places a piece and wins, the successor is represented from the next player with terminal value −1; the parent flips sign and records +1 for the winning move. A draw is zero for both. Replay targets must apply the same perspective change to the final outcome. A useful test is a position with three aligned pieces and a legal square completing four: backed-up value for that move should favor the choosing player.
The sentinel bit belongs to the representation, not playable squares. Each column’s actual top bit is checked before placing another piece. Horizontal reflection swaps first and seventh columns, second and sixth, and so on; it must also reflect the visit vector. Retaining unreflected policy labels would teach the network to favor the wrong column. Value, expressed from the current player, does not change under reflection.
Root Dirichlet noise mixes network prior with sample :
It applies once to the root of self-play search, only over legal actions. It is removed for evaluation. Small concentration gives more extreme samples; large concentration approaches a uniform distribution. The symmetric sample’s expectation is uniform, so the expectation of is , not necessarily the original prior.
The example uses a fixed seven-move prior and 500 reproducible samples per seed. Mean entropy describes dispersion of those mixtures; it is not entropy of the mean or a strength measurement. Choice of depends on action count and mixture: no universal value exists. Seeds for distinct processes should differ to avoid duplicated trajectories.
Visit distribution guides training. At the start of each game code samples from visits; later it uses the most visited action. The target retains the full distribution. The chosen move’s subtree is reused and previous counts remain; a new root receives a fresh noise mixture only for that move’s simulations. The example does not implement resignation: every game ends with four in a row or a full board.
Actors, batches, and limits
In the self-play pipeline, processes maintain independent trees and send leaves to a process owning the network. The server batches pending requests, runs one forward pass, and returns each result to its actor. Batched inference can amortize GPU overhead, but gathering a very large batch can increase waiting and memory.
The lab permits one outstanding request per actor and each actor plays one game at a time. Actual batch size therefore cannot exceed actor count; no two simulations run simultaneously on the same tree. Virtual loss helps when workers share a tree and might choose the same leaf before evaluation, but is unnecessary and unimplemented here. Learning occurs between self-play rounds, so all actors in one round use the same checkpoint. Queues and process startup also take time.
Maximum batch size is a cap, not a promise that many leaves arrive in time. With only two requests in flight, a limit of 256 still yields batches of one or two. Increasing concurrency requires more independent trees or requests and measuring coordination cost. The server waits briefly to group requests; waiting longer may fill the GPU better while delaying actors needing a response to continue. A useful measurement records batch count, mean size, and end-to-end time.
A system with concurrent training must decide when to replace the server model and ensure a batch does not accidentally mix two parameter versions. Round-based execution avoids that race at the cost of stopping self-play during updates. Production would also require queue limits, process supervision, and failure recovery; the example stops actors if one fails but does not reconstruct an interrupted round.
This figure is a hypothetical model, not a measurement. It assumes 36 moves per game, eight cores, 0.25 ms CPU per leaf, and ms inference for batch . Throughput is limited by the smallest of CPU, GPU, and concurrency capacities. The figure allows multiple simultaneous games per actor as a design assumption; the implementation below keeps one. It excludes queues, startup, transfer, training, and storage costs.
In a real short run with two actors, two games per round, and eight simulations, the first round took approximately 13.30 s self-play and the second 11.99 s, with mean batch sizes 1.77 and 1.70. The test computer had an RTX 3060; these are not RTX 4060 figures or a weekend-strength prediction. Four games cannot estimate stable performance. Measure round time, batch distribution, and memory on your machine and compare the full budget before extrapolating.
Train and evaluate
The bounded-window buffer retains positions, visits, and outcomes. Symmetry augmentation reflects the board horizontally and reverses column probability order. Loss combines policy cross-entropy and value squared error; Adam uses weight regularization. The program saves the initial checkpoint and one per round, plus measured losses and times. Small loss does not guarantee greater strength: it may reflect repeated data, easy targets, or self-play that finds no counterexample.
The report also saves first-column counts, their empirical entropy, and mean entropy of visit targets. These differ: the first summarizes chosen root actions and the second distributions across many states. With only two games per round, opening diversity is a very noisy diagnostic. A policy can distribute visits among bad actions and have high entropy; diversity should accompany results against opponents and tactical checks, not replace them.
A checkpoint saves a model snapshot, not all accumulated experience state. This example saves weights and round metadata; exact training resumption would also require optimizer, buffer, and random generator states. The lab creates a new optimizer each round, a simplification resetting its moments. That choice and window size affect results and must be held constant when comparing runs. Neither mixed precision nor an optimized inference server is used.
Evaluation uses paired random openings: both checkpoints play each opening once with each color assignment. Score is 1 per win and 0.5 per draw. Under a Bradley–Terry logistic model, expected score and Elo difference relate as
If all games are won or lost, the unregularized estimate is infinite. Here half a point per side is added before converting score to Elo; draws use fractional score as an approximation, not an explicit draw model. Whole opening pairs are resampled for bootstrap. If all bootstrap samples are identical, code declares the interval degenerate rather than presenting informative uncertainty.
Figure data come from four games with two paired openings: the final checkpoint scored three points versus one. Smoothed difference was approximately 147 Elo and pair-bootstrap interval 0 to 382 Elo. Two pairs are too few for a general conclusion; the interval applies only to the final checkpoint. The initial point is zero by definition because the checkpoint is compared with itself, not from an additional tournament. Lines connect those two points and do not represent intermediate measurements. The time axis includes self-play and training in the recorded run.
For a second check, an exact solver explores all continuations from positions with six spaces remaining and returns win, draw, or loss under perfect play. The lab sample chooses moves that do not end the game before reaching those positions, so it is biased and not representative of ordinary games. In the short test, the checkpoint chose an optimal action in all five sampled positions. Five late positions do not certify agent strength or solve the initial board.
If several actions have the same exact value, all are optimal for this measure. In particular, when all lose under perfect play, choosing any counts as optimal although defeat is inevitable. The metric does not distinguish winning sooner from later or losing later from sooner. A solver returning distance to the end could rank those alternatives, but would answer a finer question than win, draw, or loss. General strength estimation needs positions at different depths and external opponents, plus sampling intervals.
Paired openings reduce some color imbalance but do not make games within a pair independent. They are therefore resampled together. In such a small sample bootstrap can yield a wide or even degenerate range; repeating deterministic games from the same board does not create independent observations either. Record openings, seeds, and color assignment, and increase pair count before comparing close checkpoints.
Lab: self-play, batching, and checkpoints
Install PyTorch and NumPy locally. With ORYON_QUICK=1 the program uses two actors, one game per actor and round, eight simulations, two rounds, and ten updates per round. With ORYON_QUICK=0 it uses 20 rounds, 16 games per actor, 100 simulations, and 100 updates per round. The second budget has not been run here. Variable ORYON_C4_OUT selects output folder and ORYON_C4_SEED seed. CUDA limits process-allocatable memory to at most 7 GiB; effective value and time depend on the machine.
The cell writes a local program and executes it as a separate process. This lets Windows spawn mode import actor functions from a real file. Do not change the file while running. Self-play time includes process startup and queues; inference measurement includes copying results to CPU. Checkpoints are saved with metadata and weights.
from pathlib import Path
import subprocess, sys, os
script = Path('az_connect4.py').resolve()
script.write_text(r'''import json, math, os, queue, random, sys, time, traceback
from collections import deque
from pathlib import Path
import multiprocessing as mp
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
WIDTH,HEIGHT=7,6
BOTTOM=[1<<(7*c) for c in range(WIDTH)]
TOP=[1<<(7*c+5) for c in range(WIDTH)]
FULL=sum(((1<<HEIGHT)-1)<<(7*c) for c in range(WIDTH))
def four(bits):
for shift in (1,7,6,8):
x=bits&(bits>>shift)
if x&(x>>(2*shift)):return True
return False
def legal(mask):return [c for c in range(WIDTH) if not mask&TOP[c]]
def move(player,mask,c):
if c not in legal(mask):raise ValueError('Columna llena')
player ^= mask
mask |= mask+BOTTOM[c]
return player,mask
def end(player,mask):
if four(player^mask):return -1.
return 0. if mask==FULL else None
def planes(player,mask):
other=player^mask
return np.array([[(player>>(7*c+r))&1 for r in range(HEIGHT) for c in range(WIDTH)],
[(other>>(7*c+r))&1 for r in range(HEIGHT) for c in range(WIDTH)]],np.float32).reshape(2,HEIGHT,WIDTH)
def mirror(bits):
return sum(((bits>>(7*c))&127)<<(7*(WIDTH-1-c)) for c in range(WIDTH))
class Residual(nn.Module):
def __init__(self,width):
super().__init__();self.a=nn.Linear(width,width);self.b=nn.Linear(width,width)
def forward(self,x):return F.relu(x+self.b(F.relu(self.a(x))))
class Network(nn.Module):
def __init__(self,width=64,blocks=2):
super().__init__();self.entry=nn.Linear(84,width)
self.blocks=nn.ModuleList([Residual(width) for _ in range(blocks)])
self.policy=nn.Linear(width,7);self.value=nn.Linear(width,1)
def forward(self,x):
x=F.relu(self.entry(x.flatten(1)))
for block in self.blocks:x=block(x)
return self.policy(x),torch.tanh(self.value(x)).squeeze(-1)
class Node:
def __init__(self,player,mask):
self.player=player;self.mask=mask;self.n=np.zeros(7,np.int32);self.w=np.zeros(7,np.float64)
self.prior=None;self.children={};self.result=end(player,mask)
def expand(node,infer):
if node.result is not None:return node.result
node.prior,value=infer(node.player,node.mask)
return value
def search(root,sims,infer,rng=None,noise=.0,c=1.5):
if root.result is not None:raise ValueError('Posición terminal')
if root.prior is None:expand(root,infer)
priors=root.prior.copy();actions=legal(root.mask)
if noise:
priors[actions]=(1-noise)*priors[actions]+noise*rng.dirichlet(np.full(len(actions),.3))
for _ in range(sims):
node=root;path=[]
while True:
if node.result is not None:v=node.result;break
if node.prior is None:v=expand(node,infer);break
prior=priors if node is root else node.prior
q=np.divide(node.w,node.n,out=np.zeros(7),where=node.n>0)
score=q+c*prior*np.sqrt(1+node.n.sum())/(1+node.n)
valid=np.zeros(7,bool);valid[legal(node.mask)]=True
a=int(np.argmax(np.where(valid,score,-np.inf)));path.append((node,a))
if a not in node.children:
p,m=move(node.player,node.mask,a);node.children[a]=Node(p,m)
node=node.children[a]
for parent,a in reversed(path):
v=-v;parent.n[a]+=1;parent.w[a]+=v
return root.n.copy()
def actor(worker,games,sims,out,inbox,seed):
try:
rng=np.random.default_rng(seed)
def infer(p,m):
out.put(('eval',worker,p,m));prior,value=inbox.get()
return np.asarray(prior),float(value)
for game in range(games):
root=Node(0,0);trajectory=[];turn=0;opening=None
while root.result is None:
counts=search(root,sims,infer,rng,.25)
pi=counts/counts.sum();trajectory.append((root.player,root.mask,pi,turn))
a=int(rng.choice(7,p=pi)) if turn<8 else int(np.argmax(counts))
if turn==0:opening=a
if a not in root.children:
p,m=move(root.player,root.mask,a);root.children[a]=Node(p,m)
root=root.children[a];turn+=1
examples=[]
for p,m,pi,t in trajectory:
z=root.result*((-1)**(turn-t))
examples.append((p,m,pi.tolist(),z))
out.put(('game',worker,examples,turn,opening))
out.put(('done',worker))
except BaseException:
out.put(('error',worker,traceback.format_exc()))
def selfplay(model,device,workers,games,sims,seed,batch_limit=16):
ctx=mp.get_context('spawn');out=ctx.Queue();inboxes=[ctx.Queue() for _ in range(workers)]
procs=[ctx.Process(target=actor,args=(i,games,sims,out,inboxes[i],seed+10007*i)) for i in range(workers)]
for p in procs:p.start()
started=time.perf_counter();done=0;records=[];batches=[];openings=[];inference_seconds=0.
try:
while done<workers:
try:item=out.get(timeout=2.)
except queue.Empty:
if any(p.exitcode not in (None,0) for p in procs):raise RuntimeError('Falló un actor')
continue
pending=[item]
if item[0]=='eval':
deadline=time.perf_counter()+.005
while len(pending)<batch_limit:
try:pending.append(out.get(timeout=max(0.,deadline-time.perf_counter())))
except queue.Empty:break
evals=[]
for item in pending:
if item[0]=='eval':evals.append(item)
elif item[0]=='game':records.extend(item[2]);openings.append(item[4])
elif item[0]=='done':done+=1
elif item[0]=='error':raise RuntimeError(item[2])
if evals:
x=np.stack([planes(e[2],e[3]) for e in evals]);mask=np.zeros((len(evals),7),bool)
for i,e in enumerate(evals):mask[i,legal(e[3])]=True
t=time.perf_counter()
with torch.no_grad():
logits,value=model(torch.as_tensor(x,device=device))
prob=F.softmax(logits.masked_fill(~torch.as_tensor(mask,device=device),-1e9),-1)
probs=prob.cpu().numpy();values=value.cpu().numpy()
inference_seconds+=time.perf_counter()-t;batches.append(len(evals))
for i,e in enumerate(evals):inboxes[e[1]].put((probs[i].tolist(),float(values[i])))
for p in procs:p.join(timeout=10)
if any(p.exitcode!=0 for p in procs):raise RuntimeError('Actor no terminó correctamente')
finally:
for p in procs:
if p.is_alive():p.terminate()
for p in procs:p.join()
elapsed=time.perf_counter()-started
counts=np.bincount(openings,minlength=7);prob=counts/counts.sum()
entropy=float(-sum(x*math.log(x) for x in prob if x))
target_entropy=float(np.mean([-sum(x*math.log(x) for x in row[2] if x) for row in records]))
return records,{'games':workers*games,'positions':len(records),'seconds':elapsed,
'games_per_hour':workers*games*3600/elapsed,'inference_seconds':inference_seconds,
'mean_batch':float(np.mean(batches)),'max_batch':max(batches),'batches':len(batches),
'opening_counts':counts.tolist(),'opening_entropy':entropy,'target_entropy':target_entropy}
def train(model,device,replay,steps,rng,batch_size=64):
optimizer=torch.optim.Adam(model.parameters(),lr=1e-3,weight_decay=1e-4)
losses=[]
for _ in range(steps):
idx=rng.integers(len(replay),size=min(batch_size,len(replay)));batch=[replay[int(i)] for i in idx]
states=[];targets=[];values=[];masks=[]
for p,m,pi,z in batch:
if rng.random()<.5:p,m,pi=mirror(p),mirror(m),pi[::-1]
states.append(planes(p,m));targets.append(pi);values.append(z)
ok=np.zeros(7,bool);ok[legal(m)]=True;masks.append(ok)
x=torch.tensor(np.stack(states),device=device);pi=torch.tensor(np.asarray(targets),device=device,dtype=torch.float32)
z=torch.tensor(values,device=device,dtype=torch.float32);valid=torch.tensor(np.array(masks),device=device)
logits,v=model(x);logp=F.log_softmax(logits.masked_fill(~valid,-1e9),-1)
policy=-(pi*logp).sum(-1).mean();value=F.mse_loss(v,z);loss=policy+value
optimizer.zero_grad();loss.backward();optimizer.step()
losses.append((float(policy.detach()),float(value.detach())))
return {'policy_loss':losses[-1][0],'value_loss':losses[-1][1],'updates':steps}
def save(model,path,metadata):
torch.save({'state_dict':model.state_dict(),'width':64,'blocks':2,'metadata':metadata},path)
def main():
quick=os.getenv('ORYON_QUICK','1')=='1';root=Path(os.getenv('ORYON_C4_OUT','oryon-c4'));root.mkdir(parents=True,exist_ok=True)
seed=int(os.getenv('ORYON_C4_SEED','0'));random.seed(seed);np.random.seed(seed);torch.manual_seed(seed);rng=np.random.default_rng(seed)
torch.set_num_threads(1);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type=='cuda':
torch.cuda.manual_seed_all(seed);total=torch.cuda.get_device_properties(0).total_memory
torch.cuda.set_per_process_memory_fraction(min(1.,7*1024**3/total));torch.cuda.reset_peak_memory_stats()
model=Network().to(device);save(model,root/'c4-initial.pt',{'round':0,'seed':seed})
workers=2;games=1 if quick else 16;sims=8 if quick else 100;rounds=2 if quick else 20;steps=10 if quick else 100
replay=deque(maxlen=20000);history=[];start=time.perf_counter()
for i in range(1,rounds+1):
model.eval();records,timing=selfplay(model,device,workers,games,sims,seed+100000*i);replay.extend(records)
model.train();losses=train(model,device,replay,steps,rng)
row={'round':i,**timing,**losses,'replay_size':len(replay),'total_seconds':time.perf_counter()-start}
history.append(row);save(model,root/f'c4-round{i}.pt',{'round':i,'seed':seed,'quick':quick})
print('ronda',row,flush=True)
report={'seed':seed,'quick':quick,'device':str(device),'torch':torch.__version__,'numpy':np.__version__,
'workers':workers,'games_per_actor':games,'simulations':sims,'rounds':rounds,
'peak_cuda_gib':torch.cuda.max_memory_allocated()/1024**3 if device.type=='cuda' else None,'history':history}
(root/'training.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
print('Guardado',root,report)
if __name__=='__main__':
mp.freeze_support();main()''',encoding='utf-8')
result=subprocess.run([sys.executable,str(script)],capture_output=True,text=True,encoding='utf-8',errors='replace',env={**os.environ,'PYTHONIOENCODING':'utf-8'})
print(result.stdout)
if result.returncode: raise RuntimeError(result.stderr[-3000:])npm run lab and open the connection link.Lab: tournament and exact solver
The next cell loads checkpoints generated above. Quick mode plays four games in two opening pairs, performs 1000 pair resamples, and evaluates five positions with six spaces remaining. Full mode uses 40 games and 30 positions; that budget has not been run. Exact recursion is feasible here due to the remaining-space limit, but does not aim to solve from the empty board in practical time.
from pathlib import Path
import subprocess, sys, os
script = Path('c4_eval.py').resolve()
script.write_text(r'''import json, os, time
from functools import lru_cache
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
from az_connect4 import Network,Node,search,move,end,planes,legal,four
@lru_cache(maxsize=None)
def exact(player,mask):
terminal=end(player,mask)
if terminal is not None:return int(terminal)
return max(-exact(*move(player,mask,a)) for a in legal(mask))
def scores(player,mask):return {a:-exact(*move(player,mask,a)) for a in legal(mask)}
def sample_late(rng,n,remaining=6):
found=[];attempts=0
while len(found)<n and attempts<20000:
attempts+=1;p=m=0
for _ in range(42-remaining):
candidates=[a for a in legal(m) if end(*move(p,m,a)) is None]
if not candidates:break
a=int(rng.choice(candidates));p,m=move(p,m,a)
if m.bit_count()==42-remaining and end(p,m) is None:found.append((p,m))
if len(found)<n:raise RuntimeError('No se generaron posiciones tardías suficientes')
return found
def load(path,device):
ck=torch.load(path,map_location=device,weights_only=True);model=Network(ck['width'],ck['blocks']).to(device)
model.load_state_dict(ck['state_dict']);model.eval();return model
def infer_fn(model,device):
def infer(p,m):
with torch.no_grad():
x=torch.tensor(planes(p,m)[None],device=device);logits,value=model(x)
valid=torch.zeros((1,7),dtype=torch.bool,device=device);valid[0,legal(m)]=True
prob=F.softmax(logits.masked_fill(~valid,-1e9),-1)[0].cpu().numpy()
return prob,float(value.item())
return infer
def play(infers,sims,first,opening):
p=m=0;turn=0;records=[]
for a in opening:p,m=move(p,m,a);turn+=1
while end(p,m) is None:
who=(first+turn)%2;root=Node(p,m);prior,value=infers[who](p,m)
count=search(root,sims,infers[who]);a=int(np.argmax(count))
records.append({'player':int(p),'mask':int(m),'who':who,'prior':prior.tolist(),
'visits':count.tolist(),'value':value,'action':a})
p,m=move(p,m,a);turn+=1
# El resultado terminal está expresado para el jugador que habría actuado.
result=end(p,m);winner=None if result==0 else (first+turn-1)%2
return (0.5 if winner is None else float(winner==1)),records
def elo(score):
# Corrección de medio punto por lado, explicitada; evita infinitos con muestras pequeñas.
rate=(sum(score)+.5)/(len(score)+1)
return 400*np.log10(rate/(1-rate))
def main():
root=Path(os.getenv('ORYON_C4_OUT','oryon-c4'));quick=os.getenv('ORYON_QUICK','1')=='1'
torch.set_num_threads(1);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model0=load(root/'c4-initial.pt',device);model1=load(root/f'c4-round{2 if quick else 20}.pt',device)
infers=[infer_fn(model0,device),infer_fn(model1,device)];rng=np.random.default_rng(8021)
games=4 if quick else 40;sims=8 if quick else 100;results=[];samples=[];openings=[]
for pair in range(games//2):
opening=rng.integers(0,7,size=2).tolist();openings.append(opening)
for first in (0,1):
score,trace=play(infers,sims,first,opening);results.append(score)
if pair==0 and first==0:samples=trace
print('pareja',pair,'inicio',opening,'primer checkpoint',first,'puntos final',score,'jugadas',len(trace),flush=True)
paired=np.asarray(results).reshape(-1,2)
bootstrap=np.array([elo(paired[rng.integers(len(paired),size=len(paired))].ravel()) for _ in range(1000)])
interval=None if np.ptp(bootstrap)==0 else np.quantile(bootstrap,[.025,.975]).tolist()
points=sample_late(rng,5 if quick else 30);evaluations=[]
for p,m in points:
truth=scores(p,m);visits=search(Node(p,m),sims,infers[1]);a=int(np.argmax(visits))
evaluations.append({'player':p,'mask':m,'optimal_actions':[a for a,v in truth.items() if v==max(truth.values())],
'choice':a,'optimal':truth[a]==max(truth.values()),'scores':truth,'visits':visits.tolist()})
report={'games':games,'simulations':sims,'scores':results,'paired_openings':openings,'elo_difference':float(elo(results)),
'bootstrap_95':interval,'bootstrap_degenerate':interval is None,'solver_remaining':6,
'solver_positions':evaluations,'optimal_fraction':float(np.mean([r['optimal'] for r in evaluations])),
'device':str(device),'torch':torch.__version__,'numpy':np.__version__}
(root/'evaluation.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
(root/'sample-game.json').write_text(json.dumps(samples,indent=2,allow_nan=False),encoding='utf-8')
print('Evaluación',report)
if __name__=='__main__':main()''',encoding='utf-8')
result=subprocess.run([sys.executable,str(script)],capture_output=True,text=True,encoding='utf-8',errors='replace',env={**os.environ,'PYTHONIOENCODING':'utf-8'})
print(result.stdout)
if result.returncode: raise RuntimeError(result.stderr[-3000:])npm run lab and open the connection link.Lab: an mctx reference
mctx provides batched search in JAX. Install mctx==0.0.71, jax==0.12.0.1, jaxlib==0.12.0.1 and compatible dependencies in an isolated environment also containing PyTorch and NumPy. This lesson’s test used JAX on CPU even though PyTorch detected CUDA. Code copies the same checkpoint weights to JAX and checks outputs and transitions against PyTorch and bitboards before searching.
The comparison uses the same positions and simulation count, but mctx and the custom implementation differ in transformation and selection details. mctx processes the set as a batch and the custom version sequentially on CPU. The first call, including JIT compilation, and a warm call are measured separately. One repetition and five positions cannot establish general speed or compare strength; a second full AlphaZero reproduction is not run.
from pathlib import Path
import subprocess, sys, os
script = Path('mctx_compare.py').resolve()
script.write_text(r'''import json, os, time
from pathlib import Path
import numpy as np
import torch
import jax
import jax.numpy as jnp
import mctx
jax.config.update('jax_platform_name','cpu')
from az_connect4 import Node,search,planes,legal,move,end
from c4_eval import load,infer_fn,sample_late,scores
rootdir=Path(os.getenv('ORYON_C4_OUT','oryon-c4'));quick=os.getenv('ORYON_QUICK','1')=='1'
model=load(rootdir/f'c4-round{2 if quick else 20}.pt',torch.device('cpu'))
params={k:jnp.asarray(v.detach().numpy()) for k,v in model.state_dict().items()}
def dense(x,w,b):return [email protected]+b
def network(board):
x=jax.nn.relu(dense(board.reshape(board.shape[0],-1),params['entry.weight'],params['entry.bias']))
for i in range(2):
h=jax.nn.relu(dense(x,params[f'blocks.{i}.a.weight'],params[f'blocks.{i}.a.bias']))
x=jax.nn.relu(x+dense(h,params[f'blocks.{i}.b.weight'],params[f'blocks.{i}.b.bias']))
logits=dense(x,params['policy.weight'],params['policy.bias'])
value=jnp.tanh(dense(x,params['value.weight'],params['value.bias'])[:,0])
invalid=(board[:,0,5,:]+board[:,1,5,:])>0
return jnp.where(invalid,-1e9,logits),value
windows=[]
for r in range(6):
for c in range(7):
for dr,dc in ((1,0),(0,1),(1,1),(1,-1)):
if 0<=r+3*dr<6 and 0<=c+3*dc<7:windows.append([(r+i*dr)*7+c+i*dc for i in range(4)])
windows=jnp.array(windows,dtype=jnp.int32)
def recurrent(params_unused,key,action,embedding):
board,was_terminal=embedding
b=jnp.arange(board.shape[0]);occupied=board[:,0]+board[:,1]
column=occupied[b,:,action];row=jnp.sum(column,axis=1).astype(jnp.int32)
updated=board[:,0].at[b,jnp.minimum(row,5),action].set(1.)
win=jnp.any(jnp.all(updated.reshape((-1,42))[:,windows]>0,axis=2),axis=1)
candidate=jnp.stack((board[:,1],updated),axis=1)
next_board=jnp.where(was_terminal[:,None,None,None],board,candidate)
full=jnp.all(jnp.sum(next_board,axis=1)>0,axis=(1,2));terminal=was_terminal|win|full
logits,value=network(next_board)
dummy=jnp.where(jnp.arange(7)==0,0.,-1e9)
logits=jnp.where(terminal[:,None],dummy,logits)
reward=jnp.where(was_terminal,0.,win.astype(jnp.float32))
out=mctx.RecurrentFnOutput(reward=reward,discount=jnp.where(terminal,0.,-1.),
prior_logits=logits,value=jnp.where(terminal,0.,value))
return out,(next_board,terminal)
rng=np.random.default_rng(1802);positions=sample_late(rng,5 if quick else 30)
board=np.stack([planes(p,m) for p,m in positions]);sims=8 if quick else 100
jboard=jnp.asarray(board);logits,value=network(jboard)
# Contrasta las reglas JAX y la red copiada con los cálculos PyTorch/bitboard.
with torch.no_grad():
torch_logits,torch_value=model(torch.tensor(board))
np.testing.assert_allclose(np.asarray(value),torch_value.numpy(),rtol=2e-5,atol=2e-6)
for i,(p,m) in enumerate(positions):
np.testing.assert_allclose(np.asarray(logits)[i,legal(m)],torch_logits.numpy()[i,legal(m)],rtol=2e-5,atol=2e-6)
for i,(p,m) in enumerate(positions):
for a in legal(m):
result,(next_board,done)=recurrent(None,None,jnp.array([a]),(jboard[i:i+1],jnp.array([False])))
np_p,np_m=move(p,m,a);terminal=end(np_p,np_m)
np.testing.assert_array_equal(np.asarray(next_board)[0],planes(np_p,np_m))
assert float(result.reward[0])==(1. if terminal==-1 else 0.)
assert float(result.discount[0])==(0. if terminal is not None else -1.)
assert bool(done[0])==(terminal is not None)
if terminal is not None:
again,(same,still_done)=recurrent(None,None,jnp.array([0]),(next_board,done))
np.testing.assert_array_equal(np.asarray(same),np.asarray(next_board))
assert bool(still_done[0]) and float(again.reward[0])==0. and float(again.discount[0])==0.
root=mctx.RootFnOutput(prior_logits=logits,value=value,embedding=(jboard,jnp.zeros(len(positions),dtype=bool)))
invalid=(jboard[:,0,5,:]+jboard[:,1,5,:])>0
@jax.jit
def run(key):
return mctx.muzero_policy(None,key,root,recurrent,num_simulations=sims,invalid_actions=invalid,
dirichlet_fraction=0.,temperature=0.)
key=jax.random.PRNGKey(0);start=time.perf_counter();result=run(key);result.action.block_until_ready();first=time.perf_counter()-start
start=time.perf_counter();result=run(key);result.action.block_until_ready();warm=time.perf_counter()-start
own=infer_fn(model,torch.device('cpu'));start=time.perf_counter()
counts=[search(Node(p,m),sims,own) for p,m in positions];own_seconds=time.perf_counter()-start
ours=[int(np.argmax(n)) for n in counts];theirs=np.asarray(result.action).astype(int).tolist()
truth=[scores(p,m) for p,m in positions]
def optimal(choices):return [truth[i][a]==max(truth[i].values()) for i,a in enumerate(choices)]
report={'library':'mctx','mctx':mctx.__version__,'jax':jax.__version__,'device':str(jax.devices()[0]),
'positions':len(positions),'simulations':sims,'first_call_seconds':first,'warm_seconds':warm,
'own_cpu_seconds':own_seconds,'mctx_choices':theirs,'own_choices':ours,
'mctx_optimal':optimal(theirs),'own_optimal':optimal(ours),
'warning':'Misma red y posiciones; PUCT y transformación Q difieren, lote mctx frente a búsqueda secuencial propia.'}
(rootdir/'mctx-comparison.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
print('Comparación real',report)''',encoding='utf-8')
result=subprocess.run([sys.executable,str(script)],capture_output=True,text=True,encoding='utf-8',errors='replace',env={**os.environ,'PYTHONIOENCODING':'utf-8'})
print(result.stdout)
if result.returncode: raise RuntimeError(result.stderr[-3000:])npm run lab and open the connection link.The comparison prints actions and whether each matches any solver-optimal action in those positions. Initial compilation should not be mixed with warm time. Agreement or disagreement may arise from search or the small sample; both methods share weights and rules here but not the same selection algorithm.
Exercises
def mcts_batch(roots, simulations, select, evaluate, expand, backup):
pass