written-binary-maze-solver / written_maze.py
ScAGI's picture
Publish hand-written binary maze solver and CUDA benchmark
81dfd31 verified
Raw History Blame Contribute Delete
5.05 kB
"""No learned parameters. Fixed local attention followed by layered signed threshold gates."""
import time
from collections import deque
import numpy as np
OFF=(( -1,0),(0,1),(1,0),(0,-1))
G={}
def reg(out, threshold, pos, neg=()):
assert not (set(pos)&set(neg)) and len(set(pos+neg))==len(pos+neg)
G[out]=(threshold,[(k,1) for k in pos]+[(k,-1) for k in neg])
reg("near",1,tuple("s"+str(i) for i in range(4)))
reg("new",2,("open","near"),("seen",))
for i in range(4):
reg("pick"+str(i),2,("new","s"+str(i)),tuple("s"+str(j) for j in range(i)))
reg("arrive"+str(i),2,("t"+str(i),"pc"+str(i)))
reg("born",2,("start","new"))
reg("next_seen",1,("seen","new"))
for i in range(4):
reg("next_parent"+str(i),1,("p"+str(i),"pick"+str(i)))
reg("next_tip",1,("born",)+tuple("arrive"+str(i) for i in range(4)))
reg("next_path",1,("path","next_tip"))
COMPILED={o:(theta,[(k,w) for k,w in terms]) for o,(theta,terms) in G.items()}
def eval_gate(o, x):
t,terms=COMPILED[o]
a=x[terms[0][0]].astype(np.int8)*terms[0][1]
for k,w in terms[1:]:
if w==1: a+=x[k]
else: np.subtract(a,x[k],out=a,casting='unsafe')
return a>=t
def head(x,i): # Fixed one-hot attention; no wrap, zero when outside the grid.
dy,dx=OFF[i]
h,w=x.shape
z=np.zeros_like(x)
dest_y=slice(max(0,-dy),min(h,h-dy)); dest_x=slice(max(0,-dx),min(w,w-dx))
src_y=slice(max(0,dy),min(h,h+dy)); src_x=slice(max(0,dx),min(w,w+dx))
z[dest_y,dest_x]=x[src_y,src_x]
return z
def solve(grid,start,goal):
sh=grid.shape
if not grid[start] or not grid[goal]: return None,0
x={k:np.zeros(sh,dtype=bool) for k in ('start','seen','tip','path','p0','p1','p2','p3')}
x['open']=grid
x['start'][start]=True; x['seen'][goal]=True
if start==goal: x['path'][start]=True; return x['path'],0
for n in range(1,2*grid.size+1):
for i in range(4):
x[f's{i}']=head(x['seen'],i)
x[f't{i}']=head(x['tip'],i)
x[f'pc{i}']=head(x[f'p{(i+2)%4}'],i)
for o in G: x[o]=eval_gate(o,x)
if x['next_path'][goal]: return x['next_path'],n
if not x['new'].any() and not x['next_tip'].any(): return None,n
for k in ('seen','tip','path'): x[k]=x['next_'+k]
for i in range(4): x[f'p{i}']=x[f'next_parent{i}']
raise RuntimeError("bound exhausted")
def bfs(grid,start,goal):
sh=grid.shape
if not grid[start] or not grid[goal]: return None
q=deque([(start,0)]); seen={start}
while q:
(y,x),d=q.popleft()
if (y,x)==goal: return d
for a,b in OFF:
j,k=y+a,x+b
if 0<=j<sh[0] and 0<=k<sh[1] and grid[j,k] and (j,k) not in seen:
seen.add((j,k));q.append(((j,k),d+1))
return None
def maze(size,rng):
g=np.zeros((size,size),dtype=bool)
st=[(1,1)];g[1,1]=1
while st:
y,x=st[-1]; options=[]
for dy,dx in OFF:
a,b=y+2*dy,x+2*dx
if 1<=a<size-1 and 1<=b<size-1 and not g[a,b]: options.append((a,b))
if not options: st.pop();continue
a,b=options[int(rng.integers(len(options)))]
g[a,b]=1;g[(a+y)//2,(b+x)//2]=1;st.append((a,b))
return g,(1,1),(size-2,size-2)
def load_checkpoint(path):
import json
from pathlib import Path
doc=json.loads(Path(path).read_text(encoding='utf-8'))
assert doc['format']=='sg-maze-signed-threshold-v1'
assert doc['offsets']==[list(x) for x in OFF]
rows={}
for row in doc['gates']:
assert row['name'] not in rows
rows[row['name']]=(row['threshold'],[(a,b) for a,b in row['edges']])
assert list(rows)==list(G) and all(type(t) is int and all(type(w) is int and w in (-1,1) for _,w in es) for t,es in rows.values())
G.clear()
G.update(rows)
COMPILED.clear()
COMPILED.update(rows)
if __name__=="__main__":
import sys
if len(sys.argv)>1: load_checkpoint(sys.argv[1])
rng=np.random.default_rng(583812)
fixtures=[maze(15,rng) for _ in range(32)]+[maze(31,rng) for _ in range(16)]
for _ in range(8):
g=rng.random((100,100))>.30;g[0,:]=g[:,-1]=1
fixtures.append((g,(0,0),(99,99)))
fixtures.extend([(np.eye(13,dtype=bool),(0,0),(12,12)),(np.ones((4,6),dtype=bool),(1,2),(1,2)),(np.ones((31,31),dtype=bool),(0,0),(30,30)),(np.zeros((3,3),dtype=bool),(0,0),(2,2)),maze(101,rng)])
times=[0.,0.]; counts=[0,0]; max_loops=0
for g,a,b in fixtures:
t=time.perf_counter(); d=bfs(g,a,b);times[0]+=time.perf_counter()-t
t=time.perf_counter(); p,k=solve(g,a,b);times[1]+=time.perf_counter()-t
max_loops=max(k,max_loops)
if d is None: assert p is None;counts[0]+=1
else:
assert p is not None and p[a] and p[b] and (p<=g).all() and p.sum()==d+1 and bfs(p,a,b)==d
assert k==2*d
counts[1]+=1
print(dict(fixtures=len(fixtures),reachable=counts[1],unreachable_or_blocked=counts[0],signed_weights=sum(len(t) for _,t in G.values()),thresholds=len(G),max_loops=max_loops,bfs_sec=times[0],block_sec=times[1]))