Frontier of the AlphaZero line: Gumbel, sampled MCTS, EfficientZero and algorithm discovery
Examine developments after MuZero: MCTS as regularized optimization, Gumbel AlphaZero, Sampled MuZero, Stochastic MuZero, EfficientZero, and learned search for discovery in AlphaTensor, AlphaDev, and formal proof. Identify open questions and limitations in imperfect information.
After this lesson you can
- Explain MCTS as an approximation to KL-regularized policy optimization.
- Implement Gumbel AlphaZero root selection with sequential halving and compare it with PUCT.
- Describe how Sampled MuZero and Stochastic MuZero address large action spaces and randomness.
- Formulate discovery as a single-player game in the style of AlphaTensor.
- Critically distinguish detailed published results from announcements.
Before you start
Search with fewer simulations and more problem types
The AlphaZero and MuZero line combines a learned policy with search. This raises questions: what if only a few simulations fit, how should search handle continuous actions or chance, and can the environment be an algorithm-discovery problem? Later answers change specific system components and must be compared with their budgets, not method names alone.
Search improvement is approximate. A poor prior may leave a promising action unexplored, and learned evaluation can misvalue even visited branches. A theoretical solution with exact values does not guarantee a network trained on finite data meets its assumptions. The following figures make those conditions visible in small problems.
Visits and regularized optimization
Grill and colleagues interpret MCTS selection as approximate regularized policy optimization. At a root with search values , prior , and action distribution , one formulation is
KL direction matters: the prior appears in the first argument. The penalty grows large if approaches zero while is positive. For , first-order conditions give
The last equation can be solved by binary search over . To relate this problem to PUCT, the figure uses smoothed visits and . The example index is thus . The paper uses a nearby convention with and one fictitious visit per action; the initial difference does not change the interpretive lesson.
The condition follows by introducing a multiplier for the probability sum. The derivative with respect to is ; setting it to zero gives the expression above. For , the fraction sum decreases as increases, so binary search finds normalization. The derivation uses positive prior and ; zero priors require careful handling of limits and boundary solutions.
The expression illustrates two forces: favors high-value actions and KL limits departure from the prior. Smaller permits more mass on high values. In the example changes with visit count, so two slider positions also represent two distinct regularized problems. Small distance between visits and solution does not prove correct; it compares distributions built from the same fixed numbers.
Prior and values of eight actions are fixed in this example. Each simulation increments the highest-indexed action’s count; the regularized optimum is recomputed with for the chosen budget. L1 distance measures distribution discrepancy, not agent strength. With few counts, discrete visits and initialization matter. In a real tree changes during exploration and the model may be wrong, so it does not follow that every search exactly solves optimization with true values.
Sample and reduce candidates
Gumbel AlphaZero addresses a small-budget problem: PUCT may repeatedly select prior-favored actions and never evaluate a better alternative. If are independent Gumbel variables and are logits, sorting and taking the largest samples without replacement from the corresponding categorical distribution.
Once candidates are selected, sequential halving distributes simulations among them and removes some less promising ones in successive rounds. With four candidates and 16 simulations, one allocation gives each two visits in round one and each survivor four in round two. Ranking combines Gumbel noise fixed for that search, logits, and a transformation of estimates. Budget and tie rules vary and must be declared.
The example is an eight-action deterministic bandit with hand-set values. Visiting an action reveals its exact . Cards show prior, noise, value, and visits; color marks survivors. The Gumbel indicator is the fraction of 500 seeds where chosen action value exceeds expected prior value. PUCT is deterministic in this configuration and its chosen value is shown. This fraction measures selection in one example, not a universal agent-improvement probability.
The paper by Danihelka and colleagues presents an improvement guarantee under conditions on action evaluation and the operator used. It cannot simply be transferred to approximate values, unconsidered actions, or a different implementation. The lab uses a teaching variant with completed for unvisited actions and simple scaling; it does not claim to reproduce every detail or the published algorithm’s guarantee.
The basic guarantee’s idea can be seen with exact values. Fix a noise sample and a top-k set containing action with the largest perturbed logit. Let maximize the same perturbed logit plus an increasing function . The score without value of is at least that of , while the score with value of is at least that of . Subtracting inequalities gives and, if is strictly increasing, . The same noise is reused in both choices; that coupling is essential to comparison.
Averaged over noise, follows the prior policy by Gumbel-max. This argument assumes exact candidate values and selection of the specified maximum. Sequential halving with noisy evaluations can discard an action due to an incorrect estimate; a learned model can also assign incorrect value. Thus the proof does not say every empirical result of an approximate implementation beats the prior in every state. Report observed differences with uncertainty and compute spent.
A complete target policy can combine logits and completed values instead of training only on nonzero visits. The rule completing unobserved values matters: using the mean of visited values is an approximation, not new information about those actions. Sampling without replacement helps distribute budget but does not make leaf estimates exact.
Large spaces, chance, and scarce data
Sampled MuZero handles huge or continuous action spaces by generating a finite candidate set and applying the improvement operator there. Proposal distribution and sampling corrections are part of the method; taking a few arbitrary actions and renormalizing does not automatically reproduce its results. If a useful region is rarely proposed, search may miss it. Progressive widening is another family increasing candidates as visits grow.
In continuous control, the probability of exactly repeating a real number may be practically zero. Enumerating all actions becomes infeasible; sampling candidates makes each node finite but adds an error source besides the value model. More candidates improve potential coverage while consuming evaluations. Changing the proposal may improve one region’s coverage and worsen another, so comparisons require recording sample count and generating distribution.
Stochastic MuZero separates agent choice from a chance variable using an afterstate and a model of possible outcomes. It can represent different transitions after the same action and search with chance nodes. A deterministic model predicting an average can hide risks or multimodal alternatives. Learned uncertainty may also be poorly calibrated, and partial observation requires representing available information rather than one hidden world sample.
EfficientZero studies data efficiency with three ingredients: self-supervised consistency loss between representations, reward-prefix prediction, and value-target correction accounting for trajectory age. It is not simply “MuZero with more simulations.” Its published evaluation should be read with its data budget, preprocessing, and evaluation.
These ingredients address different problems. Consistency provides a signal between imagined state and a representation of future observations without reconstructing every pixel. Reward prefix helps represent a sum across the unroll. Value correction addresses mismatch between old data and current policy. An ablation removing only one while holding other budgets fixed helps study its contribution; comparing a small implementation with a much larger published result isolates none.
Search for algorithms
Search for discovery can formulate a task as a single-player game. In AlphaTensor, state is a residual tensor and an action subtracts a rank-one tensor . If residual reaches zero, factors describe an exact bilinear algorithm. Fewer scalar products do not necessarily mean less real time: additions, memory, and hardware matter too.
The tensor corresponds to matrix multiplication , with four inputs per matrix and four outputs. The figure supplies seven Strassen factors and eight direct-algorithm factors in advance. Subtract them in any order and undo; reaching zero residual exactly verifies coefficients. Since the seven known factors are available, choosing them does not demonstrate autonomous discovery. The lab also verifies the identity using integer arithmetic.
Each tensor entry indicates how a product of an entry from the first matrix and one from the second contributes to an output. Factor represents a product of two linear combinations distributed among outputs according to . If factors sum to the target tensor, equality holds for all inputs, not just a matrix sample. Testing numerical products remains useful for code errors, but exact equality of all 64 coefficients is the decisive check for this construction.
AlphaTensor studied specific sizes and fields as well as performance objectives for particular hardware. Distinguish those published results from a general claim about every size or machine. AlphaDev searched for instruction-level sorting routines and measured performance under specific conditions; fewer instructions alone do not guarantee lower latency on every processor.
In formal proof, a verifier can check whether a sequence satisfies logical-system rules. An accepted proof is strong correctness evidence relative to verifier and assumptions, but search may consume substantial compute or be limited by available formalization. The same caution applies to language-model-guided search: more inference compute and more training are distinct resources to account for.
Imperfect-information games add difficulty: an agent cannot observe an opponent’s private state and must reason over information sets and strategies. Searching as though hidden cards were known can produce invalid or exploitable decisions. Student of Games combines learning and search with public information and strategic reasoning; perfect-information search does not automatically solve poker.
Lab: PUCT and Gumbel in Connect Four
The first program reuses the previous lesson’s network and rules. It starts all six variants from the same initial checkpoint and runs PUCT or simplified Gumbel selection with budgets 2, 8, and 32. Gumbel’s target policy fills unvisited values with the mean of visited ones and applies softmax to logits plus those values. Candidate count is a power of two no greater than budget or legal actions.
With ORYON_QUICK=1 each variant collects two games, performs ten updates, and plays two games against the initial checkpoint. Code uses CPU to make individual calls comparable. ORYON_QUICK=0 proposes 40 games and 200 updates per variant; that budget has not been run. ORYON_FRONTIER_OUT controls output folder and ORYON_C4_INITIAL can provide the previous lesson’s initial checkpoint. Without it, the first cell creates an untrained one with seed 0. Install NumPy and PyTorch.
The match mixes training and selection changes: the initial opponent uses PUCT and the Gumbel variant uses its own selector. Two games neither separate effects nor establish a strength difference. The first variant may include optimizer and library initialization cost; measured seconds are not a stable speed evaluation.
from pathlib import Path
import os, subprocess, sys
root=Path(os.getenv('ORYON_FRONTIER_OUT','oryon-frontera')).resolve()
scripts=root/'scripts';scripts.mkdir(parents=True,exist_ok=True)
(scripts/'az_connect4.py').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')
(scripts/'c4_eval.py').write_text(r'''import json, os, time
from functools import lru_cache
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
from az_connect4 import Network,Node,search,move,end,planes,legal,four
@lru_cache(maxsize=None)
def exact(player,mask):
terminal=end(player,mask)
if terminal is not None:return int(terminal)
return max(-exact(*move(player,mask,a)) for a in legal(mask))
def scores(player,mask):return {a:-exact(*move(player,mask,a)) for a in legal(mask)}
def sample_late(rng,n,remaining=6):
found=[];attempts=0
while len(found)<n and attempts<20000:
attempts+=1;p=m=0
for _ in range(42-remaining):
candidates=[a for a in legal(m) if end(*move(p,m,a)) is None]
if not candidates:break
a=int(rng.choice(candidates));p,m=move(p,m,a)
if m.bit_count()==42-remaining and end(p,m) is None:found.append((p,m))
if len(found)<n:raise RuntimeError('No se generaron posiciones tardías suficientes')
return found
def load(path,device):
ck=torch.load(path,map_location=device,weights_only=True);model=Network(ck['width'],ck['blocks']).to(device)
model.load_state_dict(ck['state_dict']);model.eval();return model
def infer_fn(model,device):
def infer(p,m):
with torch.no_grad():
x=torch.tensor(planes(p,m)[None],device=device);logits,value=model(x)
valid=torch.zeros((1,7),dtype=torch.bool,device=device);valid[0,legal(m)]=True
prob=F.softmax(logits.masked_fill(~valid,-1e9),-1)[0].cpu().numpy()
return prob,float(value.item())
return infer
def play(infers,sims,first,opening):
p=m=0;turn=0;records=[]
for a in opening:p,m=move(p,m,a);turn+=1
while end(p,m) is None:
who=(first+turn)%2;root=Node(p,m);prior,value=infers[who](p,m)
count=search(root,sims,infers[who]);a=int(np.argmax(count))
records.append({'player':int(p),'mask':int(m),'who':who,'prior':prior.tolist(),
'visits':count.tolist(),'value':value,'action':a})
p,m=move(p,m,a);turn+=1
# El resultado terminal está expresado para el jugador que habría actuado.
result=end(p,m);winner=None if result==0 else (first+turn-1)%2
return (0.5 if winner is None else float(winner==1)),records
def elo(score):
# Corrección de medio punto por lado, explicitada; evita infinitos con muestras pequeñas.
rate=(sum(score)+.5)/(len(score)+1)
return 400*np.log10(rate/(1-rate))
def main():
root=Path(os.getenv('ORYON_C4_OUT','oryon-c4'));quick=os.getenv('ORYON_QUICK','1')=='1'
torch.set_num_threads(1);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model0=load(root/'c4-initial.pt',device);model1=load(root/f'c4-round{2 if quick else 20}.pt',device)
infers=[infer_fn(model0,device),infer_fn(model1,device)];rng=np.random.default_rng(8021)
games=4 if quick else 40;sims=8 if quick else 100;results=[];samples=[];openings=[]
for pair in range(games//2):
opening=rng.integers(0,7,size=2).tolist();openings.append(opening)
for first in (0,1):
score,trace=play(infers,sims,first,opening);results.append(score)
if pair==0 and first==0:samples=trace
print('pareja',pair,'inicio',opening,'primer checkpoint',first,'puntos final',score,'jugadas',len(trace),flush=True)
paired=np.asarray(results).reshape(-1,2)
bootstrap=np.array([elo(paired[rng.integers(len(paired),size=len(paired))].ravel()) for _ in range(1000)])
interval=None if np.ptp(bootstrap)==0 else np.quantile(bootstrap,[.025,.975]).tolist()
points=sample_late(rng,5 if quick else 30);evaluations=[]
for p,m in points:
truth=scores(p,m);visits=search(Node(p,m),sims,infers[1]);a=int(np.argmax(visits))
evaluations.append({'player':p,'mask':m,'optimal_actions':[a for a,v in truth.items() if v==max(truth.values())],
'choice':a,'optimal':truth[a]==max(truth.values()),'scores':truth,'visits':visits.tolist()})
report={'games':games,'simulations':sims,'scores':results,'paired_openings':openings,'elo_difference':float(elo(results)),
'bootstrap_95':interval,'bootstrap_degenerate':interval is None,'solver_remaining':6,
'solver_positions':evaluations,'optimal_fraction':float(np.mean([r['optimal'] for r in evaluations])),
'device':str(device),'torch':torch.__version__,'numpy':np.__version__}
(root/'evaluation.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
(root/'sample-game.json').write_text(json.dumps(samples,indent=2,allow_nan=False),encoding='utf-8')
print('Evaluación',report)
if __name__=='__main__':main()''',encoding='utf-8')
(scripts/'gumbel_lab.py').write_text(r'''import json, math, os, time
from pathlib import Path
import numpy as np
import torch
import az_connect4 as az
from c4_eval import load,infer_fn
def softmax(x):
y=np.exp(x-np.max(x));return y/y.sum()
def halving(logits,q_fn,budget,k,rng,gumbel=True):
legal=np.flatnonzero(np.isfinite(logits));k=min(k,budget,len(legal))
if k<1:raise ValueError('No hay presupuesto o acciones')
noise=rng.gumbel(size=len(logits)) if gumbel else np.zeros(len(logits))
active=sorted(legal,key=lambda a:-(logits[a]+noise[a]))[:k]
counts=np.zeros(len(logits),int);sums=np.zeros(len(logits));rounds=[];left=budget
while len(active)>1 and left:
stages=math.ceil(math.log2(len(active)))
each=max(1,left//(len(active)*stages))
for a in active:
for _ in range(min(each,left)):
sums[a]+=q_fn(int(a));counts[a]+=1;left-=1
if not left:break
if not left:break
means=np.divide(sums,counts,out=np.zeros_like(sums),where=counts>0)
active=sorted(active,key=lambda a:(-(logits[a]+noise[a]+means[a]),a))
rounds.append({'active':list(map(int,active)),'counts':counts.tolist()})
active=active[:math.ceil(len(active)/2)]
while left:
a=int(active[0]);sums[a]+=q_fn(a);counts[a]+=1;left-=1
return int(active[0]),counts,sums,rounds
def gumbel_search(root,infer,budget,rng,training):
if root.prior is None:az.expand(root,infer)
logits=np.where(root.prior>0,np.log(np.maximum(root.prior,1e-30)),-np.inf)
k=2**int(math.floor(math.log2(min(budget,len(az.legal(root.mask))))))
def visit(a):
if a not in root.children:
p,m=az.move(root.player,root.mask,a);root.children[a]=az.Node(p,m)
child=root.children[a]
if child.result is not None:value=-child.result
else:
before=float(child.w.sum());az.search(child,1,infer);value=-(float(child.w.sum())-before)
root.n[a]+=1;root.w[a]+=value;return value
action,counts,sums,rounds=halving(logits,visit,budget,k,rng,gumbel=training)
known=counts>0;mix=float(sums.sum()/counts.sum())
completed=np.where(known,np.divide(sums,counts,out=np.zeros_like(sums),where=known),mix)
target=np.zeros(7);allowed=az.legal(root.mask);target[allowed]=softmax(logits[allowed]+completed[allowed])
return action,target,counts
def select(root,infer,budget,method,rng,training):
if method=='puct':
counts=az.search(root,budget,infer,rng,.25 if training else 0.)
target=counts/counts.sum();action=int(rng.choice(7,p=target)) if training else int(np.argmax(counts))
else:action,target,counts=gumbel_search(root,infer,budget,rng,training)
return action,target,counts
def play_data(model,device,budget,method,rng):
infer=infer_fn(model,device);p=m=0;turn=0;trajectory=[]
while az.end(p,m) is None:
node=az.Node(p,m);a,pi,_=select(node,infer,budget,method,rng,True)
trajectory.append((p,m,pi,turn));p,m=az.move(p,m,a);turn+=1
final=az.end(p,m)
return [(p,m,pi,final*((-1)**(turn-t))) for p,m,pi,t in trajectory]
def game(infer0,infer1,budget,method,rng,first):
p=m=0;turn=0
while az.end(p,m) is None:
current=(first+turn)%2;root=az.Node(p,m)
a,_,_=select(root,(infer0,infer1)[current],budget,method if current==1 else 'puct',rng,False)
p,m=az.move(p,m,a);turn+=1
result=az.end(p,m);winner=None if result==0 else (first+turn-1)%2
return .5 if winner is None else float(winner==1)
def main():
torch.set_num_threads(1);quick=os.getenv('ORYON_QUICK','1')=='1';root=Path(os.getenv('ORYON_GUMBEL_OUT','oryon-gumbel'));root.mkdir(parents=True,exist_ok=True)
baseline=Path(os.environ['ORYON_C4_INITIAL']);device=torch.device('cpu');games=2 if quick else 40;updates=10 if quick else 200
results=[]
for budget in (2,8,32):
for method in ('puct','gumbel'):
torch.manual_seed(10);rng=np.random.default_rng(1000+budget);model=load(baseline,device);baseline_model=load(baseline,device)
started=time.perf_counter();data=[]
for _ in range(games):data.extend(play_data(model,device,budget,method,rng))
loss=az.train(model,device,data,updates,rng);model.eval();inferences=[infer_fn(baseline_model,device),infer_fn(model,device)]
scores=[game(*inferences,budget,method,rng,first) for first in (0,1)]
row={'method':method,'simulations':budget,'games':games,'positions':len(data),'updates':updates,
'policy_loss':loss['policy_loss'],'value_loss':loss['value_loss'],'scores_vs_initial':scores,
'seconds':time.perf_counter()-started,'device':str(device)}
results.append(row);print('experimento',row,flush=True)
(root/'gumbel-comparison.json').write_text(json.dumps(results,indent=2,allow_nan=False),encoding='utf8')
print('Resultados guardados',root)
if __name__=='__main__':main()''',encoding='utf-8')
initial=Path(os.getenv('ORYON_C4_INITIAL',str(root/'c4-initial.pt'))).resolve()
if not initial.exists():
initializer=scripts/'initial.py'
initializer.write_text("import torch, az_connect4 as az\ntorch.manual_seed(0)\nmodel=az.Network()\naz.save(model,"+repr(str(initial))+",{'round':0,'seed':0})\n",encoding='utf-8')
check=subprocess.run([sys.executable,str(initializer)],capture_output=True,text=True,encoding='utf-8',errors='replace')
if check.returncode:raise RuntimeError(check.stderr[-3000:])
env={**os.environ,'PYTHONIOENCODING':'utf-8','ORYON_C4_INITIAL':str(initial),'ORYON_GUMBEL_OUT':str(root)}
result=subprocess.run([sys.executable,str(scripts/'gumbel_lab.py')],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.Lab: a small tensor with demonstrations
The second cell exactly constructs tensor and fifteen discrete actions: seven Strassen factors and eight direct products. It trains a small policy–value network, first on demonstrations including the seven known factors and then with self-play and search. It checks that final residual is exactly zero and logs a random-search comparison.
This task is deliberately bounded: the action space already contains the solution and demonstrations reveal it. The network may learn to follow those factors; that does not prove it rediscovered Strassen from scratch or can search all possible vectors. The short run uses 20 demonstrations, 150 initial updates, three search episodes, and 30 later updates. The proposed long run has not been performed.
from pathlib import Path
import os, subprocess, sys
root=Path(os.getenv('ORYON_FRONTIER_OUT','oryon-frontera')).resolve()
scripts=root/'scripts';scripts.mkdir(parents=True,exist_ok=True)
script=scripts/'tensor_lab.py'
script.write_text(r'''import json,os,time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
# Orden de entradas: a11,a12,a21,a22 y b11,b12,b21,b22; salidas c11,c12,c21,c22.
S=[
([1,0,0,1],[1,0,0,1],[1,0,0,1]),
([0,0,1,1],[1,0,0,0],[0,0,1,-1]),
([1,0,0,0],[0,1,0,-1],[0,1,0,1]),
([0,0,0,1],[-1,0,1,0],[1,0,1,0]),
([1,1,0,0],[0,0,0,1],[-1,1,0,0]),
([-1,0,1,0],[1,1,0,0],[0,0,0,1]),
([0,1,0,-1],[0,0,1,1],[1,0,0,0]),
]
def tensor():
T=np.zeros((4,4,4),dtype=np.int8)
for i in range(2):
for j in range(2):
for k in range(2):T[2*i+k,2*k+j,2*i+j]=1
return T
def outer(u,v,w):return np.einsum('i,j,k->ijk',u,v,w).astype(np.int8)
def factors():
terms=[outer(*[np.array(x,dtype=np.int8) for x in triple]) for triple in S]
for a,b,c in np.argwhere(tensor()):
u=np.eye(4,dtype=np.int8)[a];v=np.eye(4,dtype=np.int8)[b];w=np.eye(4,dtype=np.int8)[c]
terms.append(outer(u,v,w))
return terms
TERMS=factors();T=tensor()
assert np.array_equal(sum(TERMS[:7]),T)
assert np.array_equal(sum(TERMS[7:]),T)
def features(residual,used):return np.concatenate((residual.ravel().astype(np.float32),used.astype(np.float32)))
class Net(nn.Module):
def __init__(self):
super().__init__();self.shared=nn.Sequential(nn.Linear(79,64),nn.ReLU(),nn.Linear(64,64),nn.ReLU())
self.policy=nn.Linear(64,15);self.value=nn.Linear(64,1)
def forward(self,x):
h=self.shared(x);return self.policy(h),torch.tanh(self.value(h)).squeeze(-1)
def prediction(net,residual,used):
with torch.no_grad():
logits,value=net(torch.tensor(features(residual,used))[None]);mask=torch.tensor(~used)[None]
p=F.softmax(logits.masked_fill(~mask,-1e9),-1)[0].numpy()
return p,float(value.item())
class Node:
def __init__(self,residual,used):
self.residual=residual;self.used=used;self.n=np.zeros(15,int);self.w=np.zeros(15);self.children={}
self.terminal=1. if not np.any(residual) else -1. if used.sum()>=7 else None
self.prior=None
def search(net,root,budget):
for _ in range(budget):
node=root;path=[]
while True:
if node.terminal is not None:v=node.terminal;break
if node.prior is None:
node.prior,v=prediction(net,node.residual,node.used);break
q=np.divide(node.w,node.n,out=np.zeros(15),where=node.n>0)
score=q+1.5*node.prior*np.sqrt(1+node.n.sum())/(1+node.n)
a=int(np.argmax(np.where(~node.used,score,-np.inf)));path.append((node,a))
if a not in node.children:
used=node.used.copy();used[a]=True;node.children[a]=Node(node.residual-TERMS[a],used)
node=node.children[a]
for parent,a in reversed(path):parent.n[a]+=1;parent.w[a]+=v
return root.n
def train(net,data,steps,rng):
opt=torch.optim.Adam(net.parameters(),lr=2e-3)
for _ in range(steps):
rows=[data[int(i)] for i in rng.integers(0,len(data),size=min(64,len(data)))]
x=torch.tensor(np.stack([r[0] for r in rows]));p=torch.tensor(np.stack([r[1] for r in rows]));z=torch.tensor([r[2] for r in rows],dtype=torch.float32)
logits,v=net(x);mask=torch.tensor(np.stack([r[3] for r in rows]))
loss=-(p*F.log_softmax(logits.masked_fill(~mask,-1e9),-1)).sum(-1).mean()+F.mse_loss(v,z)
opt.zero_grad();loss.backward();opt.step()
if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
return float(loss.detach())
def demo(rng):
residual=T.copy();used=np.zeros(15,bool);rows=[]
order=rng.permutation(7)
for action in order:
target=np.zeros(15,np.float32);target[[a for a in range(7) if not used[a]]]=1/(7-used[:7].sum())
rows.append((features(residual,used),target,1.,~used.copy()))
residual-=TERMS[action];used[action]=True
assert not np.any(residual)
return rows
def episode(net,budget,rng,random_action):
residual=T.copy();used=np.zeros(15,bool);history=[];actions=[]
for _ in range(7):
root=Node(residual.copy(),used.copy());counts=search(net,root,budget)
if counts.sum()==0:raise RuntimeError('Sin visitas')
pi=counts/counts.sum();a=int(rng.choice(15,p=pi)) if random_action else int(np.argmax(pi))
history.append((features(residual,used),pi.astype(np.float32),~used.copy()));actions.append(a)
residual-=TERMS[a];used[a]=True
if not np.any(residual):break
success=not np.any(residual)
return [(x,p,1. if success else -1.,mask) for x,p,mask in history],actions,residual
def main():
quick=os.getenv('ORYON_QUICK','1')=='1';root=Path(os.getenv('ORYON_TENSOR_OUT','oryon-tensor'));root.mkdir(parents=True,exist_ok=True)
seed=0;rng=np.random.default_rng(seed);torch.manual_seed(seed);torch.set_num_threads(1);net=Net()
data=[]
for _ in range(20 if quick else 200):data.extend(demo(rng))
demo_loss=train(net,data,150 if quick else 1000,rng)
generated=[];successes=0
for _ in range(3 if quick else 100):
rows,actions,residual=episode(net,16 if quick else 100,rng,True);data.extend(rows)
successes+=int(not np.any(residual));generated.append({'actions':actions,'residual_l1':int(np.abs(residual).sum())})
selfplay_loss=train(net,data,30 if quick else 500,rng)
rows,actions,residual=episode(net,32 if quick else 200,rng,False)
random_success=0
for _ in range(500 if quick else 10000):
choice=rng.choice(15,size=7,replace=False)
random_success+=int(not np.any(T-sum((TERMS[i] for i in choice))))
report={'seed':seed,'quick':quick,'demonstrations_include_strassen':True,'candidate_actions':15,
'demo_loss':demo_loss,'selfplay_loss':selfplay_loss,'selfplay':generated,'selfplay_successes':successes,
'evaluation_actions':actions,'evaluation_residual_l1':int(np.abs(residual).sum()),
'evaluation_exact':bool(not np.any(residual)),'random_trials':500 if quick else 10000,'random_successes':random_success}
(root/'tensor-report.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf8')
print('Resultado',report)
if __name__=='__main__':main()''',encoding='utf-8')
env={**os.environ,'PYTHONIOENCODING':'utf-8','ORYON_TENSOR_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 a short run all three self-play episodes and evaluation ended with zero residual using the seven provided factors; 500 random seven-factor samples did not produce zero residual. This shows the effect of supplied scaffolding, not discovery probability in the full space. The program verifies tensor equality before training; the identity was also checked here with 1000 independent integer products.
Exercises
Step 1 of 4. Which exponential variable corresponds to a Gumbel perturbed by logit ℓᵢ?
import numpy as np
def sequential_halving_root(logits, q_fn, budget, k, rng=None):
pass