Module contents
Stage 8 of 9Research 120 min

A second game: Othello against an open engine

Demonstrate system generality by bringing it to 8-by-8 Othello with a generic game interface for state, moves, dihedral-group symmetries, and encoding. Without a complete solver, evaluate the agent against a strong open engine at calibrated levels and compare learning efficiency with Connect 4.

After this lesson you can

  • Refactor the system behind a generic game interface and check Connect 4 remains the same.
  • Implement Othello with bitboards, passing turns, and the eight board symmetries.
  • Train with the same pipeline and available budget.
  • Evaluate against an open engine at several levels and estimate relative Elo.

Before you start

Change games without changing the algorithm

The Connect 4 self-play system knows more game details than it seems: seven columns, each turn adds a piece, and a full position ends the game. Othello forces those assumptions to be explicit. Here a move changes existing pieces, passing may be mandatory, and the board has eight geometric symmetries. A general system must delegate rules, representation, and transformations to the game while keeping search, storage, and training independent of those decisions.

Silver and collaborators present AlphaZero as an algorithm applicable to multiple games with their rules as game-specific knowledge. Our small system illustrates that separation in Connect 4 and Othello; its networks, budget, and results do not reproduce the scale or strength of that work’s experiments.

A game-agnostic interface must answer at least five questions: initial state, legal actions, how a state changes when an action is executed, whether it is terminal, and result from a declared perspective. Network encoding and simultaneous state and policy transformation are part of the contract. Regression tests go beyond Connect 4 compiling: they compare legal moves, transitions, value signs, search, and checkpoint performance with the previous protocol.

Regression can be measured with a frozen checkpoint. In our own run both searches were compared on 150 Connect 4 positions with 16 simulations: visits per action matched in all 150, each implementation evaluated 2169 positions with the network, and both chose 125 optimal moves according to the solver. The checkpoint was PUCT generation 8 with seed 0, SHA-256 89bc5d3f6810ad3ff89a485b2f71eb2cd8a2d5fe84c747480c581a94f5b47d70. This comparison demonstrates equivalence on that set and configuration, not every position. The set was an exploratory diagnostic shared with other checks: it should not be presented as a blind final test after choosing adjustments using those results.

Two bitboards and a reading direction

In Othello, a legal move places a piece in an empty cell and brackets one or more opposing pieces between that cell and another own piece in one of eight directions. All bracketed pieces are flipped. If the player to move has no legal move, they pass; the game ends when neither can move. Outcome comes from counting pieces, not moves played.

Two unsigned 64-bit integers can represent own and opposing pieces. With index i=8y+xi=8y+x, one bit indicates a cell. To shift right, first remove bits in the right column and then shift one position; otherwise an edge piece would falsely appear in the next row. In each direction, propagate the opponent chain and look for an empty cell at its end. Bitboards must be disjoint and contain no bits above the board.

Canonical state stores the player-to-move’s pieces first. After a normal move the two bitboards swap after flipping; they also swap after a pass. Thus value perspective changes even on a pass. A position with zero board actions does not simply end: the opponent may have an action and the game continues.

InteractivePlay against the Othello agent
B and W indicate black and white pieces; a dot marks a legal move. Generation 20 network, trained on 640 self-play games.
16
Black / white pieces2 / 2
TurnBlack: you
You play black. After your move, the board shows the prior policy and network value for white: adjust simulations and request its move. The checkpoint comes from our own run of 640 games with 16 simulations; it is a small agent, not a strong engine. Passing is explicit when no legal moves exist.

In 100 nonterminal positions from random prefixes with seed 2608, this checkpoint chose a different move when increasing from one to 32 simulations in 54 cases. The figure shows the control can change a decision; it does not prove the new move is better or estimate frequency in expert games.

Eight symmetries, one consistent policy

The square’s dihedral group contains four rotations and four reflections. Each element transforms every cell, but the special pass action stays fixed. Symmetry augmentation transforms both board planes and all 64 move probabilities together; it leaves pass probability and the outcome from the player to move unchanged. Applying one transformation to board and another to policy creates false labels.

A strong test is commutation: transform the state and then play the transformed action, or play first and transform the result. Both paths must produce the same position, even after a pass. For Connect 4 only horizontal reflection preserves gravity rules; rotating the board is not valid augmentation. A symmetric position can create duplicates, so eight transformations do not necessarily imply eight distinct examples.

Representation from the player to move simplifies both colors but requires care with sign. After placing a piece or passing, the two bitboards swap. If both players lack legal moves, piece counts are compared from the stored perspective; moving back one turn through search reverses value’s sign. Passing is not itself terminal: an implementation ending when the current player cannot move loses positions where the opponent can.

