MuZero: planning with a learned model
Study MuZero's latent model, which predicts rewards, values, and policies relevant to planning without requiring game rules. Implement representation, dynamics, and prediction functions, unrolled n-step targets, latent MCTS, min-max normalization, categorical value support, and Reanalyse on top of AlphaZero.
After this lesson you can
- Explain value equivalence as a MuZero model-design criterion.
- Implement h, g, and f and latent-space search with min-max normalization.
- Construct correctly aligned unrolled policy, value, and reward targets.
- Implement the categorical-support value transform and Reanalyse.
- Compare AlphaZero and MuZero on the same game and on an environment without known rules.
Before you start
Search without a known simulator
AlphaZero searches using rules to generate each successor. In other problems the environment can be interacted with, but no exact function permits arbitrary simulation of consequences. MuZero learns an internal model and searches inside it. Its representation need not reconstruct every pixel: it is trained to predict reward, policy, and value signals useful for decisions.
That choice does not make every compact representation sufficient. If visually similar situations require different actions and the model confuses them, planning may fail. It also does not guarantee reliability on action sequences absent from data. The relevant comparison is behavior in the environment, not just internal consistency of an imagined trajectory.
The value equivalence principle formalizes a version of this idea: two models can induce the same Bellman effect on a family of policies and value functions despite differing transitions. The family matters. Agreement only on observed policies does not ensure correctness for a new policy exploiting uncovered regions.
For example, two models could distinguish background colors differently yet produce the same rewards and values for decisions of interest. That visual detail need not be explicitly represented. Conversely, if a visual difference indicates a closed door and changes the action avoiding a penalty, discarding it can change value. The relevant property is not generic image similarity; it depends on policies, value functions, and states in the comparison.
Exact equivalence for a sufficiently broad family permits reasoning about optimal decisions, as in the exercise. In practice finite losses are fitted with limited data and imperfect approximators. Low replay loss does not prove operator equality over all states and policies. Separating that theoretical claim from measured behavior avoids turning a design objective into an experimental guarantee.
Representation, dynamics, and prediction
The MuZero model has three functions. With observation or history , actions , and latent state ,
Representation starts search from real data. Dynamics produce the next internal state and predicted transition reward; prediction supplies prior and value. Superscript counts imagined steps from , not different episodes. need not be a real observation or have physically interpretable coordinates.
Training unrolling uses actually recorded actions. At policy and value of are supervised; after applying , predicted reward is compared with and next policy and value with their targets at . The pattern repeats to . There is no initial reward loss because no action has yet been applied.
The table comes from our CartPole-v1 trajectory, seed 0. Rewards and actions are real; search visits and values are targets saved after Reanalyse with a reduced model. The final row shows policy and value but adds no extra unroll transition. Target sums observed rewards and, when enough steps exist, uses value saved at bootstrap time. Values are not results of an Atari-scale trained model.
For a single-agent task, an -step target is
if steps are available and no real terminal has been reached. If termination occurs earlier, stop the sum without bootstrap. An external time limit differs: final-observation value can be used if the underlying task continues. In a zero-sum game with reward from the acting player’s perspective, each step changes perspective and the between-step factor is .
Code masks nonexistent positions beyond the end. To illustrate stability, it normalizes each latent between its per-example minimum and maximum, averages unroll losses, and multiplies the gradient entering each dynamics step by 1/2. The operation leaves the forward value intact; it changes only backpropagation to earlier steps. The original paper describes loss and gradient scaling as an optimization choice, not proof that learning always diverges without it.
A small table helps before writing the loop. Initial representation corresponds to the observation at and receives policy and value targets at . The first dynamics call consumes the action at , predicts reward received upon reaching , and creates the state from which policy and value of are predicted. Accidentally using the previous reward still yields a valid numeric loss and training may run without exceptions, but learns an incorrect temporal relationship.
Termination affects multiple places. If an action wins a game, that reward must supervise dynamics even without a next training state. Do not invent a policy target for a post-terminal state. Time truncation ends the available record, but the task may conceptually continue and the value target may bootstrap from the final observation. The lab distinguishes both signals and cuts the unroll when the recorded sequence ends.
MCTS on learned state
Latent search selects an action with PUCT, applies instead of calling the environment, and uses to expand the new leaf. Backpropagation incorporates each edge’s predicted reward. For a single agent, a one-transition backup can be written
Here is a predicted continuation added by the reduced lab; it is not presented as a literal reproduction of every published MuZero head. In zero-sum games the child term changes sign. A reward or continuation error affects all backups passing through that branch.
When reward scale varies, value may dominate or be eclipsed by the prior bonus. Search can normalize observed values as if range is positive. Without a range yet, a finite convention is required. Normalization does not fix a wrong model, and extrema can change during search.
Suppose the only observed evaluations are 20 and 40. Normalization maps them to 0 and 1 before adding exploration bonus, so comparison does not depend on their units of tens. If only one value has been seen, dividing by zero range would be nonfinite. The program uses zero for that initial case and unvisited edges. This is one convention: other implementations may use different initial values or known ranges, so their first visits need not match.
Search alternates two kinds of information. At the root receives a real observation; deeper down generates latents without consulting the environment again. An imagined leaf’s prior and value come from , while intermediate rewards come from . A deeper trajectory can reveal a plan missed by immediate evaluation but accumulates more opportunities for error. Compare horizons and check chosen actions against the environment to distinguish extra computation from unwarranted confidence.
Points are the first two coordinates of states generated by the trained network, not a projection of physical positions. Branches are CartPole’s two actions. Each step shows counts and normalized after simulation, plus rewards, continuations, and values actually backed up in that simulation. Search extrema include edges across the visited tree, not just the root’s two children. The figure replays a saved trace; it does not invent an ideal tree.
In Connect Four, code applies the legal-column mask at the root where the real board is available. Within the reduced latent tree it permits all seven actions because it learns no legality head; it may imagine impossible actions. This is an important implementation limitation. Actions executed in the environment again pass the real mask. Adding legality prediction or restricting actions using known rules would be a different extension.
Scale values and reanalyze data
The value transformation compresses positive and negative magnitudes using
It is monotone and invertible. To represent a scalar target, transform it, locate it between two neighboring support atoms, and assign linear weights summing to one. The network predicts logits and trains with cross-entropy. To read them, average atoms on the transformed scale and apply . Due to nonlinearity, transforming the average is generally not equivalent to averaging already inverted values.
The figure and lab use integer support from −10 to 10 and clip transformed targets outside it. Within support, two weights exactly recover transformed value; after clipping the original value is not recovered. Figure gradients correspond to squared losses with respect to scalar outputs on their respective scales, not categorical-logit gradients. Original work used larger support for Atari; small bounds here are a cost choice.
If the transformed target is 2.3, encoding assigns 0.7 to atom 2 and 0.3 to atom 3. Their mean is 2.3 and only then is the inverse applied to return to original units. Cross-entropy fits a distribution, so its per-logit gradient depends on predicted probability minus target weight. The figure’s curve compares another mechanism: how a squared-loss gradient changes when the scalar target is compressed. Both illustrate scale but their derivatives concern different parameters.
Reanalyse searches again from stored observations with the current model and replaces old search targets. It does not change observed rewards or create new real transitions. MuZero Unplugged studies online use for data efficiency and offline learning from a fixed set. Offline, searching outside actions covered by data can exploit model errors; repeating search alone does not remove this problem.
Published results were obtained on Go, chess, shogi, and Atari with budgets and architectures far larger than this example. Simulation count changes compute and search quality, but one performance curve does not prove more search compensates for every model error. For an ablation, fix observations, training, time or sample budget and specify which variable changes.
Lab: two real domains
The experiment uses two distinct environments: CartPole-v1 state observations and a Connect Four board. It implements , , , categorical targets, latent PUCT, learned reward and continuation, scaled gradients, episode replay, and optional Reanalyse. It does not reconstruct pixels. This small version has an additional continuation head and lacks the paper’s architecture, resources, and full training rules.
With ORYON_QUICK=1, two episodes per domain are collected, eight simulations and 14 updates per model are used, and two episodes or games are evaluated. ORYON_QUICK=0 proposes 30 episodes, 50 simulations, and 600 updates per domain; that budget has not been run here. ORYON_REANALYSE=0 disables target updates and ORYON_MZ_SEED fixes the seed. CartPole limits are 64 steps in both example configurations.
This prototype’s collection samples visits without root Dirichlet noise. One model is updated per domain and search uses predicted continuous continuation, so no exact terminal detector exists in the dream. Real interaction does use environment termination and truncation signals. In Connect Four, alternating perspective applies to value targets and backups; confusing it would make an opponent’s win look favorable.
For the Connect Four comparison, the first cell prepares AlphaZero code from the previous lesson. If ORYON_C4_BASELINE points to an existing checkpoint it reuses it; otherwise it trains a reference in the output folder. Implementation budgets differ, so the match is an integration test, not a fair efficiency comparison. ORYON_MZ_OUT controls model and report folder. Install PyTorch, NumPy, and Gymnasium classic-control locally.
from pathlib import Path
import os, subprocess, sys
script_dir=Path(os.getenv('ORYON_MZ_OUT','oryon-muzero')).resolve()/'scripts'
script_dir.mkdir(parents=True,exist_ok=True)
script=script_dir/'az_connect4.py'
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')
root=Path(os.getenv('ORYON_MZ_OUT','oryon-muzero')).resolve()
quick=os.getenv('ORYON_QUICK','1')=='1'
baseline=Path(os.getenv('ORYON_C4_BASELINE',str(root/'az-baseline'/('c4-round2.pt' if quick else 'c4-round20.pt')))).resolve()
if not baseline.exists():
env={**os.environ,'PYTHONIOENCODING':'utf-8','ORYON_C4_OUT':str(baseline.parent)}
result=subprocess.run([sys.executable,str(script)],capture_output=True,text=True,encoding='utf-8',errors='replace',env=env)
print(result.stdout)
if result.returncode:raise RuntimeError(result.stderr[-3000:])
print('Checkpoint de referencia:',baseline)npm run lab and open the connection link.The next cell collects real transitions before model fitting. Value target uses up to five rewards and a search bootstrap value. Reanalyse updates the first trajectory while retaining actions and rewards, and additional updates run. The report logs losses, targets before and after, duration, CUDA memory, and evaluation. For CartPole truncations the final-observation bootstrap comes from the value head, not new search.
from pathlib import Path
import os, subprocess, sys
script_dir=Path(os.getenv('ORYON_MZ_OUT','oryon-muzero')).resolve()/'scripts'
script_dir.mkdir(parents=True,exist_ok=True)
script=script_dir/'muzero_lab.py'
script.write_text(r'''import json, math, os, random, time
from pathlib import Path
import gymnasium as gym
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
import az_connect4 as az
EPS=.001;SUPPORT=10;ATOMS=2*SUPPORT+1
def transform(x):return torch.sign(x)*(torch.sqrt(torch.abs(x)+1)-1)+EPS*x
def inverse(y):
return torch.sign(y)*(((torch.sqrt(1+4*EPS*(torch.abs(y)+1+EPS))-1)/(2*EPS))**2-1)
def twohot(x):
y=transform(x).clamp(-SUPPORT,SUPPORT).reshape(-1)+SUPPORT
lo=y.floor().long();hi=(lo+1).clamp_max(ATOMS-1);frac=y-lo
out=torch.zeros((len(y),ATOMS),device=x.device)
out.scatter_(1,lo[:,None],(1-frac)[:,None]);out.scatter_add_(1,hi[:,None],frac[:,None])
return out
def ce(logits,target):return -(twohot(target)*F.log_softmax(logits,-1)).sum(-1).mean()
def read(logits):
atoms=torch.arange(-SUPPORT,SUPPORT+1,device=logits.device,dtype=logits.dtype)
return inverse((logits.softmax(-1)*atoms).sum(-1))
def scale_gradient(x,scale):return x.detach()+(x-x.detach())*scale
def normalize(x):
low=x.min(-1,keepdim=True).values;high=x.max(-1,keepdim=True).values
return (x-low)/(high-low).clamp_min(1e-5)
class Model(nn.Module):
def __init__(self,obs,actions,width=64):
super().__init__();self.actions=actions;self.width=width
self.rep=nn.Linear(obs,width);self.dyn=nn.Linear(width+actions,width)
self.reward=nn.Linear(width,ATOMS);self.cont=nn.Linear(width,1)
self.policy=nn.Linear(width,actions);self.value=nn.Linear(width,ATOMS)
def h(self,obs):return normalize(F.relu(self.rep(obs)))
def g(self,state,action,scale=1.):
state=scale_gradient(state,scale)
one=F.one_hot(action,self.actions).float()
nxt=normalize(F.relu(self.dyn(torch.cat((state,one),-1))))
return nxt,self.reward(nxt),self.cont(nxt).squeeze(-1)
def f(self,state):return self.policy(state),self.value(state)
class Node:
def __init__(self,state,prior,value,reward=0.,continuation=1.):
self.state=state;self.prior=prior;self.value=value;self.reward=reward;self.continuation=continuation
self.n=np.zeros(len(prior),int);self.w=np.zeros(len(prior));self.children={}
def evaluate_state(model,state,legal):
with torch.no_grad():
logits,value=model.f(state);mask=torch.as_tensor(legal,device=state.device,dtype=torch.bool)[None]
prior=F.softmax(logits.masked_fill(~mask,-1e9),-1)[0].cpu().numpy()
v=float(read(value)[0].cpu())
return prior,v
def search(model,observation,legal,sims,gamma,sign,device,capture=False):
with torch.no_grad():state=model.h(torch.as_tensor(observation,dtype=torch.float32,device=device)[None])
prior,initial=evaluate_state(model,state,legal);root=Node(state,prior,initial);root.snapshots=[];qmin=math.inf;qmax=-math.inf
for simulation in range(sims):
node=root;path=[]
while True:
q=np.divide(node.w,node.n,out=np.zeros_like(node.w),where=node.n>0)
if qmax>qmin:qnorm=np.where(node.n>0,(q-qmin)/(qmax-qmin),0.)
else:qnorm=np.zeros_like(q)
score=qnorm+1.5*node.prior*math.sqrt(1+node.n.sum())/(1+node.n)
allowed=legal if node is root else np.ones(model.actions,bool)
a=int(np.argmax(np.where(allowed,score,-np.inf)));path.append((node,a))
if a not in node.children:
with torch.no_grad():
nxt,r,c=model.g(node.state,torch.tensor([a],device=device))
reward=float(read(r)[0].cpu());cont=float(torch.sigmoid(c)[0].cpu())
childprior,childvalue=evaluate_state(model,nxt,np.ones(model.actions,bool))
child=Node(nxt,childprior,childvalue,reward,cont);node.children[a]=child;v=child.value;break
node=node.children[a]
backup=[]
for parent,a in reversed(path):
child=parent.children[a];child_value=v;v=child.reward+gamma*sign*child.continuation*v
parent.n[a]+=1;parent.w[a]+=v;q=parent.w[a]/parent.n[a];qmin=min(qmin,q);qmax=max(qmax,q)
if capture:backup.append({'action':a,'reward':child.reward,'continuation':child.continuation,'child_value':child_value,'backed':v})
if capture:
nodes=[]
for a,child in root.children.items():
q=float(root.w[a]/root.n[a])
nodes.append({'action':a,'latent':child.state[0,:2].cpu().tolist(),'prior':float(root.prior[a]),
'visits':int(root.n[a]),'q':q,'qnorm':(q-qmin)/(qmax-qmin) if qmax>qmin else 0.,
'reward':child.reward,'continuation':child.continuation})
root.snapshots.append({'simulation':simulation+1,'selected':path[0][1],'nodes':nodes,'backup':backup,
'qmin':qmin,'qmax':qmax})
visits=root.n.astype(float);pi=visits/visits.sum()
root_value=float(root.w.sum()/root.n.sum())
return pi,root_value,root
def c4_observation(p,m):return az.planes(p,m).reshape(-1)
def c4_legal(m):
mask=np.zeros(7,bool);mask[az.legal(m)]=True;return mask
def collect(model,domain,sims,seed,device):
rng=np.random.default_rng(seed);trajectory=[];gamma=.99;sign=-1 if domain=='connect4' else 1
if domain=='cartpole':
env=gym.make('CartPole-v1',max_episode_steps=64);obs,_=env.reset(seed=seed);p=m=0
else:env=None;p=m=0;obs=c4_observation(p,m)
try:
while True:
mask=np.ones(2,bool) if domain=='cartpole' else c4_legal(m)
pi,v,root=search(model,obs,mask,sims,gamma,sign,device)
action=int(rng.choice(len(pi),p=pi))
if env is not None:
nxt,r,term,trunc,_=env.step(action);reward=float(r)
else:
p,m=az.move(p,m,action);result=az.end(p,m);term=result is not None;trunc=False
reward=1. if result==-1 else 0.;nxt=c4_observation(p,m)
trajectory.append({'obs':np.asarray(obs,np.float32),'legal':mask,'action':action,'reward':reward,
'terminated':bool(term),'truncated':bool(trunc),'pi':pi,'search_value':v})
obs=nxt
if term or trunc:break
return trajectory,np.asarray(obs,np.float32)
finally:
if env is not None:env.close()
def value_target(trajectory,final_obs,index,n,gamma,sign,model,device):
result=0.;factor=1.;T=len(trajectory)
for j in range(index,min(index+n,T)):
step=trajectory[j];result+=factor*step['reward'];factor*=gamma*sign
if step['terminated']:return result
if step['truncated']:
with torch.no_grad():
s=model.h(torch.as_tensor(final_obs,device=device,dtype=torch.float32)[None]);_,v=model.f(s)
return result+factor*float(read(v)[0].cpu())
if index+n<T:return result+factor*trajectory[index+n]['search_value']
return result
def train(model,episodes,optimizer,device,rng,domain,updates,K=3,n=5):
gamma=.99;sign=-1 if domain=='connect4' else 1;history=[]
for update in range(updates):
trajectory,final=episodes[int(rng.integers(len(episodes)))];start=int(rng.integers(len(trajectory)))
state=model.h(torch.as_tensor(trajectory[start]['obs'],device=device)[None]);loss=torch.tensor(0.,device=device)
for k in range(K+1):
i=start+k
if i>=len(trajectory):break
item=trajectory[i];logits,value=model.f(state)
legal=torch.as_tensor(item['legal'],device=device)[None];target=torch.as_tensor(item['pi'],device=device,dtype=torch.float32)[None]
policy=-(target*F.log_softmax(logits.masked_fill(~legal,-1e9),-1)).sum(-1).mean()
z=value_target(trajectory,final,i,n,gamma,sign,model,device)
vl=ce(value,torch.tensor([z],device=device));loss=loss+(policy+vl)/(K+1)
if k==K:break
action=torch.tensor([item['action']],device=device)
state,reward,continuation=model.g(state,action,scale=.5)
rl=ce(reward,torch.tensor([item['reward']],device=device))
cl=F.binary_cross_entropy_with_logits(continuation,torch.tensor([1.-float(item['terminated'])],device=device))
loss=loss+(rl+cl)/(K+1)
if item['terminated'] or item['truncated']:break
optimizer.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),10.);optimizer.step()
if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
history.append(float(loss.detach()))
return history
def reanalyse(model,episode,device,domain,sims):
trajectory,_=episode;sign=-1 if domain=='connect4' else 1
before=[(row['reward'],row['action'],row['terminated'],row['truncated']) for row in trajectory]
for row in trajectory:
pi,v,_=search(model,row['obs'],row['legal'],sims,.99,sign,device)
row['pi']=pi;row['search_value']=v
assert before==[(row['reward'],row['action'],row['terminated'],row['truncated']) for row in trajectory]
def evaluate_cartpole(model,device,sims,seed):
env=gym.make('CartPole-v1',max_episode_steps=64);results=[]
try:
for i in range(2):
obs,_=env.reset(seed=100000+seed*100+i);total=0.;length=0
while True:
pi,_,_=search(model,obs,np.ones(2,bool),sims,.99,1,device)
obs,r,term,trunc,_=env.step(int(np.argmax(pi)));total+=float(r);length+=1
if term or trunc:break
results.append({'return':total,'length':length,'terminated':bool(term),'truncated':bool(trunc)})
finally:env.close()
return results
def compare_c4(model,device,sims,baseline):
ck=torch.load(baseline,map_location=device,weights_only=True);other=az.Network(ck['width'],ck['blocks']).to(device)
other.load_state_dict(ck['state_dict']);other.eval()
def infer(p,m):
with torch.no_grad():
logits,v=other(torch.tensor(az.planes(p,m)[None],device=device));mask=torch.tensor(c4_legal(m),device=device)[None]
prior=F.softmax(logits.masked_fill(~mask,-1e9),-1)[0].cpu().numpy()
return prior,float(v.item())
results=[]
for mz_first in (True,False):
p=m=0;turn=0
while az.end(p,m) is None:
is_mz=(turn%2==0)==mz_first
if is_mz:
pi,_,_=search(model,c4_observation(p,m),c4_legal(m),sims,.99,-1,device);a=int(np.argmax(pi))
else:a=int(np.argmax(az.search(az.Node(p,m),sims,infer)))
p,m=az.move(p,m,a);turn+=1
result=az.end(p,m);winner_mz=None if result==0 else ((turn-1)%2==0)==mz_first
results.append({'muzero_first':mz_first,'moves':turn,'result':0 if winner_mz is None else 1 if winner_mz else -1})
return results
def main():
quick=os.getenv('ORYON_QUICK','1')=='1';use_reanalyse=os.getenv('ORYON_REANALYSE','1')=='1';seed=int(os.getenv('ORYON_MZ_SEED','0'))
root=Path(os.getenv('ORYON_MZ_OUT','oryon-muzero'));root.mkdir(parents=True,exist_ok=True)
baseline=Path(os.environ['ORYON_C4_BASELINE'])
np.random.seed(seed);random.seed(seed);torch.manual_seed(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()
rng=np.random.default_rng(seed);sims=8 if quick else 50;games=2 if quick else 30;updates=12 if quick else 500
reports={}
for domain,obsdim,actions in (('cartpole',4,2),('connect4',84,7)):
model=Model(obsdim,actions).to(device);optimizer=torch.optim.Adam(model.parameters(),lr=1e-3)
start=time.perf_counter();episodes=[collect(model,domain,sims,seed+100*i,device) for i in range(games)]
losses=train(model,episodes,optimizer,device,rng,domain,updates)
before=episodes[0][0][0]['pi'].copy()
if use_reanalyse:reanalyse(model,episodes[0],device,domain,sims)
after=episodes[0][0][0]['pi'].copy()
final_loss=train(model,episodes,optimizer,device,rng,domain,2 if quick else 100)
test=evaluate_cartpole(model,device,sims,seed) if domain=='cartpole' else compare_c4(model,device,sims,baseline)
data={'episodes':games,'sims':sims,'updates':updates+len(final_loss),'reanalyse':use_reanalyse,'loss_first':losses[0],'loss_last':final_loss[-1],
'reanalyse_before':before.tolist(),'reanalyse_after':after.tolist(),'evaluation':test,
'seconds':time.perf_counter()-start}
reports[domain]=data
torch.save({'state_dict':model.state_dict(),'obs':obsdim,'actions':actions,'width':64,'domain':domain,
'seed':seed,'quick':quick},root/f'muzero-{domain}.pt')
trace=episodes[0][0]
with torch.no_grad():
s=model.h(torch.as_tensor(trace[0]['obs'],device=device)[None]);pi,_,node=search(model,trace[0]['obs'],trace[0]['legal'],sims,.99,-1 if domain=='connect4' else 1,device,capture=True)
states=[]; rewards=[]
for row in trace[:4]:
nxt,r,c=model.g(s,torch.tensor([row['action']],device=device));states.append(s[0,:2].cpu().tolist());rewards.append(float(read(r)[0].cpu()));s=nxt
serial=[{'obs':row['obs'].tolist(),'action':row['action'],'reward':row['reward'],'terminated':row['terminated'],
'truncated':row['truncated'],'pi':row['pi'].tolist(),'search_value':row['search_value']} for row in trace]
(root/f'trace-{domain}.json').write_text(json.dumps({'steps':serial,'latent_first2':states,'predicted_rewards':rewards,
'gamma':.99,'n':5,'domain':domain,'tree_root':node.state[0,:2].cpu().tolist(),
'tree_snapshots':node.snapshots},indent=2,allow_nan=False),encoding='utf-8')
print(domain,data,flush=True)
result={'seed':seed,'quick':quick,'device':str(device),'torch':torch.__version__,'gymnasium':gym.__version__,
'numpy':np.__version__,'peak_cuda_gib':torch.cuda.max_memory_allocated()/1024**3 if device.type=='cuda' else None,
'domains':reports}
(root/'muzero-report.json').write_text(json.dumps(result,indent=2,allow_nan=False),encoding='utf-8')
print('Reporte',result)
if __name__=='__main__':main()''',encoding='utf-8')
root=Path(os.getenv('ORYON_MZ_OUT','oryon-muzero')).resolve()
quick=os.getenv('ORYON_QUICK','1')=='1'
baseline=Path(os.getenv('ORYON_C4_BASELINE',str(root/'az-baseline'/('c4-round2.pt' if quick else 'c4-round20.pt')))).resolve()
env={**os.environ,'PYTHONIOENCODING':'utf-8','ORYON_C4_BASELINE':str(baseline),'ORYON_MZ_OUT':str(root)}
result=subprocess.run([sys.executable,str(script)],capture_output=True,text=True,encoding='utf-8',errors='replace',env=env)
print(result.stdout)
if result.returncode:raise RuntimeError(result.stderr[-3000:])npm run lab and open the connection link.In one real short run, CartPole achieved returns 31 and 15 in two episodes. In Connect Four, MuZero lost one game and won another against a similarly reduced AlphaZero checkpoint. Two episodes or games do not establish superiority. Loss changes depend on sampled batches and do not prove model fidelity outside replay.
Lab: two mctx searches
The cell copies the CartPole checkpoint to JAX and runs mctx muzero_policy and gumbel_muzero_policy alongside custom search. It uses the same model and evaluation seeds, eight simulations in short mode, and JAX on CPU. It first compares JAX outputs and transitions with PyTorch; implementations use different selection rules and transformations. Initial compilation and episode times are reported separately. Episodes can differ in length, so total time is not a per-step comparison either.
Install mctx==0.0.71, jax==0.12.0.1, jaxlib==0.12.0.1 and compatible dependencies in an isolated environment with PyTorch, NumPy, and Gymnasium. The tested configuration uses JAX on CPU; the first implementation may use CUDA if available. The full 50-simulation comparison has not been run here.
from pathlib import Path
import os, subprocess, sys
script_dir=Path(os.getenv('ORYON_MZ_OUT','oryon-muzero')).resolve()/'scripts'
script_dir.mkdir(parents=True,exist_ok=True)
script=script_dir/'mctx_muzero.py'
script.write_text(r'''import json, os, time
from pathlib import Path
import numpy as np
import gymnasium as gym
import torch
import jax
import jax.numpy as jnp
import mctx
jax.config.update('jax_platform_name','cpu')
from muzero_lab import Model,search
rootdir=Path(os.getenv('ORYON_MZ_OUT','oryon-muzero'));checkpoint=torch.load(rootdir/'muzero-cartpole.pt',map_location='cpu',weights_only=True)
model=Model(checkpoint['obs'],checkpoint['actions'],checkpoint['width']);model.load_state_dict(checkpoint['state_dict']);model.eval();torch.set_num_threads(1)
params={k:jnp.asarray(v.detach().numpy()) for k,v in model.state_dict().items()}
def dense(x,key):return x@params[key+'.weight'].T+params[key+'.bias']
def norm(x):return (x-jnp.min(x,axis=-1,keepdims=True))/jnp.maximum(jnp.max(x,axis=-1,keepdims=True)-jnp.min(x,axis=-1,keepdims=True),1e-5)
def h(obs):return norm(jax.nn.relu(dense(obs,'rep')))
def scalar(logits):
y=jnp.sum(jax.nn.softmax(logits)*jnp.arange(-10,11,dtype=jnp.float32),axis=-1);e=.001
return jnp.sign(y)*(((jnp.sqrt(1+4*e*(jnp.abs(y)+1+e))-1)/(2*e))**2-1)
def prediction(state):return dense(state,'policy'),scalar(dense(state,'value'))
def dynamics(state,action):
x=jnp.concatenate((state,jax.nn.one_hot(action,2)),axis=-1)
nxt=norm(jax.nn.relu(dense(x,'dyn')));reward=scalar(dense(nxt,'reward'));cont=jax.nn.sigmoid(dense(nxt,'cont')[:,0])
return nxt,reward,cont
def recurrent(unused,key,action,state):
nxt,reward,cont=dynamics(state,action);logits,value=prediction(nxt)
return mctx.RecurrentFnOutput(reward=reward,discount=.99*cont,prior_logits=logits,value=value),nxt
def root(obs):
state=h(obs);logits,value=prediction(state)
return mctx.RootFnOutput(prior_logits=logits,value=value,embedding=state)
quick=os.getenv('ORYON_QUICK','1')=='1';sims=8 if quick else 50
@jax.jit
def ordinary(obs,key):return mctx.muzero_policy(None,key,root(obs),recurrent,num_simulations=sims,dirichlet_fraction=0.,temperature=0.)
@jax.jit
def gumbel(obs,key):return mctx.gumbel_muzero_policy(None,key,root(obs),recurrent,num_simulations=sims,gumbel_scale=0.)
# Compara funciones y transiciones con el modelo cargado de PyTorch.
trace=json.loads((rootdir/'trace-cartpole.json').read_text(encoding='utf8'))
obs=np.array([row['obs'] for row in trace['steps'][:4]],np.float32);actions=np.array([row['action'] for row in trace['steps'][:4]],np.int32)
with torch.no_grad():
tstate=model.h(torch.tensor(obs));tlogits,tvalue=model.f(tstate);tnext,treward,tcont=model.g(tstate,torch.tensor(actions,dtype=torch.long))
jstate=h(jnp.asarray(obs));jlogits,jvalue=prediction(jstate);jnext,jreward,jcont=dynamics(jstate,jnp.asarray(actions))
np.testing.assert_allclose(np.asarray(jstate),tstate.numpy(),atol=2e-6,rtol=2e-5)
np.testing.assert_allclose(np.asarray(jlogits),tlogits.numpy(),atol=2e-6,rtol=2e-5)
np.testing.assert_allclose(np.asarray(jnext),tnext.numpy(),atol=2e-6,rtol=2e-5)
from muzero_lab import read
np.testing.assert_allclose(np.asarray(jvalue),read(tvalue).numpy(),atol=2e-3,rtol=2e-3)
np.testing.assert_allclose(np.asarray(jreward),read(treward).numpy(),atol=2e-3,rtol=2e-3)
np.testing.assert_allclose(np.asarray(jcont),torch.sigmoid(tcont).numpy(),atol=2e-6,rtol=2e-5)
start=time.perf_counter();ordinary(jnp.asarray(obs[:1]),jax.random.PRNGKey(0)).action.block_until_ready();compile_ordinary=time.perf_counter()-start
start=time.perf_counter();gumbel(jnp.asarray(obs[:1]),jax.random.PRNGKey(0)).action.block_until_ready();compile_gumbel=time.perf_counter()-start
results={}
for name in ('propio','muzero_policy','gumbel_muzero_policy'):
env=gym.make('CartPole-v1',max_episode_steps=64);returns=[];started=time.perf_counter()
try:
for ep in range(2):
state,_=env.reset(seed=200000+ep);total=0.;steps=0
while True:
if name=='propio':action=int(np.argmax(search(model,state,np.ones(2,bool),sims,.99,1,torch.device('cpu'))[0]))
else:
fn=ordinary if name=='muzero_policy' else gumbel
action=int(np.asarray(fn(jnp.asarray(state[None]),jax.random.PRNGKey(1000*ep+steps)).action)[0])
state,r,term,trunc,_=env.step(action);total+=float(r);steps+=1
if term or trunc:break
returns.append({'return':total,'length':steps,'terminated':bool(term),'truncated':bool(trunc)})
finally:env.close()
results[name]={'episodes':returns,'seconds':time.perf_counter()-started}
report={'device':str(jax.devices()[0]),'mctx':mctx.__version__,'jax':jax.__version__,'sims':sims,
'compile_ordinary_seconds':compile_ordinary,'compile_gumbel_seconds':compile_gumbel,'results':results,
'caution':'Mismo modelo, entornos y semillas; selección/Q distinta y solo dos episodios por método.'}
(rootdir/'mctx-muzero.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf8')
print('Comparación',report)''',encoding='utf-8')
root=Path(os.getenv('ORYON_MZ_OUT','oryon-muzero')).resolve()
quick=os.getenv('ORYON_QUICK','1')=='1'
baseline=Path(os.getenv('ORYON_C4_BASELINE',str(root/'az-baseline'/('c4-round2.pt' if quick else 'c4-round20.pt')))).resolve()
env={**os.environ,'PYTHONIOENCODING':'utf-8','ORYON_C4_BASELINE':str(baseline),'ORYON_MZ_OUT':str(root)}
result=subprocess.run([sys.executable,str(script)],capture_output=True,text=True,encoding='utf-8',errors='replace',env=env)
print(result.stdout)
if result.returncode:raise RuntimeError(result.stderr[-3000:])npm run lab and open the connection link.Custom search uses mean visits and the example’s min-max normalization; mctx policies have their own selection details. Gumbel runs with zero noise scale in evaluation for reproducibility. All three policies use the same checkpoint, but two episodes per method and one device cannot establish a general strength or speed difference.
Exercises
Step 1 of 4. What equality holds for each action when applying operators to V*?
import numpy as np
def h(x):
pass
def h_inv(y):
pass
def encode(x, low, high):
pass