MuZero: planning with a learned model
Take the final step: an agent that does not know the rules. Implement MuZero's representation, dynamics, and prediction networks, search in latent space, and training unrolled for K steps with policy, value, and reward targets. Train on Connect Four, evaluate against the solver, and compare quality and compute with AlphaZero.
After this lesson you can
- Implement MuZero's three networks and search over latent states.
- Implement unrolled training with gradient scaling and n-step targets.
- Train on Connect Four and evaluate against the solver.
- Compare MuZero and AlphaZero at equal compute and analyze where the learned model fails.
Before you start
Planning without a perfect simulator
AlphaZero search uses the rules of the game to generate each child position. MuZero replaces that transition with a learned model. Search does not disappear: decisions are still compared in a tree. What changes is the object being expanded: a latent state that need not resemble a board.
Schrittwieser and collaborators train the model to predict quantities useful for planning: reward, policy, and value. Not reconstructing pixels or board cells does not guarantee that it captures every consequence of an action. A small value error in each transition can change selection several moves ahead; an appropriate check compares unrolled predictions with references on real positions that were not in training.
Three functions, three contracts
The MuZero learned model separates representation, dynamics, and prediction. For a real observation and actions , write
Here is an internal representation after imagining actions, not the real game state. corresponds to the transition from to ; and describe the imagined position. Reward indices start at one, whereas value and policy are also predicted at the root, .
The three functions do not have the same access to data. Representation receives a real observation at the start of search. Dynamics receives a latent and an action, and produces a new latent without consulting the real board. Prediction reads that latent and supplies what the tree needs to decide. Two latents can be numerically different yet yield similar predictions; comparing their coordinates component by component does not measure model accuracy unless an additional correspondence has been imposed.
The model does not need to reconstruct pieces to be useful, but that freedom has a cost: if a feature does not affect losses on observed data, the representation may discard it even when it is decisive in a rarely visited region. For example, a rare winning threat may be poorly represented if self-play hardly ever reaches it. Compare decisions against the solver and group positions by phase or difficulty; a low average loss in the buffer does not demonstrate that those threats are covered.
The trajectories belong to the cohort evaluated with seed 76: five uniformly chosen legal actions without ending the game, and no overlap with segments potentially used to train MuZero. At each depth, the legality counter compares the seven outputs of the latent head with the real rules. The real mask in the bars makes policies easier to compare: do not confuse it with the learned mask used by internal search. The prediction from the real position and the latent prediction come from the same network; the solver provides a third, independent reference.
In Connect 4, the root observation can include the pieces of the player to move and those of the opponent, as in the preceding self-play. Value needs an explicit perspective: if always measured for the player to move, every turn transition changes the sign during backpropagation through the tree. The reward for the final winning move must use the agreed perspective; do not mix that convention with a value target defined for a fixed player.
The two kinds of error in that head have different effects. A false legal prediction lets the tree spend simulations on an impossible continuation whose value can alter root selection. A false illegal prediction discards a continuation that could have been good. Average accuracy by column combines both and can seem high when most columns are legal; also record both error classes and, especially, how often search selects an actually illegal action in a reference reconstruction. In the experiment, the action executed at the root is revalidated using the real rules, but internal nodes receive no such correction.
For each simulation, the tree selects actions using their visits and priorities, applies learned dynamics when expanding a child, and backs predictions up along the path. Latent states in different branches represent hypothetical actions; they are not new observations from the environment. When the agent executes a real action and receives an observation, it builds a root from it again. An internal error can change the chosen action even if the new root starts from a correct observation.
The lab uses discount for this finite game: all intermediate rewards are zero and the winning transition receives one from the perspective of the player who moved. Terminal value is zero, so that reward is not counted twice. In the tree, if is expressed for the player who just acted and for the next player to move, the return to the parent is . An implementation with another discount must also apply it to the backed-up value and the n-step target.
Training a chain without hiding the horizon
Unrolled training takes real trajectory segments and applies recorded actions to the latent model for steps. At each depth it compares policy and value with their targets, and on each transition it compares predicted reward with observed reward. A simple scalar formulation is
The padding mask is essential when the episode ends before : do not train on fictitious targets after termination. Policy cross-entropy takes a distribution over actions, and value loss may use a categorical representation instead of scalar regression. The choice of support, transformations, and loss weights must be recorded: a small scalar implementation is not an exact reproduction of every detail of the paper.
The n-step value target combines observed rewards with a bootstrap value. From a fixed player’s perspective, if the episode does not end earlier,
If termination comes earlier, truncate the sum and do not bootstrap beyond it. From the perspective of the player to move, rewards and future value must be converted to the perspective at , including a sign change for each change of turn. The formula without additional signs assumes all quantities are already in the same perspective. Recall the n-step return and the distinction between actual termination and truncation.
A short horizon uses a potentially biased value estimate sooner; a long one incorporates more real rewards, but takes longer to reach a terminal target and may accumulate trajectory variation. In this game intermediate rewards are zero and the outcome supplies the decisive signal. Training unroll length and value-target horizon are different parameters: decides how many imagined transitions receive loss from a segment, while decides how far each value target is constructed. Choosing the same number for both is a possible configuration, not a mathematical identity.
For example, if there are no intermediate rewards, , and bootstrap value is expressed for the player to move at , two turn changes return to the same perspective as at : the contribution is . With it is . In a terminal win, reward is first assigned to the player who made the winning move and then converted to the perspective of the position receiving the target. Record this convention with each dataset: a silent sign change can produce finite losses while teaching the agent to prefer losing.
Scaling the gradient through a latent transition changes learning without changing the computed forward value. For a tensor , the expression equals exactly, but its derivative with respect to is . For example, halves the gradient crossing that point. A deeper loss’s gradient passes through several such factors, so its contribution may decay with depth. This is an optimization decision, not proof that the model is correct.
The scaling affects the path toward earlier layers; it does not by itself change the observed loss or prediction at that transition. Compare two things separately: that the forward pass is identical and that the derivative with respect to the input tensor is reduced. Multiplying the entire loss by also reduces gradients of the heads producing it, so it is not the same intervention. This difference matters when several heads share the representation.
A related extension is EfficientZero, which adds a consistency loss between representations of real observations and states predicted by dynamics, along with changes to value targets. This extra signal can help with little data, but this lab does not implement EfficientZero and its Atari results do not automatically transfer to Connect 4. Consistency does not remove the need to check reward, legality, and value against external references.
What equal-compute comparison means
Evaluation should use held-out positions labeled by the solver, with the same definition of optimal move and the legal mask declared by the protocol. Report self-play cost, training operations, and evaluation search separately: a dynamics evaluation and an AlphaZero network evaluation need not cost the same in time or FLOPs. Matching only the number of games or only simulations does not match total compute.
The difference is visible in the specific architectures used by the pilots. The short residual network from p12-l06 has four 64-channel blocks; the small MuZero on this page uses a 128-unit latent. If we count multiply-accumulates (MACs) of dense and convolution layers per example, excluding biases, activations, normalization, and backward, the difference is large. For MuZero, the second number counts one dynamics operation, its reward head, and all prediction heads; initial representation is counted separately.
az_stem = 2 * 64 * 3 * 3 * 42
az_blocks = 4 * 2 * 64 * 64 * 3 * 3 * 42
az_heads = 2 * 64 * 32 * 42 + 1344 * 7 + 1344 * 128 + 128
az = az_stem + az_blocks + az_heads
mu_root = 84 * 128 + 128 * 128 + 128 * 7 + 128 + 128 * 7 + 128
mu_transition = (135 * 128 + 128 * 128) + (135 * 128 + 128) + (128 * 7 + 128 + 128 * 7 + 128)
print('AlphaZero, un forward:', az, 'MAC')
print('MuZero, representación y cabezas:', mu_root, 'MAC')
print('MuZero, dinámica y cabezas:', mu_transition, 'MAC')
print('razón forward AlphaZero / dinámica MuZero:', round(az / mu_transition, 1))
# Control MLP: representación 84-128-128 y cabezas de política y valor.
az_mlp_forward = 84 * 128 + 128 * 128 + 128 * 7 + 128
# Forward más gradientes de pesos y entrada; la observación inicial no necesita gradiente.
mu_train_sample = 3 * (mu_root + 5 * mu_transition) - 84 * 128
az_train_sample = 3 * az_mlp_forward - 84 * 128
mu_total = 12 * 25 * 64 * mu_train_sample
az_total = 12 * 296 * 64 * az_train_sample
print('MAC de matrices de ajuste, MuZero y control:', mu_total, az_total)
print('desfase relativo:', round(abs(mu_total - az_total) / max(mu_total, az_total), 6))This count is an arithmetic approximation, not a measurement of time or energy: batches, GPU occupancy, and omitted costs change actual performance. It is enough to rule out automatically treating one simulation in each system as equal-cost. For an equal-compute ablation, add representation and dynamics forwards, training and its backward, and adjust budgets before comparing.
To analyze the model, take a held-out real sequence, represent its first position, and unroll the actions actually played. At each depth compare latent value with the target obtained from the corresponding real position and report error by horizon. This analysis conditioned on real actions does not guarantee that actions chosen by search follow the same distribution. Also evaluate trajectories proposed by the agent itself and record illegal actions and terminal failures.
Two useful comparisons answer different questions. The first compares the latent prediction with the same network’s prediction after representing the real observation: it shows internal inconsistency, but both can be wrong in the same way. The second compares each with the solver: it measures error against the game reference without assuming direct representation is correct. In both cases retain the same trajectory set for each depth; if terminated trajectories are discarded, state that the groups are no longer paired and show how many survive.
In our comparison we fixed 12 generations, 32 games per generation, and 16 self-play simulations for both methods before evaluation. MuZero uses , batch size 64, and 25 updates per generation; the AlphaZero control uses the same representation dimension and 296 updates. This control is a small MLP with 84, 128, and 128 units, not the residual network from p12-l06. The pilot and previous runs are not part of these campaigns, which started from scratch with seed 0.
We count forward and backward matrix multiply operations. PyTorch Profiler and the dimension count agree: per training example, MuZero performs 873,600 MACs and AlphaZero 73,728. The gradient does not need to propagate to the input observation, so one cannot simply multiply each forward by three. With the fixed batch and update counts, totals are 16,773,120,000 and 16,760,438,784 MACs respectively: a relative difference of 0.076%. This equality approximates matrix fitting cost; it excludes activations, normalization, optimizer, search, and energy and does not automatically equalize time or total compute.
On the same 150 positions, balanced with 50 per phase, AlphaZero search chose 120 optimal moves (80.0%) and MuZero 109 (72.7%). The paired difference is −7.3 percentage points. Both used 16 simulations per decision, not the same inference cost. The set had been used for previous diagnostics, so these results are exploratory rather than a blind test. Descriptive Wilson intervals are 72.9 to 85.6% and 65.0 to 79.2%, respectively; stratification and duplicate exclusion limit their interpretation as independent samples. One training seed does not measure variation between agents: it cannot establish that one dominates in general.
Search compute is also recorded separately. MuZero used approximately 6,854 million matrix MACs in self-play; AlphaZero’s count was 2,485 million including self-play and periodic validation. The counters do not cover exactly the same tasks, so they do not constitute matched total compute. In these sequential CPU runs, self-play and fitting times were 12.34 and 6.31 seconds for MuZero, versus 6.38 and 13.79 for AlphaZero. These are measurements on this machine under its particular load, not hardware benchmarks.
To measure latent value, real legal actions were sampled without using the model’s output to choose trajectories. Of the 150 starting positions, 49 reached a terminal before five moves; the remaining 101 were retained at all depths. Their six positions were checked against potential MuZero training segments, with no overlap. The weak solver returns −1, 0, or 1 from the perspective of the player to move; we compare each latent prediction with it. The 101 trajectories are paired across horizons, although selecting by survival favors games that do not end early and does not describe all states.
import numpy as np
depth = np.arange(6)
mae = np.array([0.882915, 0.932046, 0.916822, 0.907922, 0.941298, 0.899107])
false_legal = np.array([71, 51, 59, 65, 78, 86])
actual_illegal = np.array([75, 88, 102, 119, 134, 148])
for k, e, fp, n in zip(depth, mae, false_legal, actual_illegal):
print('horizonte', k, 'n trayectorias', 101, 'error absoluto medio', round(float(e), 3),
'falsos legales / columnas ilegales', int(fp), '/', int(n))Value error does not increase monotonically: it goes from 0.883 at the root to 0.899 after five actions, with intermediate variation. At depth five the head marked 86 of 148 actually illegal columns as legal and rejected 39 of 559 legal ones. The root uses the exact mask; inside the tree those errors can have an effect. The 101 trajectories were nonterminal at all depths and there were no false terminal predictions, but that cohort does not measure whether the head detects actual terminals. Mean reward error on those zero-reward transitions was 0.094 on the first and 0.117 on the fifth. These measurements diagnose this checkpoint; they do not prove that a particular prediction caused a particular decision failure.
Model and loss in the local lab
Start with the three functions and two additional heads predicting legality and termination. The latter are choices in this experiment, not a claim that original MuZero uses this exact architecture. The legality head allows internal search to use the model without consulting the rules, but it can make mistakes. The cell checks shapes and one gradient step with test tensors; it is not Connect 4 training.
import torch
from torch import nn
from torch.nn import functional as F
class MuNet(nn.Module):
def __init__(self, hidden=128):
super().__init__()
self.representation = nn.Sequential(nn.Flatten(), nn.Linear(84, hidden), nn.ReLU(),
nn.Linear(hidden, hidden), nn.Tanh())
self.transition = nn.Sequential(nn.Linear(hidden + 7, hidden), nn.ReLU(),
nn.Linear(hidden, hidden), nn.Tanh())
self.reward = nn.Sequential(nn.Linear(hidden + 7, hidden), nn.ReLU(),
nn.Linear(hidden, 1), nn.Tanh())
self.policy = nn.Linear(hidden, 7)
self.value = nn.Sequential(nn.Linear(hidden, 1), nn.Tanh())
self.legal = nn.Linear(hidden, 7)
self.terminal = nn.Linear(hidden, 1)
def initial(self, observation):
return self.representation(observation.float())
def dynamics(self, hidden, action):
x = torch.cat([hidden, F.one_hot(action.long(), 7).float()], dim=-1)
return self.transition(x), self.reward(x).squeeze(-1)
def predict(self, hidden):
return (self.policy(hidden), self.value(hidden).squeeze(-1),
self.legal(hidden), self.terminal(hidden).squeeze(-1))
torch.manual_seed(4)
model = MuNet(hidden=16)
obs = torch.zeros(3, 2, 6, 7)
h0 = model.initial(obs)
h1, reward = model.dynamics(h0, torch.tensor([0, 1, 2]))
policy, value, legality, terminal = model.predict(h1)
assert h0.shape == h1.shape == (3, 16)
assert reward.shape == value.shape == terminal.shape == (3,)
assert policy.shape == legality.shape == (3, 7)
print('formas verificadas:', tuple(h1.shape), tuple(policy.shape), tuple(value.shape))npm run lab and open the connection link.The first observation plane corresponds to the player to move and the second to the opponent. The action vector is one-hot, not an ordinal column imposing an artificial distance between moves. The figure’s network uses 128 units; the cell uses 16 to keep the check small. Latent state has dimension 16 in the test and 128 in the experiment; it need not directly represent the 42 cells.
def unroll_loss(model, obs, actions, policy, value, reward, legal, terminal, valid, scale=0.5):
# policy: B x (K+1) x 7; legal tiene la misma forma.
# value, reward, terminal y valid: B x (K+1); actions: B x K.
h = model.initial(obs)
total = obs.new_zeros((), dtype=torch.float32)
K = actions.shape[1]
for k in range(K + 1):
if k:
h, r = model.dynamics(h, actions[:, k - 1])
h = scale * h + (1 - scale) * h.detach()
total = total + (((r - reward[:, k]) ** 2) * valid[:, k]).sum()
logits, v, lg, term = model.predict(h)
lp = -(policy[:, k] * F.log_softmax(logits, dim=-1)).sum(-1)
lv = (v - value[:, k]) ** 2
ll = F.binary_cross_entropy_with_logits(lg, legal[:, k], reduction='none').mean(-1)
lt = F.binary_cross_entropy_with_logits(term, terminal[:, k], reduction='none')
total = total + ((lp + lv + ll + lt) * valid[:, k]).sum()
return total / valid.sum().clamp_min(1)
B, K = 3, 3
obs = torch.rand(B, 2, 6, 7)
actions = torch.randint(7, (B, K))
policy = torch.softmax(torch.rand(B, K + 1, 7), dim=-1)
value, reward = torch.rand(B, K + 1), torch.rand(B, K + 1)
legal = torch.ones(B, K + 1, 7)
terminal = torch.zeros(B, K + 1)
valid = torch.tensor([[1, 1, 1, 1], [1, 1, 0, 0], [1, 1, 1, 0]], dtype=torch.float32)
loss = unroll_loss(model, obs, actions, policy, value, reward, legal, terminal, valid)
changed = value.clone()
changed[valid == 0] = 1000
assert torch.allclose(loss, unroll_loss(model, obs, actions, policy, changed, reward, legal, terminal, valid))
loss.backward()
assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters())
print('pérdida finita, relleno ignorado y gradientes finitos:', bool(torch.isfinite(loss)))npm run lab and open the connection link.Here the loss is normalized by the number of valid positions. A terminal position can have zero policy target, zero value, and an empty legality mask; it remains valid to teach the transition reward and termination head. Later steps are masked. In a complete system you must also exclude from training any segment containing a validation or test position.
Searching and training with the learned model
To reproduce the experiment, first prepare the az4 package from p12-l06 and the separate datasets from p12-l07, and execute the two model and loss cells above in the same local interpreter. The following search applies the real legal mask only at the root; imagined nodes use the learned head. If it proposes no action, the algorithm falls back to the highest logit: this is an explicit convention that may hide a legality error. Termination is also predicted. During self-play, the real board still checks the selected root action and outcomes; the model is not presented as an exact simulator.
import json, os, sys, time
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import torch
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
HERE = LAB.parent / 'p12-l09'
HERE.mkdir(parents=True, exist_ok=True)
DEVICE = torch.device('cpu')
torch.set_num_threads(1)
m = SimpleNamespace(MuNet=MuNet, unroll_loss=unroll_loss)
class CountedMuNet(m.MuNet):
def __init__(self):
super().__init__()
self.counts={f'{mode}_{name}':0 for mode in ('search','train') for name in ('initial','dynamics','predict')}
def _count(self,name,x):
self.counts[f'{"train" if self.training else "search"}_{name}']+=len(x)
def initial(self,obs):
self._count('initial',obs);return super().initial(obs)
def dynamics(self,hidden,action):
self._count('dynamics',hidden);return super().dynamics(hidden,action)
def predict(self,hidden):
self._count('predict',hidden);return super().predict(hidden)
@torch.inference_mode()
def latent_search(model,obs,root_legal,sims,rng,device,explore=True):
G=len(obs);M=sims+1;H=model.policy.in_features;idx=np.arange(G)
N=np.zeros((G,M,7),np.float32);W=np.zeros((G,M,7),np.float32)
P=np.zeros((G,M,7),np.float32);R=np.zeros((G,M,7),np.float32)
child=np.full((G,M,7),-1,np.int32);mask=np.zeros((G,M,7),bool)
term=np.zeros((G,M),bool);expanded=np.zeros((G,M),bool);count=np.ones(G,np.int32)
hidden=torch.zeros((G,M,H),device=device)
hidden[:,0]=model.initial(torch.as_tensor(obs,device=device))
logit,val,_,_=model.predict(hidden[:,0]); lp=logit.cpu().numpy()
mask[:,0]=root_legal
def softmax(z,legal):
z=np.where(legal,z,-1e9);e=np.exp(z-z.max(1,keepdims=True));e*=legal
return e/e.sum(1,keepdims=True)
P[:,0]=softmax(lp,root_legal);expanded[:,0]=True
if explore:
for i in idx:
acts=np.flatnonzero(root_legal[i]);P[i,0,acts]=.75*P[i,0,acts]+.25*rng.dirichlet(np.ones(len(acts)))
for _ in range(sims):
node=np.zeros(G,np.int32);active=idx;path=[]
while len(active):
nd=node[active];n=N[active,nd];q=W[active,nd]/np.maximum(n,1)
score=q+1.5*P[active,nd]*np.sqrt(np.maximum(n.sum(1,keepdims=True),1))/(1+n)
a=np.where(mask[active,nd],score,-np.inf).argmax(1);path.append((active,nd,a))
ch=child[active,nd,a];fresh=ch<0
if fresh.any():
gg,nn,aa=active[fresh],nd[fresh],a[fresh];new=count[gg];count[gg]+=1
next_h,r=model.dynamics(hidden[gg,nn],torch.as_tensor(aa,device=device))
logits,v,legal_logits,terminal_logits=model.predict(next_h)
hidden[gg,new]=next_h
legal=(legal_logits.cpu().numpy()>0)
# Si la cabeza no propone ninguna, conserva la de mayor logit.
empty=~legal.any(1)
if empty.any():legal[empty,np.argmax(legal_logits.cpu().numpy()[empty],axis=1)]=True
mask[gg,new]=legal;P[gg,new]=softmax(logits.cpu().numpy(),legal)
term[gg,new]=(terminal_logits.cpu().numpy()>0)
R[gg,nn,aa]=r.cpu().numpy();expanded[gg,new]=True
child[gg,nn,aa]=new;ch=ch.copy();ch[fresh]=new
node[active]=ch
# Una simulación se detiene en la hoja recién expandida o una terminal predicha.
active=active[(~fresh) & (~term[active,ch])]
# Si la hoja se predice terminal su valor es cero; si no, evalúa su valor latente.
_,v,_,_=model.predict(hidden[idx,node]);value=v.cpu().numpy()
value=np.where(term[idx,node],0.,value)
for gg,nn,aa in reversed(path):
value[gg]=R[gg,nn,aa]-value[gg]
N[gg,nn,aa]+=1;W[gg,nn,aa]+=value[gg]
return N[:,0].astype(np.int64),val.cpu().numpy()
search = SimpleNamespace(search=latent_search)
def collect(model,n_games,sims,rng):
games=[{'p':0,'mask':0,'states':[],'policies':[],'values':[],'actions':[]} for _ in range(n_games)]
active=games[:];finished=[]
while active:
p=np.array([g['p'] for g in active],np.int64);mask=np.array([g['mask'] for g in active],np.int64)
obs=engine.encode_np(p,mask);legal=engine.legal_np(mask)
visits,values=search.search(model,obs,legal,sims,rng,DEVICE,explore=True)
next_active=[]
for i,g in enumerate(active):
pi=visits[i]/visits[i].sum()
action=int(rng.choice(7,p=pi)) if len(g['states'])<12 else int(np.argmax(visits[i]))
g['states'].append((g['p'],g['mask']));g['policies'].append(pi.astype(np.float32))
g['values'].append(float(values[i]));g['actions'].append(action)
g['p'],g['mask'],won=engine.play(g['p'],g['mask'],action)
if won or g['mask']==engine.FULL:
g['states'].append((g['p'],g['mask']));g['won']=bool(won);finished.append(g)
else:next_active.append(g)
active=next_active
return finished
def target_value(g,t,n=5):
T=len(g['actions'])
if t==T:return 0.
if t+n<T:return (-1.)**n*g['values'][t+n]
return ((-1.)**(T-1-t)) if g['won'] else 0.
def eligible(episodes,K,excluded):
# Ninguna posición del segmento desenrollado puede pertenecer a validación/prueba.
usable=[(g,t) for g in episodes for t in range(len(g['actions']))
if all(engine.canonical_key(*g['states'][u]) not in excluded
for u in range(t,min(len(g['actions']),t+K+1)))]
if not usable:raise RuntimeError('sin posiciones de entrenamiento')
return usable
def batch(usable,B,K,rng):
X=[];A=[];PI=[];V=[];R=[];L=[];TERM=[];VALID=[]
for pick in rng.integers(len(usable),size=B):
g,t=usable[int(pick)];T=len(g['actions'])
p,mask=g['states'][t];X.append(engine.encode_np(np.array([p]),np.array([mask]))[0])
actions=[];pol=[];vals=[];rews=[];leg=[];term=[];valid=[]
for k in range(K+1):
u=t+k;exists=u<=T;is_terminal=u==T
valid.append(float(exists));term.append(float(is_terminal) if exists else 0.)
if exists and not is_terminal:
pu,mu=g['states'][u]
legal=engine.legal_np(np.array([mu],np.int64))[0].astype(np.float32)
pol.append(g['policies'][u]);vals.append(target_value(g,u));leg.append(legal)
else:
pol.append(np.zeros(7,np.float32));vals.append(0.);leg.append(np.zeros(7,np.float32))
# Recompensa de la acción precedente, medida desde quien la ejecutó.
rews.append(float(k>0 and is_terminal and g['won']))
if k<K:actions.append(g['actions'][u] if u<T else 0)
A.append(actions);PI.append(pol);V.append(vals);R.append(rews);L.append(leg);TERM.append(term);VALID.append(valid)
def tensor(x,dtype=None):return torch.as_tensor(np.asarray(x),dtype=dtype,device=DEVICE)
return (tensor(X,torch.float32),tensor(A,torch.long),tensor(PI,torch.float32),tensor(V,torch.float32),
tensor(R,torch.float32),tensor(L,torch.float32),tensor(TERM,torch.float32),tensor(VALID,torch.float32))
def train(generations=20,games=32,sims=16,updates=100,B=128,K=5,seed=0,
folder_name='mu-seed0',resume=False,stop_after=None):
from az4.evaluate import load_jsonl
data=LAB.parent/'p12-l07'/'data'
excluded={x['key'] for name in ('validation.jsonl','test.jsonl') for x in load_jsonl(data/name)}
rng=np.random.default_rng(seed);torch.manual_seed(seed)
net=CountedMuNet().to(DEVICE);opt=torch.optim.Adam(net.parameters(),lr=1e-3,weight_decay=1e-4)
replay=[];folder=HERE/folder_name;folder.mkdir(exist_ok=True)
start=1
config={'games':games,'sims':sims,'updates':updates,'B':B,'K':K,'seed':seed,'device':str(DEVICE)}
assert all(p.device.type=='cpu' for p in net.parameters())
state_file=folder/'state.pt'
if resume and state_file.exists():
st=torch.load(state_file,map_location=DEVICE,weights_only=False)
if st['config']!=config:raise ValueError('El contrato de ejecución no coincide')
net.load_state_dict(st['model']);opt.load_state_dict(st['optimizer']);replay=st['replay'];net.counts=st['counts']
rng.bit_generator.state=st['numpy_rng'];torch.set_rng_state(st['torch_rng'].cpu())
start=st['generation']+1
log=folder/'train.jsonl'
rows=[json.loads(x) for x in log.read_text(encoding='utf-8').splitlines() if x.strip() and json.loads(x)['generation']<st['generation']] if log.exists() else []
if len(rows)!=st['generation']-1:raise ValueError('Historial incompleto antes del estado')
rows.append(st['last_record'])
log.write_text(''.join(json.dumps(x)+'\n' for x in rows),encoding='utf-8')
print(f'reanudando en generación {start}',flush=True)
elif state_file.exists():
raise FileExistsError('La ejecución ya existe; usa resume=True o cambia de carpeta')
for gen in range(start,generations+1):
net.eval();started=time.perf_counter();replay.extend(collect(net,games,sims,rng));replay=replay[-2000:]
selfplay_seconds=time.perf_counter()-started
usable=eligible(replay,K,excluded);net.train();losses=[];started=time.perf_counter()
for _ in range(updates):
inputs=batch(usable,B,K,rng);loss=m.unroll_loss(net,*inputs)
opt.zero_grad(set_to_none=True);loss.backward();opt.step();losses.append(float(loss.detach()))
if DEVICE.type=='cuda':torch.cuda.synchronize()
train_seconds=time.perf_counter()-started
torch.save({'state_dict':net.state_dict(),'gen':gen,'seed':seed,'games':games,'sims':sims,'K':K},folder/f'gen_{gen:03d}.pt')
record={'generation':gen,'games':gen*games,'sims':sims,'loss':float(np.mean(losses)),
'seconds_selfplay':selfplay_seconds,'seconds_train':train_seconds,'counts_cumulative':net.counts.copy()}
state={'generation':gen,'config':config,'model':net.state_dict(),'optimizer':opt.state_dict(),
'replay':replay,'counts':net.counts,'numpy_rng':rng.bit_generator.state,'torch_rng':torch.get_rng_state(),
'cuda_rng':None,'last_record':record}
tmp=folder/'state.tmp';torch.save(state,tmp);tmp.replace(state_file)
with (folder/'train.jsonl').open('a',encoding='utf-8') as f:f.write(json.dumps(record)+'\n')
print(json.dumps(record),flush=True)
if stop_after is not None and gen>=stop_after:break
npm run lab and open the connection link.State is saved after each generation with weights, optimizer, buffer, generators, counters, and the latest log row; an interruption within a generation requires repeating it. Bit-for-bit reproducibility also depends on the device and its deterministic operations. This long cell creates a new folder and can resume after interruption:
train(generations=12, games=32, sims=16, updates=25, B=64, K=5,
seed=0, folder_name='mu-seed0', resume=True)npm run lab and open the connection link.To reproduce CPU times, start the interpreter with CUDA_VISIBLE_DEVICES=-1 before importing PyTorch. To reproduce the control, run the next cell after preparing az4 and p12-l07 data. The control uses horizontal symmetry and gradient clipping from the AlphaZero pipeline; MuZero uses its own heads and unrolled loss. These are additional implementation choices, so the comparison does not isolate one feature’s effect. In this version of az4, if the process is interrupted exactly between saving state and writing its metrics row, that row must be restored before resuming: do not mistake an incomplete log for a complete state.
from dataclasses import replace
from az4 import train as az_train
class SmallPolicyValue(nn.Module):
def __init__(self, channels=128, blocks=0):
super().__init__()
if channels != 128 or blocks != 0:
raise ValueError('Arquitectura distinta del protocolo')
self.representation = nn.Sequential(nn.Flatten(), nn.Linear(84, 128), nn.ReLU(),
nn.Linear(128, 128), nn.Tanh())
self.policy = nn.Linear(128, 7)
self.value = nn.Sequential(nn.Linear(128, 1), nn.Tanh())
def forward(self, x, legal):
h = self.representation(x.float())
return self.policy(h).masked_fill(~legal, -1e9), self.value(h).squeeze(-1)
az_train.PolicyValueNet = SmallPolicyValue
az_train.PRESETS['corta'] = replace(az_train.PRESETS['corta'], generations=12, games_per_gen=32,
parallel_games=32, sims=16, channels=128, blocks=0, buffer_size=60000,
batch_size=64, steps_per_gen=296, val_sims=8, val_positions=30, seed=0)
az_folder = HERE / 'az-seed0'
if (az_folder / 'state.pt').exists():
st = torch.load(az_folder / 'state.pt', map_location='cpu', weights_only=False)
prior = [json.loads(line) for line in (az_folder / 'metrics.jsonl').read_text(encoding='utf8').splitlines() if line.strip()]
matches = [row for row in prior if row['generation'] == st['generation']]
if len(matches) != 1:
raise ValueError('Falta la fila de métricas del estado; restáurala antes de reanudar')
offset = matches[0]['evals_cumulative']
original_evaluator = az_train.Evaluator
class ContinuousEvaluator(original_evaluator):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.positions = offset
az_train.Evaluator = ContinuousEvaluator
az_train.main(['--preset', 'corta', '--run', str(az_folder),
'--data', str(LAB.parent / 'p12-l07' / 'data'), '--resume'])npm run lab and open the connection link.from az4 import mcts
from az4.net import Evaluator
from az4.evaluate import load_jsonl
items = load_jsonl(LAB.parent / 'p12-l07' / 'data' / 'test.jsonl')
assert len(items) == 150 and len({x['key'] for x in items}) == 150
states = [engine.from_moves(x['moves']) for x in items]
pos = np.array([x[0] for x in states], np.int64)
mask = np.array([x[1] for x in states], np.int64)
az_net = SmallPolicyValue().to(DEVICE)
az_net.load_state_dict(torch.load(az_folder / 'checkpoints' / 'gen_012.pt', map_location=DEVICE, weights_only=True))
az_net.eval()
mu_net = MuNet().to(DEVICE)
mu_net.load_state_dict(torch.load(HERE / 'mu-seed0' / 'gen_012.pt', map_location=DEVICE, weights_only=True)['state_dict'])
mu_net.eval()
az_visits, _, _ = mcts.search(Evaluator(az_net, DEVICE), pos, mask, 16)
mu_visits, _ = latent_search(mu_net, engine.encode_np(pos, mask), engine.legal_np(mask), 16,
np.random.default_rng(75), DEVICE, explore=False)
for name, visits in [('AlphaZero', az_visits), ('MuZero', mu_visits)]:
choices = visits.argmax(1)
correct = sum(item['values'][int(choice)] == max(v for v in item['values'] if v is not None)
for item, choice in zip(items, choices))
print(name, 'jugadas óptimas', correct, '/', len(items))npm run lab and open the connection link.The next cell reconstructs the paired cohort and queries the solver for each nonterminal position. It can take longer than neural search: cost depends on position and solver cache. The full state is used to exclude from the cohort any position present in a segment that could have been used to fit MuZero.
mu_state = torch.load(HERE / 'mu-seed0' / 'state.pt', map_location='cpu', weights_only=False)
assert mu_state['generation'] == 12
validation = load_jsonl(LAB.parent / 'p12-l07' / 'data' / 'validation.jsonl')
excluded = {x['key'] for x in validation + items}
used = set()
for game, t in eligible(mu_state['replay'], 5, excluded):
for u in range(t, min(len(game['actions']), t + 5) + 1):
used.add(engine.canonical_key(*game['states'][u]))
rng = np.random.default_rng(76)
cohort = []
for item in items:
p, mask = engine.from_moves(item['moves'])
trajectory, actions = [(p, mask)], []
for _ in range(5):
choices = np.flatnonzero(engine.legal_np(np.array([mask], np.int64))[0])
action = int(rng.choice(choices))
p, mask, won = engine.play(p, mask, action)
if won or mask == engine.FULL:
break
actions.append(action)
trajectory.append((p, mask))
if len(actions) == 5 and all(engine.canonical_key(*state) not in used for state in trajectory):
cohort.append((item, trajectory, actions))
solver = engine.Solver()
errors = [[] for _ in range(6)]
false_legal = np.zeros(6, dtype=int)
actual_illegal = np.zeros(6, dtype=int)
with torch.inference_mode():
for item, trajectory, actions in cohort:
p, mask = trajectory[0]
h = mu_net.initial(torch.as_tensor(engine.encode_np(np.array([p]), np.array([mask])), device=DEVICE))
for k, (p, mask) in enumerate(trajectory):
_, value, legality, _ = mu_net.predict(h)
exact = max(v for v in item['values'] if v is not None) if k == 0 else solver.value(p, mask)
actual = engine.legal_np(np.array([mask], np.int64))[0]
predicted = (legality.cpu().numpy()[0] > 0)
errors[k].append(abs(float(value.item()) - exact))
false_legal[k] += int((predicted & ~actual).sum())
actual_illegal[k] += int((~actual).sum())
if k < 5:
h, _ = mu_net.dynamics(h, torch.tensor([actions[k]], device=DEVICE))
for k in range(6):
print(k, 'n', len(errors[k]), 'MAE', float(np.mean(errors[k])),
'falsos legales', int(false_legal[k]), '/', int(actual_illegal[k]))npm run lab and open the connection link.The learning curve does not replace the held-out test. Evaluate checkpoints separately. The log distinguishes positions processed by representation, dynamics, and prediction during search and training, including padding rows computed even though their loss is masked. It also stores phase times; backward cost is excluded from those forward counters. In the comparison above, the backward of each matrix product was counted separately, as shown by the totals; game count alone does not match AlphaZero’s cost.
Exercises
def unroll_loss(model, obs, actions, targets, K):
pass