A difference from Connect 4 appears in action structure. There a full column is illegal and a turn drops one piece at one height. Here each empty cell must bracket at least one opposing line between the new piece and an own piece; placing in an empty cell without flipping any is illegal. Bitboard operations must prevent a horizontal shift from wrapping from right edge to left. Opening tests help, but comparison with an independent generator over complete games, including passes, detects errors the initial position does not cover.

The policy vector has 65 components, not 64: the first represent cells and the last pass. In a position with at least one board move, pass is masked; when there are none and the game has not ended, pass is the only legal action. Do not confuse network output count with the number of actually legal branches: most of the 65 actions may be masked in a given position.

Simulation cost depends on game and implementation. In Connect 4 a transition updates one column bit; in Othello it must discover and flip chains in several directions. A 65-logit network also has a different head from a seven-logit network. If both agents use 16 simulations per decision, that matches requested simulations, not time per game or total operation count. To study efficiency, record evaluated positions, duration, batch sizes, and training budget as well as performance against their respective references. Elo against Edax and solver accuracy in Connect 4 answer different questions and are not a common scale.

In our exploratory CPU measurement with one thread, 150 Connect 4 validation roots and 150 random Othello prefixes were searched with 16 simulations per root. Generic search evaluated 2169 network positions on the preceding test set and, on this different validation set, 2153; for Othello it evaluated 2547. Three repetitions of the validation set took 1.16, 1.34, and 1.50 seconds in Connect 4 and 0.53, 0.54, and 0.63 seconds in Othello. The figure includes tree, rules, mask, and network, with other tasks active. The Connect 4 network was residual 4×64 and the Othello one an MLP 128-128, so the difference does not isolate engine efficiency or show that one game is easier to learn.

Training runs were not equivalent either: the Connect 4 checkpoint corresponds to 8 generations of 400 games and 300 batches of 512 examples per generation, while Othello corresponds to 20 generations of 32 games and 100 batches of 128 examples. That is 1,228,800 versus 256,000 examples processed during optimization, besides search and evaluation. The figures reproduce budget but do not permit direct comparison of the games’ learning efficiency. A causal comparison needs controlled architectures and budgets and a comparable performance metric.

An external reference with uncertainty

Without a practical complete solver for every position, an external-engine evaluation measures relative performance against specific opponents. Edax publishes an Othello engine and its levels. Fix version, evaluation weights, level, seed or openings, colors, and time rules. Alternate colors and use paired openings so initial advantage is not confused with the agent’s. A win against one level is evidence about that matchup, not proof of optimal play.

When pairing colors, the natural statistical unit is the opening: its two games share initial position and may resemble each other more than games from other openings. An interval computed as if all 40 games were independent may be too narrow. Precision also depends on opening selection: a fixed easy set describes only that set; a random sample provides uncertainty about the specific distribution sampled.

To express the result in Elo, count a win as 1, a draw as half a point, and a loss as 0. Under the usual logistic model, mean score ss against a fixed opponent corresponds to a difference 400log⁡10(s/(1−s))400\log_{10}(s/(1-s)). This transformation assumes the model and ceases to be finite for scores 0 or 1. A saturated sample does not demonstrate an infinite difference: it indicates that level discriminates poorly and suggests trying a closer opponent or presenting a suitable interval. Elo between configurations measured under different time rules describes that protocol, not budget-independent strength.

Several opponents near the agent’s level are more informative than one that always wins or loses. The Elo model is an approximation and can hide nontransitive matchups.

As a short-run check, the viewer network faced Edax v4.7 with its book disabled at levels 1 and 2. Twenty six-random-move openings were generated; each was played twice with colors swapped. The agent used 16 simulations per decision. Against level 1 it won one game, drew one, and lost 38; against level 2 it lost all 40. These are results for this checkpoint and opening distribution, not a universal strength estimate.

This is a preliminary comparison: Edax uses a depth limit and the agent a simulation count, so time and compute were not matched. To estimate uncertainty by opening, the unit is the average of the two paired games. The next cell calculates a two-sided Hoeffding bound for 20 idealized independent openings, with score between 0 and 1. It is wide and depends on the opening sampling distribution. It does not turn a small sample into a precise measurement.

To explore a time comparison, ten openings were calibrated separately and the pair with closest medians among several levels and budgets was chosen: Edax level 6 and two agent simulations. Calibration medians were 0.953 and 0.947 ms per decision, respectively. On twenty other color-paired openings, the agent lost all 40 games; the same per-opening Hoeffding bound is [0, 0.304] for its mean score. During complete games measured medians were 1.169 ms for Edax and 1.802 ms for the agent, with cumulative times 1.750 and 2.134 s. Initial calibration imposed no strict limit: times changed with positions and machine load. Edax time includes GTP exchange; agent time measures local search. Budgets are approximately calibrated at opening, not exactly equal in time or a reliable Elo estimate after losing every game.

