Download brain_lab/backend/arcade_rl.py from Chungulus/brain-lab: direct link, hf CLI and curl.
- Browser
- Download file 28 kB
-
https://huggingface.co/spaces/Chungulus/brain-lab/resolve/main/brain_lab/backend/arcade_rl.py
- Command line
-
hf download hf://spaces/Chungulus/brain-lab/brain_lab/backend/arcade_rl.py
-
curl -L -o arcade_rl.py https://huggingface.co/spaces/Chungulus/brain-lab/resolve/main/brain_lab/backend/arcade_rl.py
28 kB
| """Classroom Flappy Bird and streaming Crossy Road-style environments. | |
| Actual deterministic physics, sampled independent actions, and shared tabular | |
| Q-learning. Both are local teaching adaptations, not the commercial binaries. | |
| """ | |
| import hashlib,json,threading | |
| from collections import OrderedDict | |
| from pathlib import Path | |
| import numpy as np | |
| ROOT=Path(__file__).resolve().parents[1] | |
| VERSION=3 | |
| def hashed_tiles(columns,offset,slots=16384): | |
| values=np.asarray(columns,dtype=np.int64) | |
| code=np.full(values.shape[0],7919+offset*104729,dtype=np.int64) | |
| for j in range(values.shape[1]):code=(code*1009+(values[:,j]+4096)*(101+j*38))%2147483647 | |
| return code%slots+offset*slots | |
| class Flight: | |
| actions=['Coast','Flap'];hold=3;states=8*16384;goal=20;limit=3200;features=8 | |
| input_schema=[{'name':name,'unit':unit} for name,unit in [ | |
| ('Bird height','px'),('Vertical speed','px/tick'),('Next pipe left','px'),('Next pipe right','px'), | |
| ('Next gap top','px'),('Next gap bottom','px'),('Following pipe left','px'),('Following gap top','px'),('Following gap bottom','px')]] | |
| def __init__(self,n,seed,difficulty,course_length=20): | |
| if course_length is not None and (type(course_length) is not int or not 1<=course_length<=1_000_000):raise ValueError('Choose 1–1,000,000 pipes, or endless.') | |
| self.n=n;self.seed=seed;self.difficulty=difficulty;self.tick=0 | |
| self.goal=course_length;self.endless=course_length is None | |
| self.limit=None if self.endless else max(3200,int((course_length*190+340)/2.7)+400) | |
| self.rng=np.random.default_rng(seed);self.gap=155 if difficulty=='easy' else 125 | |
| # Preserve the original early courses for matched old/new comparisons. | |
| self.centers=self.rng.uniform(110,285,24);self.origins=340+np.arange(24)*190;self.pipe_cache=OrderedDict() | |
| self.speed=2.7;self.x=np.full(n,100.);self.y=np.full(n,210.);self.vy=np.zeros(n) | |
| self.done=np.zeros(n,bool);self.reason=np.full(n,'flying',object);self.score=np.zeros(n);self.total=np.zeros(n) | |
| def passed(self): | |
| count=max(0,int(np.ceil((self.speed*self.tick-304)/190))) | |
| return count if self.endless else min(count,self.goal) | |
| def geometry(self,index): | |
| index=max(0,int(index)) | |
| if not self.endless:index=min(index,self.goal-1) | |
| if index<24:return float(self.origins[index]-self.speed*self.tick),float(self.centers[index]) | |
| if index not in self.pipe_cache: | |
| self.pipe_cache[index]=float(np.random.default_rng(np.random.SeedSequence([self.seed,index,717])).uniform(110,285)) | |
| if len(self.pipe_cache)>256:self.pipe_cache.popitem(last=False) | |
| return float(340+index*190-self.speed*self.tick),self.pipe_cache[index] | |
| def pipe(self):return self.geometry(self.passed()) | |
| def observe(self): | |
| x,c=self.pipe();x2,c2=self.geometry(self.passed()+1) | |
| constant=lambda value:np.full(self.n,value) | |
| return np.column_stack([self.y,self.vy,constant(x),constant(x+52),constant(c-self.gap/2),constant(c+self.gap/2),constant(x2),constant(c2-self.gap/2),constant(c2+self.gap/2)]) | |
| def keys(self): | |
| obs=self.observe();center=(obs[:,4]+obs[:,5])/2;center2=(obs[:,7]+obs[:,8])/2 | |
| following_offset=190 if self.endless or self.passed()+1<self.goal else 0 | |
| result=[] | |
| for tile in range(8): | |
| shift=(tile%4)/4 | |
| if tile<4:values=np.column_stack([(obs[:,2]-100)/20,(obs[:,0]-center)/10,obs[:,1]/1.6]) | |
| elif tile<6:values=np.column_stack([(obs[:,6]-following_offset-100)/45,(obs[:,0]-center2)/25,obs[:,1]/3,(center2-center)/40]) | |
| else:values=np.column_stack([obs[:,0]/20,obs[:,1]/2,(obs[:,3]-52-100)/80,center/50]) | |
| result.append(hashed_tiles(np.floor(values+shift).astype(int),tile)) | |
| return np.column_stack(result) | |
| def step(self,actions,decision): | |
| active=~self.done;old_y=self.y.copy();_,center=self.pipe();old_phi=-np.abs(old_y-center)/100 | |
| if decision:self.vy[active&(actions==1)]=-6.8 | |
| self.vy[active]=np.minimum(11,self.vy[active]+.38);self.y[active]+=self.vy[active];self.tick+=1 | |
| reward=np.zeros(self.n);reward[active]=.025 | |
| crashed=active&((self.y<10)|(self.y>380)) | |
| for index in range(max(0,self.passed()-1),self.passed()+2): | |
| if not self.endless and index>=self.goal:continue | |
| x,c=self.geometry(index) | |
| if x<112 and x+52>88:crashed|=active&((self.y-10<c-self.gap/2)|(self.y+10>c+self.gap/2)) | |
| score=self.passed();passed=np.maximum(0,score-self.score);reward[active]+=passed[active]*5;self.score[active]=score | |
| finished=np.zeros(self.n,bool) if self.endless else active&~crashed&(self.score>=self.goal) | |
| reward[crashed]-=12;reward[finished]+=20 | |
| self.reason[crashed]='pipe or boundary';self.reason[finished]='goal';self.done|=crashed|finished | |
| if self.limit is not None: | |
| timed=active&~self.done&(self.tick>=self.limit);self.reason[timed]='time limit';self.done|=timed | |
| _,next_center=self.pipe();next_phi=-np.abs(self.y-next_center)/100;next_phi[self.done]=0 | |
| reward[active]+=.99*next_phi[active]-old_phi[active] | |
| self.total+=reward;return reward,active | |
| def frame(self): | |
| alive=np.flatnonzero(~self.done);leader=int(alive[0]) if len(alive) else int(np.argmax(self.score)) | |
| pipes=[] | |
| for i in range(max(0,self.passed()-1),self.passed()+6): | |
| if not self.endless and i>=self.goal:continue | |
| x,c=self.geometry(i) | |
| if -60<x<760:pipes.append({'id':i,'x':x,'center':c,'width':52,'gap':self.gap}) | |
| return {'tick':self.tick,'seed':self.seed,'leader':leader,'pipes':pipes,'ground':390,'world_height':420,'goal':self.goal,'endless':self.endless, | |
| 'input_values':self.observe()[leader].tolist(), | |
| 'runners':[{'id':i,'x':100,'y':float(self.y[i]),'vy':float(self.vy[i]),'done':bool(self.done[i]),'score':int(self.score[i]),'reason':self.reason[i]} for i in range(self.n)]} | |
| class Crossing: | |
| actions=['Wait','Forward','Left','Right','Back'];hold=8;base_states=1024*9*8;states=base_states+4*16384;goal=24;limit=2200;features=5 | |
| input_schema=[{'name':'Chicken column','unit':'columns'}]+[{'name':when+' '+action+' blocked','unit':'flag'} for when in ['Now','Next hop'] for action in ['Wait','Forward','Left','Right','Back']]+[{'name':lane+' '+value,'unit':unit} for lane in ['Current lane','Next lane','Following lane'] for value,unit in [('is road','flag'),('left car x','columns'),('right car x','columns'),('car speed','columns/tick'),('car length','columns')]] | |
| def __init__(self,n,seed,difficulty,course_length=24): | |
| if course_length is not None and (type(course_length) is not int or not 1<=course_length<=1_000_000): | |
| raise ValueError('Choose 1–1,000,000 rows, or endless.') | |
| self.n=n;self.seed=seed;self.difficulty=difficulty;self.tick=0 | |
| self.goal=course_length;self.endless=course_length is None | |
| self.limit=None if self.endless else max(2200,course_length*80) | |
| self.row_cache=OrderedDict() | |
| self.x=np.zeros(n);self.y=np.zeros(n);self.start_x=self.x.copy();self.start_y=self.y.copy();self.target_x=self.x.copy();self.target_y=self.y.copy() | |
| self.done=np.zeros(n,bool);self.reason=np.full(n,'crossing',object);self.score=np.zeros(n);self.total=np.zeros(n);self.stale=np.zeros(n,int) | |
| def _row(self,number): | |
| number=max(0,int(number)) | |
| if number in self.row_cache: | |
| self.row_cache.move_to_end(number);return self.row_cache[number] | |
| # Row-local random streams allow random access without generating a prefix. | |
| rng=np.random.default_rng(np.random.SeedSequence([self.seed,number])) | |
| road=number>1 and (self.endless or number<self.goal) and number%3!=0 | |
| direction=1 if rng.random()<.5 else -1 | |
| row={'row':number,'type':'road' if road else 'grass', | |
| 'speed':direction*(rng.uniform(.025,.038) if self.difficulty=='easy' else rng.uniform(.04,.06)), | |
| 'phase':float(rng.uniform(0,15)),'spacing':6 if self.difficulty=='easy' else 4.8,'length':float(rng.uniform(1.1,1.6))} | |
| trees=[] | |
| if not road and number>2 and (self.endless or number<self.goal-1): | |
| trees=[int(x) for x in rng.choice(np.array([-4,-3,3,4]),size=2,replace=False)] | |
| blocked=np.zeros(9) | |
| for x in trees:blocked[x+4]=1 | |
| row['_trees']=trees | |
| row['_sensors']=np.array([road,row['speed'],row['phase'],row['spacing'],row['length'],direction>0,*blocked],dtype=float) | |
| self.row_cache[number]=row | |
| if len(self.row_cache)>2048:self.row_cache.popitem(last=False) | |
| return row | |
| def _sample(self,rows): | |
| rows=np.asarray(rows,dtype=np.int64) | |
| rows=np.maximum(rows,0) if self.endless else np.clip(rows,0,self.goal) | |
| return np.stack([self._row(r)['_sensors'] for r in rows.ravel()]).reshape((*rows.shape,15)) | |
| def _leader(self): | |
| alive=np.flatnonzero(~self.done) | |
| return int(alive[np.argmax(self.score[alive])]) if len(alive) else int(np.argmax(self.score)) | |
| def _window(self): | |
| start=max(0,int(self.y[self._leader()])-12)//8*8 | |
| end=start+39 | |
| if not self.endless:end=min(end,self.goal) | |
| return start,end | |
| def rows(self): | |
| start,end=self._window() | |
| return [{k:v for k,v in self._row(i).items() if not k.startswith('_')} for i in range(start,end+1)] | |
| def trees(self): | |
| start,end=self._window() | |
| return [(x,i) for i in range(start,end+1) for x in self._row(i)['_trees']] | |
| def cars(self,tick=None): | |
| tick=self.tick if tick is None else tick;result=[] | |
| for row in self.rows: | |
| if row['type']!='road':continue | |
| for j in range(3): | |
| x=(row['phase']+j*row['spacing']+row['speed']*tick)%(row['spacing']*3)-row['spacing']*1.5 | |
| result.append({'id':row['row']*3+j,'row':row['row'],'x':float(x),'length':row['length'],'direction':1 if row['speed']>0 else -1}) | |
| return result | |
| def traffic_hit(self,x,y,tick,margin=.28): | |
| hit=np.zeros(np.shape(x),bool) | |
| for row in [np.floor(y).astype(int),np.ceil(y).astype(int)]: | |
| sensors=self._sample(row);spacing=sensors[...,3] | |
| origin=sensors[...,2]+sensors[...,1]*tick-1.5*spacing | |
| distance=np.abs((x-origin+spacing/2)%spacing-spacing/2) | |
| hit|=sensors[...,0].astype(bool)&(np.abs(y-row)<.65)&(distance<sensors[...,4]/2+margin) | |
| return hit | |
| def _blocked(self,x,y): | |
| result=(x< -4)|(x>4)|(y<0) | |
| if not self.endless:result|=y>self.goal | |
| sensors=self._sample(np.rint(y).astype(int));col=np.clip(np.rint(x)+4,0,8).astype(int) | |
| return result|np.take_along_axis(sensors[...,6:],col[...,None],axis=-1)[...,0].astype(bool) | |
| def risk(self,x,y,tick):return self._blocked(x,y)|self.traffic_hit(x,y,tick,.32) | |
| def observe(self): | |
| x=np.rint(self.x);y=np.rint(self.y);fields=[x] | |
| for tick in [self.tick,self.tick+self.hold]: | |
| for dx,dy in [(0,0),(0,1),(-1,0),(1,0),(0,-1)]:fields.append(self.risk(x+dx,y+dy,tick).astype(float)) | |
| for ahead in [0,1,2]: | |
| row=self._sample(y.astype(int)+ahead);road=row[:,0].astype(bool) | |
| origin=row[:,2]+row[:,1]*self.tick-1.5*row[:,3] | |
| left=origin+np.floor((x-origin)/row[:,3])*row[:,3];right=left+row[:,3] | |
| fields.extend([road.astype(float),np.where(road,left,0),np.where(road,right,0),np.where(road,row[:,1],0),np.where(road,row[:,4],0)]) | |
| return np.column_stack(fields) | |
| def keys(self): | |
| obs=self.observe();bits=1<<np.arange(5) | |
| now=(obs[:,1:6]*bits).sum(1).astype(int);later=(obs[:,6:11]*bits).sum(1).astype(int) | |
| base=(((((now*32+later)*9+np.clip(obs[:,0]+4,0,8).astype(int))*2+obs[:,11].astype(int))*2+obs[:,16].astype(int))*2+(obs[:,19]>0).astype(int)) | |
| values=[] | |
| for j in [11,16,21]: | |
| road=obs[:,j];phase=np.where(road,(obs[:,0]-obs[:,j+1])/np.maximum(1,obs[:,j+2]-obs[:,j+1]),0) | |
| values.extend([road,phase*8,obs[:,j+3]/.025,obs[:,j+4]/.4]) | |
| values.append(obs[:,0]);values=np.column_stack(values) | |
| return np.column_stack([base]+[self.base_states+hashed_tiles(np.floor(values+tile/4).astype(int),tile) for tile in range(4)]) | |
| def step(self,actions,decision): | |
| active=~self.done;reward=np.zeros(self.n);reward[active]=-.008 | |
| if decision: | |
| self.start_x=self.x.copy();self.start_y=self.y.copy() | |
| dx=np.array([0,0,-1,1,0])[actions];dy=np.array([0,1,0,0,-1])[actions] | |
| tx=self.x+dx;ty=self.y+dy;blocked=self._blocked(tx,ty) | |
| reward[active&blocked]-=.2;tx[blocked]=self.x[blocked];ty[blocked]=self.y[blocked] | |
| self.target_x=tx;self.target_y=ty | |
| phase=(self.tick%self.hold+1)/self.hold | |
| self.x[active]=self.start_x[active]+(self.target_x[active]-self.start_x[active])*phase | |
| self.y[active]=self.start_y[active]+(self.target_y[active]-self.start_y[active])*phase | |
| self.tick+=1;hit=active&self.traffic_hit(self.x,self.y,self.tick) | |
| reward[hit]-=10;self.reason[hit]='hit by traffic';self.done|=hit | |
| if phase==1: | |
| reached=np.maximum(self.score,np.floor(self.y+.001));gain=reached-self.score | |
| reward[active]+=gain[active]*2;self.stale[active]=np.where(gain[active]>0,0,self.stale[active]+self.hold);self.score[active]=reached[active] | |
| if not self.endless: | |
| goal=active&~self.done&(self.y>=self.goal);reward[goal]+=30;self.reason[goal]='goal';self.done|=goal | |
| timed=active&~self.done&(self.stale>=240) | |
| if self.limit is not None:timed|=active&~self.done&(self.tick>=self.limit) | |
| reward[timed]-=4;self.reason[timed]='waited too long';self.done|=timed | |
| self.total+=reward;return reward,active | |
| def frame(self): | |
| phase=(self.tick%self.hold)/self.hold;start,end=self._window() | |
| return {'tick':self.tick,'seed':self.seed,'leader':self._leader(),'cars':self.cars(),'trees':self.trees,'rows':self.rows,'goal':self.goal, | |
| 'endless':self.endless,'window_start':start,'window_end':end,'input_values':self.observe()[self._leader()].tolist(), | |
| 'runners':[{'id':i,'x':float(self.x[i]),'y':float(self.y[i]),'hop':float(np.sin(phase*np.pi)*.35) if not self.done[i] and (self.target_y[i]!=self.start_y[i] or self.target_x[i]!=self.start_x[i]) else 0, | |
| 'done':bool(self.done[i]),'score':int(self.score[i]),'reason':self.reason[i]} for i in range(self.n)]} | |
| ENVIRONMENTS={'flappy':Flight,'crossy':Crossing} | |
| class ArcadeRL: | |
| def __init__(self,game,owner='classroom',population=32,difficulty='easy',seed=7,course_length='default'): | |
| if game not in ENVIRONMENTS:raise ValueError('Choose Flappy Bird or Crossy Road.') | |
| self.game=game;self.owner=owner;self.lock=threading.RLock();self.env_type=ENVIRONMENTS[game] | |
| directory=ROOT/'data/arcade_learning';directory.mkdir(exist_ok=True) | |
| self.checkpoint=directory/(game+'-'+hashlib.sha256(owner.encode()).hexdigest()[:24]+'.npz') | |
| self.reset(population,difficulty,seed,course_length) | |
| def reset(self,population=32,difficulty='easy',seed=7,course_length='default'): | |
| if not isinstance(population,int) or not 1<=population<=128:raise ValueError('Choose 1–128 agents.') | |
| if difficulty not in ['easy','standard']:raise ValueError('Choose easy or standard difficulty.') | |
| if course_length=='default':course_length=20 if self.game=='flappy' else 24 | |
| if course_length is not None and (type(course_length) is not int or not 1<=course_length<=1_000_000):raise ValueError('Choose a whole-number course length from 1 to 1,000,000, or endless.') | |
| with self.lock: | |
| self.population=population;self.difficulty=difficulty;self.seed=int(seed);self.rng=np.random.default_rng(seed) | |
| self.course_length=course_length | |
| self.q=np.zeros((self.env_type.states,len(self.env_type.actions)),np.float32);self.visited=np.zeros(self.env_type.states,bool) | |
| self.experiences=self.updates=self.transitions=self.wins=self.episodes=0;self.round=0;self.history=[];self.exploration=.18 if self.game=='flappy' else .25 | |
| self.auto_exploration=self.game=='flappy';self.replay_size=0;self.replay_cursor=0;self.replay_capacity=12000;self.replay_updates=0 | |
| count=self.env_type.features | |
| self.replay_keys=np.zeros((self.replay_capacity,count),np.int64);self.replay_next=np.zeros_like(self.replay_keys) | |
| self.replay_actions=np.zeros(self.replay_capacity,np.int64);self.replay_rewards=np.zeros(self.replay_capacity);self.replay_discounts=np.zeros(self.replay_capacity) | |
| self._fresh();self.manual=None;self.pending=0 | |
| return self.state() | |
| def _environment(self,population,seed): | |
| if self.game=='crossy':return Crossing(population,seed,self.difficulty,self.course_length) | |
| return Flight(population,seed,self.difficulty,self.course_length) | |
| def _fresh(self): | |
| if self.round: | |
| self.history.append({'round':self.round,'mean_score':float(self.env.score.mean()),'best_score':float(self.env.score.max()),'wins':int(np.count_nonzero(self.env.reason=='goal'))}) | |
| self.history=self.history[-160:] | |
| self.env=self._environment(self.population,self.seed+self.round*9973);self.round+=1 | |
| self.actions=np.zeros(self.population,np.int64);self.start_keys=np.zeros((self.population,self.env_type.features),np.int64);self.accum=np.zeros(self.population);self.elapsed=np.zeros(self.population,int) | |
| def effective_exploration(self): | |
| floor=min(.025,self.exploration) | |
| return floor+(self.exploration-floor)*np.exp(-self.experiences/35000) if self.auto_exploration else self.exploration | |
| def feature_weights(self):return np.ones(self.env_type.features) if self.game=='flappy' else np.array([1.,.1,.1,.1,.1]) | |
| def values(self,keys):return (self.q[keys]*self.feature_weights()[None,:,None]).sum(axis=1) | |
| def _fit(self,keys,actions,expected,rate=.22): | |
| error=expected-self.values(keys)[np.arange(len(keys)),actions] | |
| pairs=(keys*len(self.env_type.actions)+actions[:,None]).ravel();unique,inverse=np.unique(pairs,return_inverse=True) | |
| mean=np.bincount(inverse,weights=np.repeat(error,keys.shape[1]))/np.bincount(inverse) | |
| weights=self.feature_weights();learning_rate=rate/np.sum(weights**2) | |
| # Tile tables occupy disjoint ranges, so each pair retains its feature weight. | |
| feature=np.tile(np.arange(keys.shape[1]),len(keys));weights_by_pair=np.bincount(inverse,weights=weights[feature])/np.bincount(inverse) | |
| self.q.flat[unique]+=learning_rate*weights_by_pair*mean | |
| self.updates+=len(unique);self.visited[keys]=True | |
| def _update(self,mask): | |
| ids=np.flatnonzero(mask) | |
| if not len(ids):return | |
| current=self.start_keys[ids];act=self.actions[ids];next_keys=self.env.keys()[ids] | |
| discount=np.power(.99,self.elapsed[ids])*(~self.env.done[ids]) | |
| expected=self.accum[ids]+discount*np.max(self.values(next_keys),axis=1) | |
| self._fit(current,act,expected,.22 if self.game=='flappy' else .1872);self.transitions+=len(ids) | |
| slots=(self.replay_cursor+np.arange(len(ids)))%self.replay_capacity | |
| self.replay_keys[slots]=current;self.replay_next[slots]=next_keys;self.replay_actions[slots]=act | |
| self.replay_rewards[slots]=self.accum[ids];self.replay_discounts[slots]=discount | |
| self.replay_cursor=(self.replay_cursor+len(ids))%self.replay_capacity;self.replay_size=min(self.replay_capacity,self.replay_size+len(ids)) | |
| if self.game=='flappy' and self.replay_size>=64: | |
| for _ in range(2): | |
| sample=self.rng.integers(self.replay_size,size=min(128,self.replay_size)) | |
| target=self.replay_rewards[sample]+self.replay_discounts[sample]*self.values(self.replay_next[sample]).max(axis=1) | |
| self._fit(self.replay_keys[sample],self.replay_actions[sample],target,.12);self.replay_updates+=1 | |
| def train(self,ticks): | |
| with self.lock: | |
| frames=[];every=max(1,int(ticks)//24) | |
| for t in range(int(ticks)): | |
| if self.env.done.all():self._fresh() | |
| decision=self.env.tick%self.env_type.hold==0 | |
| if decision: | |
| self.start_keys=self.env.keys();self.actions=np.argmax(self.values(self.start_keys),axis=1) | |
| random=self.rng.random(self.population)<self.effective_exploration;self.actions[random]=self.rng.integers(len(self.env_type.actions),size=np.count_nonzero(random)) | |
| self.accum[:]=0;self.elapsed[:]=0 | |
| reward,active=self.env.step(self.actions,decision);new_done=active&self.env.done | |
| self.accum+=np.power(.99,self.elapsed)*reward;self.elapsed[active]+=1;self.experiences+=int(active.sum()) | |
| self.episodes+=int(new_done.sum());self.wins+=int(np.count_nonzero(new_done&(self.env.reason=='goal'))) | |
| self._update(active&((self.env.tick%self.env_type.hold==0)|self.env.done)) | |
| if t%every==0 or t==ticks-1:frames.append(self.frame()) | |
| result=self.state();result['frames']=frames;return result | |
| def frame(self):return {'round':self.round,**self.env.frame()} | |
| def checkpoint_compatible(self): | |
| if not self.checkpoint.exists():return False | |
| try:return json.loads(self.checkpoint.with_suffix('.json').read_text()).get('version')==VERSION | |
| except (OSError,ValueError):return False | |
| def state(self): | |
| with self.lock: | |
| keys=self.env.keys();frame=self.frame();leader=frame['leader'] | |
| return {'game':self.game,'population':self.population,'difficulty':self.difficulty,'seed':self.seed,'round':self.round,'tick':self.env.tick, | |
| 'active':int(np.count_nonzero(~self.env.done)),'experiences':self.experiences,'updates':self.updates,'transitions':self.transitions,'wins':self.wins,'episodes':self.episodes, | |
| 'states':int(self.visited.sum()),'exploration':self.exploration,'goal':self.env.goal,'endless':self.course_length is None,'course_length':self.course_length,'hold':self.env_type.hold,'action_names':self.env_type.actions, | |
| 'q_values':self.values(keys)[leader].tolist(),'input_schema':self.env.input_schema,'effective_exploration':float(self.effective_exploration),'auto_exploration':self.auto_exploration,'replay_size':self.replay_size,'replay_updates':self.replay_updates,'history':list(self.history),'frame':frame,'checkpoint_available':self.checkpoint_compatible(), | |
| 'checkpoint_note':'An older saved learner uses different inputs. Start fresh and save again.' if self.checkpoint.exists() and not self.checkpoint_compatible() else '', | |
| 'algorithm':'shared tile-coded Q-learning'+(' with experience replay' if self.game=='flappy' else ' with car-position refinement'),'environment':'local classroom adaptation','physics_hz':60} | |
| def config(self,exploration,auto_exploration=None): | |
| with self.lock: | |
| self.exploration=float(exploration) | |
| if auto_exploration is not None:self.auto_exploration=bool(auto_exploration) | |
| return {'exploration':self.exploration,'auto_exploration':self.auto_exploration,'effective_exploration':float(self.effective_exploration)} | |
| def evaluate(self,seeds=None,include_frames=True): | |
| seeds=[self.seed+1001,self.seed+1002,self.seed+1003,self.seed+1004] if seeds is None else list(seeds) | |
| with self.lock: | |
| runs=[];frames=[] | |
| for index,seed in enumerate(seeds): | |
| env=self._environment(1,int(seed));actions=np.zeros(1,np.int64) | |
| budget=min(env.limit or 6000,6000);sample_every=max(8,(budget//180//8)*8) | |
| if include_frames and index==0:frames.append({'round':0,**env.frame()}) | |
| while not env.done[0] and env.tick<budget: | |
| decision=env.tick%env.hold==0 | |
| if decision:actions=np.argmax(self.values(env.keys()),axis=1) | |
| env.step(actions,decision) | |
| if include_frames and index==0 and (env.tick%sample_every==0 or env.done[0]):frames.append({'round':0,**env.frame()}) | |
| truncated=not bool(env.done[0]) | |
| if truncated: | |
| env.reason[0]='test budget' | |
| if include_frames and index==0:frames.append({'round':0,**env.frame()}) | |
| runs.append({'seed':int(seed),'score':int(env.score[0]),'success':env.reason[0]=='goal','reason':env.reason[0],'ticks':env.tick,'truncated':truncated}) | |
| return {'game':self.game,'training_experiences':self.experiences,'updates':self.updates,'exploration':0,'learning':False,'mean_score':float(np.mean([r['score'] for r in runs])), | |
| 'successes':sum(r['success'] for r in runs),'runs':runs,'frames':frames,'test_seeds':seeds,'goal':self.env.goal,'endless':self.course_length is None,'test_tick_limit':6000} | |
| def human_reset(self): | |
| with self.lock: | |
| self.manual=self._environment(1,self.seed);self.pending=0;self.manual_action=np.zeros(1,np.int64) | |
| return {'round':0,**self.manual.frame()} | |
| def human(self,action): | |
| with self.lock: | |
| if self.manual is None:self.human_reset() | |
| if action:self.pending=int(action) | |
| count=3 if self.game=='flappy' else 4 | |
| for _ in range(count): | |
| if self.manual.done[0]:break | |
| decision=self.manual.tick%self.env_type.hold==0 | |
| if decision:self.manual_action[0]=self.pending;self.pending=0 | |
| self.manual.step(self.manual_action,decision) | |
| return {'round':0,**self.manual.frame()} | |
| def save(self): | |
| with self.lock: | |
| meta={'version':VERSION,'game':self.game,'population':self.population,'difficulty':self.difficulty,'seed':self.seed,'experiences':self.experiences,'updates':self.updates, | |
| 'transitions':self.transitions,'exploration':self.exploration,'history':self.history,'course_length':self.course_length,'course_format':2,'auto_exploration':self.auto_exploration} | |
| temporary=self.checkpoint.with_suffix('.tmp') | |
| with temporary.open('wb') as f:np.savez_compressed(f,q=self.q,visited=self.visited,metadata=np.array(json.dumps(meta))) | |
| temporary.replace(self.checkpoint);digest=hashlib.sha256(self.checkpoint.read_bytes()).hexdigest() | |
| self.checkpoint.with_suffix('.json').write_text(json.dumps({'sha256':digest,**meta},indent=2)) | |
| return {'saved':True,'experiences':self.experiences,'sha256':digest} | |
| def load(self): | |
| with self.lock: | |
| if not self.checkpoint.exists():raise ValueError('Save this session’s learning first.') | |
| receipt=json.loads(self.checkpoint.with_suffix('.json').read_text()) | |
| if hashlib.sha256(self.checkpoint.read_bytes()).hexdigest()!=receipt['sha256']:raise ValueError('The saved learning has changed.') | |
| with np.load(self.checkpoint,allow_pickle=False) as f: | |
| q=f['q'];visited=f['visited'];meta=json.loads(str(f['metadata'])) | |
| expected=(self.env_type.states,len(self.env_type.actions)) | |
| if meta['game']!=self.game or meta['version']!=VERSION or q.shape!=expected or not np.isfinite(q).all() or visited.shape!=(expected[0],):raise ValueError('Incompatible saved learning.') | |
| self.reset(meta['population'],meta['difficulty'],meta['seed'],meta.get('course_length',24));self.q=q.astype(np.float32);self.visited=visited.astype(bool) | |
| for key in ['experiences','updates','transitions','exploration','history','auto_exploration']:setattr(self,key,meta[key]) | |
| return self.state() | |