Repeating the published code selected level 8 and four simulations: on the same twenty openings the agent again lost all 40 games, but cumulative times were 10.121 s for Edax and 5.704 s for the agent. That repetition reuses openings and does not count as a new independent sample. It shows why a strict per-move time budget is a different question from adjusting medians on a few positions.

Opponent and budgetWinsDrawsLossesMean score95% bound per opening
Edax level 1; agent 16 simulations11380.0375[0, 0.341]
Edax level 2; agent 16 simulations00400[0, 0.304]
Edax level 6; agent 2 simulations00400[0, 0.304]

Each row summarizes 20 openings, two colors per opening. The first two use the same openings; the third uses others and its budget was calibrated only on validation positions.

[ ]Paired results against EdaxBrowser
import numpy as np
level1 = np.zeros((20, 2))
level1[0, 0] = 0.5  # tablas
level1[18, 1] = 1.0 # victoria
level2 = np.zeros((20, 2))
radius = np.sqrt(np.log(2 / 0.05) / (2 * 20))
for name, scores in [('nivel 1', level1), ('nivel 2', level2)]:
    p = scores.mean(axis=1).mean()
    print(name, 'puntuación:', round(float(p), 4),
          'cota 95 %:', [round(float(max(0, p-radius)), 4), round(float(min(1, p+radius)), 4)])

The engine, from scratch

The next cell runs in the browser. It stores the board as two integers from the player-to-move perspective and reserves action 64 for pass. The test traverses all eight symmetries of the initial position; below you can extend the check to complete games.

[ ]Bitboards, passes, and symmetriesBrowser
FULL = (1 << 64) - 1
FILE_A, FILE_H = 0x0101010101010101, 0x8080808080808080
DIRECTIONS = [(dx, dy) for dy in (-1, 0, 1) for dx in (-1, 0, 1) if dx or dy]

def shift(bits, dx, dy):
    if dx > 0: bits &= FULL ^ FILE_H
    if dx < 0: bits &= FULL ^ FILE_A
    n = 8 * dy + dx
    return ((bits << n) & FULL) if n >= 0 else bits >> -n

def legal_moves(own, opp):
    if own & opp or (own | opp) & ~FULL: raise ValueError('bitboards inválidos')
    empty, moves = FULL ^ (own | opp), 0
    for dx, dy in DIRECTIONS:
        run = shift(own, dx, dy) & opp
        for _ in range(5): run |= shift(run, dx, dy) & opp
        moves |= shift(run, dx, dy) & empty
    return moves

def play(own, opp, action):
    legal = legal_moves(own, opp)
    if action == 64:
        if legal: raise ValueError('pase ilegal')
        return opp, own
    if not 0 <= action < 64 or not legal & (1 << action): raise ValueError('jugada ilegal')
    move, flips = 1 << action, 0
    for dx, dy in DIRECTIONS:
        ray, captured = shift(move, dx, dy), 0
        while ray & opp:
            captured |= ray
            ray = shift(ray, dx, dy)
        if ray & own: flips |= captured
    return opp ^ flips, own | flips | move

def terminal(own, opp):
    return not legal_moves(own, opp) and not legal_moves(opp, own)

def transform_action(action, symmetry):
    if action == 64: return 64
    x, y = action % 8, action // 8
    if symmetry >= 4: x = 7 - x
    for _ in range(symmetry % 4): x, y = 7 - y, x
    return 8 * y + x

def transform(bits, symmetry):
    result = 0
    while bits:
        bit = bits & -bits
        i = bit.bit_length() - 1
        bits ^= bit
        result |= 1 << transform_action(i, symmetry)
    return result

own, opp = (1 << 28) | (1 << 35), (1 << 27) | (1 << 36)
legal = legal_moves(own, opp)
assert [i for i in range(64) if legal & (1 << i)] == [19, 26, 37, 44]
for symmetry in range(8):
    assert transform(legal, symmetry) == legal_moves(transform(own, symmetry), transform(opp, symmetry))
    for action in [i for i in range(64) if legal & (1 << i)]:
        a, b = play(own, opp, action)
        assert play(transform(own, symmetry), transform(opp, symmetry), transform_action(action, symmetry)) == (transform(a, symmetry), transform(b, symmetry))
print('apertura: 4 jugadas legales; 8 simetrías y transiciones comprobadas')

One interface for two games

The following search takes a rules object and a batched evaluation function. Connect 4 and Othello share selection, expansion, and backpropagation; each adapter decides legal actions, transitions, and terminal state. First run this page’s Othello engine and prepare p12-l06’s az4 package. Equal visits on frozen positions and weights are a more precise regression test than comparing only the average of a new campaign.

[ ]Interchangeable rules and common searchLocal GPU
import math, os, sys
from pathlib import Path
from types import SimpleNamespace
import numpy as np
LAB = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser() / 'p12-l06'
sys.path.insert(0, str(LAB))
from az4 import engine
def initial(): return (1 << 28) | (1 << 35), (1 << 27) | (1 << 36)
def result(own, opp): return float(np.sign(own.bit_count() - opp.bit_count()))
game = SimpleNamespace(initial=initial, legal_moves=legal_moves, apply=play, terminal=terminal,
                       result=result, transform=transform, transform_action=transform_action)
class Connect4:
    num_actions=7
    def initial(self):return (0,0,None)
    def legal(self,state):return [i for i in range(7) if engine.move_bit(state[1],i)]
    def play(self,state,action):
        p,m,win=engine.play(state[0],state[1],action)
        return p,m,(-1 if win else 0 if m==engine.FULL else None)
    def terminal(self,state):return state[2] is not None
    def result(self,state):return state[2]

class Othello:
    num_actions=65
    def initial(self):return game.initial()
    def legal(self,state):
        moves=game.legal_moves(*state)
        return [i for i in range(64) if moves & (1<<i)] or [64]
    def play(self,state,action):return game.apply(*state,action)
    def terminal(self,state):return game.terminal(*state)
    def result(self,state):return game.result(*state)

class GenericNode:
    def __init__(self,rules,state):
        self.state=state;self.legal=rules.legal(state);self.prior=None
        self.n=np.zeros(rules.num_actions,np.int32);self.w=np.zeros(rules.num_actions,np.float64);self.children={}

def generic_search(rules,evaluate,states,sims,c_puct=1.5,rng=None,explore=False):
    """evaluate(states) -> probabilidades legales y valores desde quien mueve."""
    if sims<1 or any(rules.terminal(s) for s in states):raise ValueError('raíz terminal o presupuesto nulo')
    roots=[GenericNode(rules,s) for s in states]
    def expand(nodes):
        pri,values=evaluate([n.state for n in nodes])
        for n,p in zip(nodes,pri):n.prior=np.asarray(p)
        return values
    expand(roots)
    if explore:
        if rng is None:raise ValueError('falta generador')
        for root in roots:
            root.prior[root.legal]=.75*root.prior[root.legal]+.25*rng.dirichlet(np.full(len(root.legal),.3))
    for _ in range(sims):
        paths=[];leaves=[];values=[None]*len(roots);indices=[]
        for i,root in enumerate(roots):
            node=root;path=[]
            while True:
                legal=np.array(node.legal)
                q=node.w[legal]/np.maximum(node.n[legal],1)
                score=q+c_puct*node.prior[legal]*math.sqrt(max(1,node.n.sum()))/(1+node.n[legal])
                action=int(legal[np.argmax(score)]);path.append((node,action))
                if action not in node.children:
                    child=GenericNode(rules,rules.play(node.state,action));node.children[action]=child
                    if rules.terminal(child.state):values[i]=float(rules.result(child.state))
                    else:leaves.append(child);indices.append(i)
                    break
                node=node.children[action]
                if rules.terminal(node.state):values[i]=float(rules.result(node.state));break
            paths.append(path)
        if leaves:
            for i,v in zip(indices,expand(leaves)):values[i]=float(v)
        for path,v in zip(paths,values):
            for node,action in reversed(path):
                v=-v;node.n[action]+=1;node.w[action]+=v
    return np.stack([n.n for n in roots])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To repeat regression with your own checkpoint generated in p12-l07, specify its path via ATLAS_AZ_CHECKPOINT and use the held-out set generated there. The next test compares visits, not just chosen action; it also counts positions evaluated by both searches.

[ ]Connect 4 regression with trained weightsLocal GPU
import json, torch
from az4 import mcts
from az4.net import PolicyValueNet, Evaluator
checkpoint = Path(os.environ['ATLAS_AZ_CHECKPOINT']).expanduser()
test_path = LAB.parent / 'p12-l07' / 'data' / 'test.jsonl'
items = [json.loads(line) for line in test_path.read_text(encoding='utf-8').splitlines() if line.strip()]
net = PolicyValueNet(channels=64, blocks=4)
net.load_state_dict(torch.load(checkpoint, map_location='cpu', weights_only=True)); net.eval()
evaluate = Evaluator(net, 'cpu'); rules = Connect4(); states = []
for item in items:
    state = rules.initial()
    for action in item['moves']:
        state = rules.play(state, action)
        assert not rules.terminal(state)
    states.append(state)
p = np.array([s[0] for s in states], np.int64)
mask = np.array([s[1] for s in states], np.int64)
def adapter(batch):
    return evaluate(np.array([s[0] for s in batch], np.int64),
                    np.array([s[1] for s in batch], np.int64))
previous, _, _ = mcts.search(evaluate, p, mask, 16)
previous_cost = evaluate.positions; evaluate.positions = 0
generic = generic_search(rules, adapter, states, 16)
assert np.array_equal(previous, generic) and previous_cost == evaluate.positions
optimal = sum(item['values'][int(visits.argmax())] == max(v for v in item['values'] if v is not None)
              for item, visits in zip(items, generic))
print('posiciones con visitas iguales:', len(items), '| óptimas:', optimal,
      '| posiciones evaluadas por búsqueda:', previous_cost)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Reproducible self-play and training

In a local Python environment with NumPy and PyTorch, first run the preceding engine and common-search cells in the same interpreter. The viewer checkpoint was trained with Othello-specific search and the same 128-128 network, visit targets, eight symmetries, and 20 generations of 32 games. The generic implementation was checked against that search on frozen positions and a partial run; check regression before using it in another campaign. Search batches leaf evaluation, applies noise only during self-play, and flips sign on a pass too. The buffer retains the latest 40 000 positions. Training is expensive; it does not start automatically when opening the lesson.

[ ]Othello network, search, and self-playLocal GPU
import json, math, random
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

def initial():
    return (1 << 28) | (1 << 35), (1 << 27) | (1 << 36)

def result(own, opp):
    return float(np.sign(own.bit_count() - opp.bit_count()))

game = SimpleNamespace(initial=initial, legal_moves=legal_moves, apply=play,
                       terminal=terminal, result=result, transform=transform,
                       transform_action=transform_action)
OTHELLO_DIR = Path('othello-lab')
OTHELLO_DIR.mkdir(parents=True, exist_ok=True)
DEVICE=torch.device('cuda' if torch.cuda.is_available() else 'cpu')

def actions(own,opp):
    bits=game.legal_moves(own,opp)
    return [i for i in range(64) if bits & (1<<i)] or [64]

def encode(own,opp):
    return np.array([[int((v>>i)&1) for i in range(64)] for v in (own,opp)],np.float32).reshape(-1)

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.body=nn.Sequential(nn.Linear(128,128),nn.ReLU(),nn.Linear(128,128),nn.ReLU())
        self.policy=nn.Linear(128,65);self.value=nn.Linear(128,1)
    def forward(self,x,legal):
        h=self.body(x)
        return self.policy(h).masked_fill(~legal,-1e9),torch.tanh(self.value(h)).squeeze(-1)

def search(net, states, sims, rng, explore=True):
    rules = Othello()
    def batch_evaluate(batch):
        x = np.stack([encode(*state) for state in batch])
        legal = np.zeros((len(batch), 65), bool)
        for i, state in enumerate(batch): legal[i, rules.legal(state)] = True
        with torch.inference_mode():
            logits, value = net(torch.tensor(x, device=DEVICE), torch.tensor(legal, device=DEVICE))
            return torch.softmax(logits, dim=1).cpu().numpy(), value.cpu().numpy()
    return list(generic_search(rules, batch_evaluate, states, sims, rng=rng, explore=explore))

def selfplay(net,count,sims,rng):
    slots=[{'state':game.initial(),'hist':[]} for _ in range(count)]
    dataset=[]
    while slots:
        counts=search(net,[s['state'] for s in slots],sims,rng)
        remaining=[]
        for slot,n in zip(slots,counts):
            pi=n/n.sum();own,opp=slot['state']
            # Muestreo de visitas en 12 primeros turnos; después máxima visita.
            a=int(rng.choice(65,p=pi)) if len(slot['hist'])<12 else int(np.argmax(n))
            slot['hist'].append((own,opp,pi.astype(np.float32)))
            slot['state']=game.apply(own,opp,a)
            if game.terminal(*slot['state']):
                terminal=game.result(*slot['state']);T=len(slot['hist'])
                for t,(p,q,target) in enumerate(slot['hist']):
                    z=terminal*((-1)**(T-t))
                    dataset.append((p,q,target,float(z)))
            else:remaining.append(slot)
        slots=remaining
    return dataset

def augment(row,sym):
    own,opp,pi,z=row
    policy=np.zeros(65,np.float32)
    for i in range(65):policy[game.transform_action(i,sym)]=pi[i]
    own,opp=game.transform(own,sym),game.transform(opp,sym)
    legal=np.zeros(65,bool);legal[actions(own,opp)]=True
    return encode(own,opp),legal,policy,z

def train(generations=20,games_per_gen=32,sims=16,updates=100,seed=0,folder_name='autor16-othello-runs',resume=False):
    rng=np.random.default_rng(seed);random.seed(seed);torch.manual_seed(seed)
    net=Net().to(DEVICE);opt=torch.optim.Adam(net.parameters(),lr=1e-3,weight_decay=1e-4)
    replay=[]; folder=OTHELLO_DIR/folder_name;folder.mkdir(exist_ok=True)
    state_path=folder/'state.pt';start=1
    contract={'seed':seed,'games_per_gen':games_per_gen,'sims':sims,'updates':updates}
    if state_path.exists():
        if not resume: raise FileExistsError('La carpeta ya contiene una ejecución; usa resume=True')
        saved=torch.load(state_path,map_location=DEVICE,weights_only=False)
        if saved['contract']!=contract:raise ValueError('El contrato de entrenamiento cambió')
        net.load_state_dict(saved['net']);opt.load_state_dict(saved['optimizer']);replay=saved['replay']
        rng.bit_generator.state=saved['numpy_rng'];random.setstate(saved['python_rng'])
        torch.set_rng_state(saved['torch_rng'].cpu())
        if torch.cuda.is_available() and saved['cuda_rng'] is not None:
            torch.cuda.set_rng_state_all([state.cpu() for state in saved['cuda_rng']])
        start=saved['generation']+1
        log=folder/'train.jsonl'
        if log.exists():
            rows=[line for line in log.read_text(encoding='utf-8').splitlines() if json.loads(line)['generation']<start]
            log.write_text(''.join(line+'\n' for line in rows),encoding='utf-8')
    for gen in range(start,generations+1):
        net.eval();new=selfplay(net,games_per_gen,sims,rng);replay.extend(new)
        replay=replay[-40000:];net.train(); losses=[]
        for _ in range(updates):
            rows=[augment(replay[int(i)],int(rng.integers(8))) for i in rng.integers(len(replay),size=128)]
            x,mask,pi,z=map(np.stack,zip(*rows))
            logits,val=net(torch.as_tensor(x,device=DEVICE),torch.as_tensor(mask,device=DEVICE))
            target=torch.as_tensor(pi,device=DEVICE);outcome=torch.as_tensor(z,dtype=torch.float32,device=DEVICE)
            loss=-(target*F.log_softmax(logits,dim=1)).sum(1).mean()+F.mse_loss(val,outcome)
            opt.zero_grad(set_to_none=True);loss.backward();opt.step();losses.append(loss.item())
        checkpoint={'state_dict':net.state_dict(),'generation':gen,'seed':seed,'sims':sims,'games_per_gen':games_per_gen}
        torch.save(checkpoint,folder/f'gen_{gen:03d}.pt')
        state={'contract':contract,'generation':gen,'net':net.state_dict(),'optimizer':opt.state_dict(),
               'replay':replay,'numpy_rng':rng.bit_generator.state,'python_rng':random.getstate(),
               'torch_rng':torch.get_rng_state(),
               'cuda_rng':torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None}
        temporary=folder/'state.tmp';torch.save(state,temporary);temporary.replace(state_path)
        row={'generation':gen,'games':gen*games_per_gen,'positions':len(replay),'loss':float(np.mean(losses))}
        with (folder/'train.jsonl').open('a',encoding='utf-8') as f:f.write(json.dumps(row)+'\n')
        print(json.dumps(row),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Train the small agentLocal GPU
train(generations=20, games_per_gen=32, sims=16, updates=100, seed=0,
      folder_name='runs-seed0', resume=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The state.pt file retains optimizer, buffer, and generators after each generation; interruption midway through a phase requires repeating it from the last complete state. Bit-for-bit continuation also depends on device and deterministic operations. Check Connect 4 regression by comparing visits action by action with the preceding implementation, including a trained checkpoint, before changing game. In Othello check passes, perspective changes, and all eight policy transformations. Checkpoints and seed are part of the evaluation protocol; a single training run does not quantify its variation.

This cell reproduces search measurement with both networks on CPU. It uses the Connect 4 checkpoint specified by ATLAS_AZ_CHECKPOINT, the Othello one generated above, and p12-l07 validation positions. Durations vary with machine and concurrent load; evaluated-position count is part of the result, not a universal constant.

[ ]Measure search in both gamesLocal GPU
import time
torch.set_num_threads(1)
from az4.net import PolicyValueNet, Evaluator
from az4.evaluate import load_jsonl
az = PolicyValueNet(channels=64, blocks=4).cpu()
az.load_state_dict(torch.load(Path(os.environ['ATLAS_AZ_CHECKPOINT']), map_location='cpu', weights_only=True)); az.eval()
ot = Net().cpu()
ot.load_state_dict(torch.load(OTHELLO_DIR/'runs-seed0'/'gen_020.pt', map_location='cpu', weights_only=True)['state_dict']); ot.eval()
arules, orules = Connect4(), Othello()
az_states = []
for item in load_jsonl(LAB.parent/'p12-l07'/'data'/'validation.jsonl'):
    state = arules.initial()
    for action in item['moves']: state = arules.play(state, action)
    az_states.append(state)
rng = np.random.default_rng(1608); ot_states = []
while len(ot_states) < len(az_states):
    state = orules.initial()
    for _ in range(int(rng.integers(4, 55))):
        state = orules.play(state, int(rng.choice(orules.legal(state))))
        if orules.terminal(state): break
    else: ot_states.append(state)
aeval = Evaluator(az, 'cpu'); counts = {'othello': 0}
def alpha_eval(batch):
    return aeval(np.array([s[0] for s in batch], np.int64), np.array([s[1] for s in batch], np.int64))
def othello_eval(batch):
    legal = np.zeros((len(batch), 65), bool)
    for i, state in enumerate(batch): legal[i, orules.legal(state)] = True
    x = torch.as_tensor(np.stack([encode(*state) for state in batch]))
    with torch.inference_mode(): logits, value = ot(x, torch.as_tensor(legal))
    counts['othello'] += len(batch)
    return torch.softmax(logits, 1).numpy(), value.numpy()
for rules, fn, states in ((arules, alpha_eval, az_states), (orules, othello_eval, ot_states)):
    generic_search(rules, fn, states[:2], 2)  # calentamiento, fuera de la medida
for name, rules, fn, states in (('Conecta 4', arules, alpha_eval, az_states), ('Othello', orules, othello_eval, ot_states)):
    for repeat in range(3):
        before = aeval.positions if name == 'Conecta 4' else counts['othello']
        start = time.perf_counter(); visits = generic_search(rules, fn, states, 16)
        elapsed = time.perf_counter() - start
        after = aeval.positions if name == 'Conecta 4' else counts['othello']
        assert (visits.sum(axis=1) == 16).all()
        print(name, repeat, 'raíces:', len(states), 'evaluaciones:', after-before, 'segundos:', elapsed)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Games against Edax

To repeat the comparison, install Edax with its evaluation files and point EDAX_EXE to the executable. The following protocol uses GTP, disables the book, records each move, and checks legality with our engine. It starts from six random moves and repeats each opening with both colors. Edax’s limit is a depth level and the agent’s a simulation count: also record times if you want to calibrate them, since they are not equivalent by construction.

[ ]GTP bridge and paired gamesLocal GPU
import os, subprocess, time
from pathlib import Path
EDAX = Path(os.environ['EDAX_EXE']).expanduser().resolve()

def gtp(process, message):
    process.stdin.write(message + '\n'); process.stdin.flush()
    lines = []
    while True:
        line = process.stdout.readline()
        if line == '': raise RuntimeError('Edax terminó antes de responder')
        if not line.strip():
            if lines: break
            continue
        lines.append(line.strip())
    response = ' '.join(lines)
    if not response.startswith('='): raise RuntimeError(response)
    return response[1:].strip()

def notation(action):
    return 'pass' if action == 64 else chr(97 + action % 8) + str(1 + action // 8)

def parse_move(text):
    if text.lower() == 'pass': return 64
    return (int(text[1:]) - 1) * 8 + ord(text[0].lower()) - 97

def play_edax(net, level, seed, edax_black, sims=16):
    process = subprocess.Popen([str(EDAX), '-gtp', '-l', str(level), '-book-usage', 'off'],
        cwd=EDAX.parent, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        text=True, bufsize=1)
    rng = np.random.default_rng(seed); own, opp = initial(); black = True; moves = []; timings = []
    try:
        assert gtp(process, 'protocol_version') == '2'
        for _ in range(6):
            color = 'black' if black else 'white'; bits = legal_moves(own, opp)
            if terminal(own, opp): break
            choices = [i for i in range(64) if bits & (1 << i)] or [64]
            action = int(rng.choice(choices)); gtp(process, 'play ' + color + ' ' + notation(action))
            own, opp = play(own, opp, action); moves.append(notation(action)); black = not black
        opening = moves.copy()
        while not terminal(own, opp):
            color = 'black' if black else 'white'; bits = legal_moves(own, opp)
            started = time.perf_counter()
            if black == edax_black:
                action = parse_move(gtp(process, 'genmove ' + color))
            else:
                visits = search(net, [(own, opp)], sims, rng, explore=False)[0]
                action = int(np.argmax(visits))
            timings.append({'side': 'edax' if black == edax_black else 'agent',
                            'seconds': time.perf_counter() - started})
            if black != edax_black: gtp(process, 'play ' + color + ' ' + notation(action))
            if not ((action == 64 and not bits) or (0 <= action < 64 and bits & (1 << action))):
                raise ValueError('jugada ilegal: ' + notation(action))
            own, opp = play(own, opp, action); moves.append(notation(action)); black = not black
        agent_result = result(own, opp) * (1 if black != edax_black else -1)
        return {'level': level, 'seed': seed, 'edax_black': edax_black, 'sims': sims,
                'opening': opening, 'moves': moves, 'agent_result': agent_result, 'timings': timings}
    finally:
        if process.poll() is None:
            gtp(process, 'quit'); process.wait()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Paired checkpoint evaluationLocal GPU
checkpoint = OTHELLO_DIR / 'runs-seed0' / 'gen_020.pt'
net = Net().to(DEVICE)
net.load_state_dict(torch.load(checkpoint, map_location=DEVICE, weights_only=True)['state_dict'])
net.eval()
games = [play_edax(net, level, seed, color, sims=16)
         for level in (1, 2) for seed in range(20) for color in (True, False)]
(OTHELLO_DIR / 'edax-results.json').write_text(json.dumps(games, indent=2), encoding='utf-8')
for level in (1, 2):
    values = [g['agent_result'] for g in games if g['level'] == level]
    print('nivel', level, 'victorias', values.count(1), 'tablas', values.count(0), 'derrotas', values.count(-1))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

If results differ, check version, weights, seed, checkpoint, device, and simulation count before attributing it to randomness. Games use paired openings; calculate the interval by opening, not individual game.

To calibrate time, use different openings from test and choose the pair before playing the latter. The following measurements include Edax GTP communication and only the agent’s local search, as in the described comparison. The chosen pair can change on another machine.

[ ]Calibrate the time budgetLocal GPU
import statistics, math
DEVICE = torch.device('cpu'); torch.set_num_threads(1); net = net.cpu().eval()
def calibration_position(seed):
    rng = np.random.default_rng(seed); own, opp = initial(); black = True; moves = []
    for _ in range(6):
        bits = legal_moves(own, opp)
        choices = [i for i in range(64) if bits & (1 << i)] or [64]
        action = int(rng.choice(choices))
        moves.append(('black' if black else 'white', action))
        own, opp = play(own, opp, action); black = not black
    return own, opp, moves, ('black' if black else 'white')

def edax_times(level, positions):
    process = subprocess.Popen([str(EDAX), '-gtp', '-l', str(level), '-book-usage', 'off'],
        cwd=EDAX.parent, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
    times = []
    try:
        assert gtp(process, 'protocol_version') == '2'
        for own, opp, moves, color in positions:
            gtp(process, 'clear_board')
            for turn, action in moves: gtp(process, 'play ' + turn + ' ' + notation(action))
            start = time.perf_counter(); action = parse_move(gtp(process, 'genmove ' + color))
            times.append(time.perf_counter() - start)
            bits = legal_moves(own, opp)
            assert (action == 64 and not bits) or (0 <= action < 64 and bits & (1 << action))
    finally:
        if process.poll() is None: gtp(process, 'quit'); process.wait()
    return times

def agent_times(sims, positions):
    rng = np.random.default_rng(75); times = []
    search(net, [positions[0][:2]], sims, rng, explore=False)
    for own, opp, _, _ in positions:
        start = time.perf_counter(); search(net, [(own, opp)], sims, rng, explore=False)
        times.append(time.perf_counter() - start)
    return times

positions = [calibration_position(seed) for seed in range(100, 110)]
edax = {level: edax_times(level, positions) for level in (4, 5, 6, 7, 8)}
agent = {sims: agent_times(sims, positions) for sims in (1, 2, 4, 8, 16, 32)}
level, sims = min(((level, sims) for level in edax for sims in agent),
    key=lambda pair: abs(math.log(statistics.median(edax[pair[0]]) / statistics.median(agent[pair[1]]))))
paired = [play_edax(net, level, seed, color, sims) for seed in range(1000, 1020) for color in (True, False)]
record = {'calibration_edax': edax, 'calibration_agent': agent, 'level': level, 'sims': sims, 'games': paired}
(OTHELLO_DIR / 'edax-time-calibrated.json').write_text(json.dumps(record, indent=2), encoding='utf-8')
print('elegidos:', level, sims, '| puntuación:', sum((g['agent_result'] + 1) / 2 for g in paired) / len(paired))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericCompare augmentations
Without duplicates, how many times larger is the number of valid geometric transformations for Othello than for Connect 4? Count the identity and remember gravity must be preserved.
QuizA move without placing a piece
Representation and value are always from the player-to-move perspective. In a nonterminal position without legal moves, play passes to the opponent. What happens to value perspective when backing up?
QuizAn informative opponent
How do you calibrate the external engine to estimate a useful relative Elo?
CodeMoves with bitboards
Implement legal_moves(own, opp) for Othello with i = 8*y+x. Return the integer whose bits mark legal empty cells. own and opp are disjoint 64-bit bitboards. For each of eight directions, shift without wrapping at edges, propagate through up to six opponent pieces, and find an empty cell at the end.
def legal_moves(own, opp):
  pass
Shift+Enter to run
Key idea
Generality is checked at boundaries: a pass changes perspective, a symmetry transforms state and policy together, and external evaluation needs an explicit protocol and sufficient uncertainty reporting.