Exploration in deep RL: shaping, intrinsic rewards and posterior sampling
With sparse or misleading rewards, ε-greedy exploration can take exponential time. Study potential-based shaping and its invariance theorem, count bonuses and pseudo-counts, prediction-error curiosity and the noisy-TV trap, RND, deep exploration through posterior sampling (PSRL and bootstrapped DQN), and Go-Explore. Extend optimism and Thompson sampling from bandits to MDPs.
After this lesson you can
- Show that potential-based shaping preserves optimal policies.
- Implement exploration bonuses using counts, pseudo-counts, and RND.
- Explain the noisy-TV problem and which methods suffer from it.
- Extend Thompson sampling to MDPs with PSRL and bootstrapped DQN.
- Evaluate exploration by coverage as well as by return.
Before you start
A reward at the end of a hallway
A sparse reward does not say which intermediate action has brought the agent closer to the goal. In a chain where it must choose to advance nine times consecutively, a uniform independent policy has probability to complete the traversal in an episode. The number of episodes until the first success is geometric with mean . The calculation presupposes nine independent binary decisions, reset on failure and the same probability in each episode. If there are ten decisions, not nine, the answer changes. A learned policy does not have to remain uniform, and those hypotheses do not describe DQN behavior on their own.
The problem worsens when a small reward near the beginning makes the greedy policy return there. With -greedy, if advancing can only be chosen through uniform exploration at each step, and the greedy action always backtracks, the probability of nine consecutive advances is . This is a specific construction, not a universal law for all MDPs. Deep exploration maintains a hypothesis or intention throughout a sequence; an isolated random decision that is forgotten at the next step is insufficient.
Reward progress without changing the objective
Suppose a known potential function measures progress toward a desired region. Potential-based shaping replaces the reward with
The difference provides an intermediate incentive, but its discounted sum telescopes. For a trajectory of length ,
In infinite horizon with and bounded potential, the last term tends to zero. In a finite episode terminated upon reaching a terminal, it suffices to impose for all terminals; another valid convention consists in continuing the explicit transitions of absorbing states coherently. Then for any policy , and all actions in the same state undergo the same translation: . The set of optimal policies is preserved, not necessarily the speed with which an approximate algorithm learns them.
The terminal condition matters. If you stop accumulating return at termination and leave different terminal potentials, can depend on the outcome and change which action is preferable. Nor is rewarding each advance enough: if a cycle delivers more extra reward than it costs to undo, the agent may repeat it instead of solving the task. Ng, Harada, and Russell characterize the transformations that preserve optimal policies under the relevant assumptions.
The board has nine squares, deterministic moves, and discount . Entering the goal gives a reward of and ends the episode; other steps cost , including those that collide with a boundary. Arbitrary-bonus mode adds the value of the destination cell, except at the goal. Potential mode adds and sets at the goal. The figure solves both MDPs through Bellman iteration and compares all tied actions within a numerical tolerance. It displays the optimal policies of this model, rather than learned trajectories.
With the initial bonus in the center, the optimal value from the upper-left corner rises from to approximately , and the optimal actions change in seven of the eight nonterminal cells: repeatedly visiting the center can outweigh reaching the goal. Switch to potential mode while keeping the same numbers: the optimal actions match those under the base reward again, although their values change. The contrast does not require the potential to point in a sensible direction: invariance holds even for a poorly chosen potential, although learning may become slower.
Visits, density and novelty
Count-based exploration adds a bonus that decreases with the number of visits, for example . In a table, is a literal count. The bonus changes the learning problem and is not an evaluation reward: when comparing agents, measure both environmental coverage and external return.
With continuous observations or images, almost every vector may be different. A hash such as SimHash assigns an observation to a cell using the signs of random projections. Nearby states tend to share codes, but this is not guaranteed: a hyperplane can separate arbitrarily close points. Changing variable scales or the seed changes the counts; two states with the same hash need not be equivalent for decision-making.
Tang and colleagues studied counts over hash codes in continuous control and Atari; useful novelty depends on the granularity and information retained. An overly coarse code merges different situations; an overly fine code may treat almost every observation as new.
A density model offers another generalization. If the probability assigned to before training on that observation is and afterward is , the pseudo-count is defined by analogy with empirical frequencies. Solving the two frequency equations gives
To derive it, set and . Substitute into the second equality and solve for ; multiplying by yields the formula. This expression requires and ; if the model does not increase that probability, the denominator does not support a positive count. For a genuine tabular counter, it reproduces the count under the corresponding conditions. For a density network, it depends on the model and its update; it does not independently recover the true number of visits. Bellemare and colleagues develop the relationship between density and pseudo-counts.
Tabular Laboratory: First Arrival and Coverage
The experiment chain has depth decisions and two actions. The first ends the episode and gives a Bernoulli reward with a mean of 0.05; the second advances and only the last advance gives a reward of 1. A success means reaching that final reward, not getting the small reward. The grid is 4 × 4, with four actions, walls, and a single reward upon reaching the goal. In both cases, transitions and visited states are counted until the first success; if it does not reach within the budget, the result is marked as censored and not presented as observed time to success.
Q-learning uses and step size ; the count-based variant adds in nonterminal states. Simplified R-max treats a state-action pair as unknown until two visits and assigns it the optimistic value . PSRL uses Dirichlet priors for transitions and Beta priors for Bernoulli rewards, sampling a model at the start of each episode and keeping it fixed throughout that episode. Value iteration is limited to 100 passes: this is a computable approximation, not a proof of a guarantee. Random seeds are not shared between algorithms as though they produced aligned trajectories.
"""Prototipo tabular reproducible; resultados censurados explícitamente."""
import numpy as np
def chain(depth):
# depth decisiones binarias; izquierda termina con recompensa Bernoulli pequeña.
S=depth;A=2;terminal=S
transitions=np.empty((S,A),int); means=np.zeros((S,A))
for s in range(S):
transitions[s,0]=terminal;means[s,0]=.05
transitions[s,1]=terminal if s==S-1 else s+1
means[s,1]=1. if s==S-1 else 0.
return transitions,means,0
def grid(width):
S=width*width;A=4;terminal=S;target=S-1
transitions=np.empty((S,A),int);means=np.zeros((S,A))
for s in range(S):
x,y=s%width,s//width
for a,(dx,dy) in enumerate([(1,0),(0,1),(-1,0),(0,-1)]):
t=max(0,min(width-1,y+dy))*width+max(0,min(width-1,x+dx))
transitions[s,a]=terminal if t==target else t
means[s,a]=float(t==target)
return transitions,means,0
def values(P,rewards,gamma=.95,unknown=None,iterations=100):
S,A=P.shape[:2];v=np.zeros(S+1)
for _ in range(iterations):
q=rewards+gamma*np.einsum('sak,k->sa',P,v)
if unknown is not None:q=np.where(unknown,1/(1-gamma),q)
new=q.max(axis=1)
if np.max(abs(new-v[:S]))<1e-8:break
v[:S]=new
return q
def run(transitions,means,start,method,seed,max_episodes=1000,max_steps=60):
S,A=transitions.shape;terminal=S;rng=np.random.default_rng(seed)
counts=np.zeros((S,A),int);visits=np.zeros(S,int);outcomes=np.zeros((S,A,S+1),int)
successes=np.zeros((S,A));Q=np.zeros((S,A));steps=0
for episode in range(1,max_episodes+1):
if method=='rmax':
known=counts>=2
P=np.divide(outcomes,counts[...,None],out=np.zeros_like(outcomes,dtype=float),where=counts[...,None]>0)
R=np.divide(successes,counts,out=np.zeros_like(successes),where=counts>0)
policy=values(P,R,unknown=~known)
elif method=='psrl':
P=np.empty((S,A,S+1))
for s in range(S):
for a in range(A):P[s,a]=rng.dirichlet(outcomes[s,a]+.1)
R=rng.beta(successes+1,counts-successes+1)
policy=values(P,R)
state=start
for _ in range(max_steps):
visits[state]+=1
if method in ('q','count'):
action=int(rng.integers(A)) if rng.random()<.1 else int(rng.choice(np.flatnonzero(Q[state]>=Q[state].max()-1e-12)))
else:action=int(rng.choice(np.flatnonzero(policy[state]>=policy[state].max()-1e-12)))
nxt=transitions[state,action];reward=float(rng.random()<means[state,action]);steps+=1
outcomes[state,action,nxt]+=1;counts[state,action]+=1;successes[state,action]+=reward
if method in ('q','count'):
bonus=.2/np.sqrt(1+visits[nxt]) if method=='count' and nxt!=terminal else 0.
target=reward+bonus+(.95*Q[nxt].max() if nxt!=terminal else 0.)
Q[state,action]+=.2*(target-Q[state,action])
if nxt==terminal:
goal=(means[state,action]==1.)
if goal:return {'success':True,'steps':steps,'episode':episode,'coverage':int(np.count_nonzero(visits))}
break
state=nxt
return {'success':False,'steps':steps,'episode':max_episodes,'coverage':int(np.count_nonzero(visits))}
def summarize(rows):
completed=[row['steps'] for row in rows if row['success']]
return {'exitos':len(completed),'censurados':len(rows)-len(completed),
'mediana_solo_exitos':float(np.median(completed)) if completed else None,
'pasos':[row['steps'] for row in rows],
'coberturas':[row['coverage'] for row in rows],
'llego':[row['success'] for row in rows]}The cells run 20 seeds per method and model, with a maximum of 500 episodes and 60 steps per episode. The lists include steps from all runs: for censored runs, these are steps until the cutoff, not until success. The median is calculated only over successful runs and can look optimistic when many runs are censored; check their number as well. Coverage counts states visited before the first success or the cutoff. Since runs do not have equal step budgets, coverage alone does not establish exploration efficiency.
environments=[('cadena4',chain(4)),('cadena6',chain(6)),('cadena8',chain(8)),('grid4',grid(4))]
q_results={label:[run(*env,'q',seed,max_episodes=500) for seed in range(20)] for label,env in environments}
for label,rows in q_results.items(): print(label,summarize(rows))count_results={label:[run(*env,'count',seed,max_episodes=500) for seed in range(20)] for label,env in environments}
for label,rows in count_results.items(): print(label,summarize(rows))rmax_results={label:[run(*env,'rmax',seed,max_episodes=500) for seed in range(20)] for label,env in environments}
for label,rows in rmax_results.items(): print(label,summarize(rows))psrl_results={label:[run(*env,'psrl',seed,max_episodes=500) for seed in range(20)] for label,env in environments}
for label,rows in psrl_results.items(): print(label,summarize(rows))In a run of these cells, Q-learning reached the goal in 17 out of 20 seeds on the six-decision chain, with a median of 258 steps among successes. The count-based variant, simplified R-max, and PSRL succeeded in all 20 seeds: their medians were 18.5, 36.5, and 23.5 steps, respectively. Q-learning’s median excludes three censored runs, so comparisons must account for those failures.
On the grid, all four variants succeeded in all 20 seeds, but median step counts were 54.5 for Q-learning, 1221 for counts, 43.5 for R-max, and 1626 for PSRL. The bonus that helps on the chain does not help on this small grid under these settings. These are results for this program and budget, not a general algorithm ranking or a test of asymptotic complexity.
Red bars indicate that the goal was not reached before the cutoff: their height is the number of observed transitions, not an arrival time. Change the depth and method and select a seed to see the exact data. Medians use only successful runs; a smaller median alongside many censored runs does not demonstrate greater reliability. The comparison includes the neural variant reproduced below, with 20 runs at the same depths and episode limit.
For a neural comparison, the following experiment implements a small bootstrapped-DQN variant with a shared hidden layer, five heads, and fixed random priors. Each transition is assigned to each head through a Bernoulli mask, the target network is copied every 50 steps, and one head is retained throughout the episode. The input is a one-hot state encoding. The code computes gradients with NumPy and runs 20 seeds per depth with the same 500-episode cutoff. First arrival does not demonstrate that the learned policy is optimal.
"""DQN con capa oculta compartida y cabezas bootstrap, implementado con NumPy."""
import numpy as np
def bootstrap_chain(depth,seed,max_episodes=500,heads=5,width=12):
rng=np.random.default_rng(seed);gamma=.95;learning_rate=.01
# Entrada one-hot: W1[state] es la activación previa de la capa oculta.
W1=rng.normal(0,.25,(depth,width));W2=rng.normal(0,.1,(heads,width,2))
prior=rng.normal(0,.5,(heads,depth,2));target1=W1.copy();target2=W2.copy()
replay=[];steps=0;visited=set()
def q(s,w1,w2):
h=np.maximum(w1[s],0.)
return np.einsum('...h,kha->...ka',h,w2)+prior[:,s,:].transpose(1,0,2) if np.ndim(s)>0 else np.einsum('h,kha->ka',h,w2)+prior[:,s,:]
for episode in range(1,max_episodes+1):
head=int(rng.integers(heads));state=0
for _ in range(depth):
visited.add(state);Q=q(state,W1,W2);action=int(rng.choice(np.flatnonzero(Q[head]>=Q[head].max()-1e-12)))
done=(action==0 or state==depth-1)
reward=float(rng.random()<.05) if action==0 else float(state==depth-1)
nxt=state if done else state+1
mask=(rng.random(heads)<.5).astype(float)
replay.append((state,action,reward,nxt,done,mask));steps+=1
if len(replay)>=16:
selected=rng.integers(len(replay),size=16);batch=[replay[int(i)] for i in selected]
s=np.array([x[0] for x in batch]);a=np.array([x[1] for x in batch]);r=np.array([x[2] for x in batch]);ns=np.array([x[3] for x in batch]);d=np.array([x[4] for x in batch]);m=np.stack([x[5] for x in batch])
hidden=np.maximum(W1[s],0.);pred=q(s,W1,W2);nextq=q(ns,target1,target2).max(axis=2)
chosen=pred[np.arange(16)[:,None],np.arange(heads)[None,:],a[:,None]]
error=(chosen-(r[:,None]+gamma*(1-d[:,None])*nextq))*m
scale=max(float(m.sum()),1.);grad2=np.zeros_like(W2);grad1=np.zeros_like(W1)
for k in range(heads):
for action_index in range(2):
z=2*error[:,k]*(a==action_index)/scale
grad2[k,:,action_index]=hidden.T@z
np.add.at(grad1,s,(z[:,None]*W2[k,:,action_index])*(W1[s]>0))
W1-=learning_rate*grad1;W2-=learning_rate*grad2
if steps%50==0:target1=W1.copy();target2=W2.copy()
if done:
if action==1 and state==depth-1:return {'success':True,'steps':steps,'episode':episode,'coverage':len(visited)}
break
state=nxt
return {'success':False,'steps':steps,'episode':max_episodes,'coverage':len(visited)}npm run lab and open the connection link.boot_results={depth:[bootstrap_chain(depth,seed,500) for seed in range(20)] for depth in (4,6,8)}
for depth,rows in boot_results.items():
print(depth,{'exitos':sum(row['success'] for row in rows),
'pasos':[row['steps'] for row in rows],
'llego':[row['success'] for row in rows],
'coberturas':[row['coverage'] for row in rows]})npm run lab and open the connection link.In the recorded execution, the network reached the goal in 10 of 20 seeds for depth 4, in 3 of 20 for depth 6, and in 2 of 20 for depth 8. The rest were censored as the budget ran out. This negative result prevents asserting that this implementation achieved polynomial scaling: maintaining one head per episode does not guarantee diversity or sufficient optimism by itself. The reference article and this experiment use different implementations and budgets.
Curiosity and the noisy television
A dynamics predictor can reward prediction error on the next observation. This error mixes novelty with intrinsically unpredictable noise: a randomly changing screen can provide constant surprise even when the agent understands that it does not control its contents. In ICM, an inverse task predicts the action from two representations, and a forward task predicts the next representation from the state and action. The learned representation can ignore aspects unrelated to the action, but there is no general guarantee that it eliminates all irrelevant noise. Pathak and colleagues introduce the method; the architecture and environment affect the result.
Burda and colleagues studied curiosity without external reward in 54 environments and examined several representations; they also highlighted the limitations of prediction error in stochastic settings. That empirical result does not guarantee that a curiosity bonus aligns with the goal of a new task.
Random Network Distillation (RND) does not attempt to predict the next state. A randomly initialized, frozen target network and a predictor receive the same observation ; intrinsic reward is proportional to . Since is deterministic, this avoids the irreducible error of predicting a random transition from a fixed input. This does not imply immunity to noisy TV: new random images may remain difficult to fit and attract the agent. Mavor-Parker and colleagues demonstrate this vulnerability empirically. The original RND paper defines the bonus and combines extrinsic and intrinsic signals.
The toy assumes independent, equiprobable screen bits. Even the best predictor of the next bit, 0.5, has expected squared error 0.25. The second bar imagines a representation that perfectly discards these bits and assigns error 0 to a familiar position and 1 to a new one: it illustrates ICM’s goal without guaranteeing that a network achieves it. For the third bar, each of the frames has a fixed random label or ; a tabular predictor returns zero for an unseen image and memorizes its label after seeing it. Expected error on the next image is after independent visits. This is a deliberately limited tabular analogue of RND without generalization between images; it does not use a trained network. Increasing leaves many images unseen even after numerous visits. The three scales explain mechanisms, rather than ranking the rewards of actual implementations.
The map adds an independent experiment in a room of 25 cells with a screen at its center. An agent chooses the action with the greatest immediate signal, with 10% random movement, and can stay still. A new ordinary cell gives 1 and a familiar cell gives 0; the screen gives 0.25 for the pixel model, zero for the representation that ignores it, and the fraction of frames not yet memorized for the fixed-target model. Stepping onto the screen adds a uniformly sampled image to memory. The numbers count visits per cell for one fixed seed and the selected step budget. No PPO or ICM policy has been trained: the map shows how these assumed signals can alter a myopic decision, rather than establishing which real agent would become trapped. The same control sets in the theoretical calculation and the total steps on the map; actual screen visits may differ.
Three networks trained on the screen
The following experiment complements the idealized model with real networks. Each observation contains the position in one-hot of a 5 × 5 room and 16 additional bits; those bits are zero except for the central television, where they are random. The pixel network predicts the next observation from the current one and the action. ICM learns a representation through an inverse action model and predicts the next representation. RND adjusts a predictor to the output of a frozen random network. They are trained for 1000 updates with batches of 128 from 30,000 generated transitions, and errors are measured on 12,000 independent transitions. The error scales of pixels and features are not directly comparable.
During traversal, a planner with access to the known movement model estimates each action’s surprise using eight possible observations, chooses the maximum with 10% random actions, and takes 300 steps. This is not an RL-trained policy: it queries the environment model to isolate how the signal affects a myopic decision. The networks remain frozen and the map counts visits; the update selector changes only the error measurement. With seeds 0, 1, and 2, the television received 232, 278, and 182 visits with pixel prediction; 183, 60, and 279 with ICM; and 65, 278, and 267 with RND. Variation between seeds rules out claiming immunity. The following code reproduces the networks and traversals; selecting a seed in the figure selects the networks and traversal from that run.
"""Tres modelos de curiosidad entrenados en transiciones de un grid con pantalla ruidosa."""
import json
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
DIM=41;A=5
MOVES=np.array([[0,0],[0,-1],[1,0],[0,1],[-1,0]])
def data(seed,n):
rng=np.random.default_rng(seed);s=rng.integers(25,size=n);a=rng.integers(A,size=n)
x=s%5;y=s//5;nx=np.clip(x+MOVES[a,0],0,4);ny=np.clip(y+MOVES[a,1],0,4);nxt=ny*5+nx
def obs(states):
out=np.zeros((n,DIM),np.float32);out[np.arange(n),states]=1
mask=states==12;out[mask,25:]=rng.integers(2,size=(int(mask.sum()),16))
return out
return torch.tensor(obs(s)),torch.tensor(a),torch.tensor(obs(nxt)),torch.tensor(nxt==12)
def network(inp,out):return nn.Sequential(nn.Linear(inp,64),nn.ReLU(),nn.Linear(64,out))
class Models(nn.Module):
def __init__(self):
super().__init__();self.pixel=network(DIM+A,DIM);self.encoder=network(DIM,16);self.inverse=network(32,A);self.forward_model=network(16+A,16);self.target=network(DIM,16);self.predictor=network(DIM,16)
for p in self.target.parameters():p.requires_grad_(False)
def errors(self,s,a,ns):
act=torch.nn.functional.one_hot(a,A).float();phi=self.encoder(s);nextphi=self.encoder(ns)
pix=(self.pixel(torch.cat((s,act),1))-ns).square().mean(1)
icm=(self.forward_model(torch.cat((phi,act),1))-nextphi.detach()).square().mean(1)
rnd=(self.predictor(ns)-self.target(ns).detach()).square().mean(1)
return pix,icm,rnd
def loss(self,s,a,ns):
pix,icm,rnd=self.errors(s,a,ns);phi=self.encoder(s);nextphi=self.encoder(ns)
inverse=torch.nn.functional.cross_entropy(self.inverse(torch.cat((phi,nextphi),1)),a)
return pix.mean()+.8*inverse+.2*icm.mean()+rnd.mean()
def greedy_rollout(model,method,seed,steps=300,draws=8):
# El planificador consulta el modelo de transición conocido para los candidatos;
# estima la sorpresa esperada con ocho imágenes y ejecuta otra muestra independiente.
rng=np.random.default_rng(seed);state=12;counts=np.zeros(25,int)
def observation(index):
out=np.zeros(DIM,np.float32);out[index]=1
if index==12:out[25:]=rng.integers(2,size=16)
return out
current=observation(state)
for _ in range(steps):
x,y=state%5,state//5;next_states=[]
for dx,dy in MOVES:next_states.append(int(np.clip(y+dy,0,4)*5+np.clip(x+dx,0,4)))
candidate=np.stack([observation(nxt) for nxt in next_states for _ in range(draws)])
actions=torch.arange(A).repeat_interleave(draws);states=torch.tensor(np.repeat(current[None,:],A*draws,axis=0))
with torch.no_grad():score=model.errors(states,actions,torch.tensor(candidate))[method].reshape(A,draws).mean(1).numpy()
best=np.flatnonzero(score>=score.max()-1e-9)
action=int(rng.integers(A)) if rng.random()<.1 else int(rng.choice(best))
state=next_states[action];counts[state]+=1;current=observation(state)
return counts.tolist()
def experiment(seed,updates=1000):
torch.manual_seed(seed);model=Models();optimizer=torch.optim.Adam((p for p in model.parameters() if p.requires_grad),lr=1e-3)
train=data(1000+seed,30000);test=data(8000+seed,12000);generator=torch.Generator().manual_seed(9000+seed)
result=[];checkpoints={0,100,300,1000}
for step in range(updates+1):
if step in checkpoints:
with torch.no_grad():
errors=model.errors(*test[:3]);mask=test[3]
row={'seed':seed,'step':step}
for name,e in zip(('pixels','icm','rnd'),errors):
row[name]={'tv':float(e[mask].mean()),'normal':float(e[~mask].mean())}
result.append(row)
if step==updates:break
ids=torch.randint(len(train[0]),(128,),generator=generator)
loss=model.loss(*(x[ids] for x in train[:3]));optimizer.zero_grad();loss.backward();optimizer.step()
paths=[greedy_rollout(model,method,20000+seed) for method in range(3)]
return result,pathsnpm run lab and open the connection link.runs=[experiment(seed) for seed in range(3)]
for seed,(rows,paths) in enumerate(runs):
print(seed, rows, {name: path[12] for name,path in zip(("pixels","icm","rnd"),paths)})npm run lab and open the connection link.In a practical implementation, normalize observations with accumulated statistics and measure the scale of the bonus before combining it with the external return. If the bonus dominates, the agent may optimize irrelevant novelty instead of the task. Two value heads allow assigning different discounts and masks to both returns: for example, an extrinsic episodic value and another intrinsic one that considers the sequence of episodes as a continuous process. That requires defining which observation follows a reset and not confusing an external truncation with a task termination. Normalization is part of the algorithm and its statistics must be saved if training is resumed or the predictor is used in evaluation.
Local Lab: PPO and RND in MiniGrid
The experiment uses MiniGrid-Empty-8x8-v0, whose external reward appears upon reaching the goal. The policy receives a partial 7 × 7 × 3 image divided by 10; it can only turn left, turn right, or advance. The RND predictor and fixed random target receive that observation normalized using running mean and variance, then clipped between -5 and 5. The bonus is the mean squared error between their features, divided by the running standard deviation of discounted intrinsic return. The policy combines external advantage with 0.1 times intrinsic advantage, using two separate value heads.
For external return, advantage propagation stops at termination or truncation, but truncations retain the value of the final observation. Intrinsic return is nonepisodic: after any reset, its next value uses the new initial observation. The random target network is not trained. Actual simulator positions are recorded only to measure coverage, never as policy input. Coverage counts distinct positions across all training environments, or across evaluation episodes; it does not guarantee complete discovery.
Each combination uses 102,400 training steps, plus 1,024 random steps to initialize observation statistics, and 50 greedy evaluation episodes without bonus. PPO and PPO+RND are compared with seeds 0, 1, and 2. You need PyTorch, NumPy, Gymnasium, and MiniGrid in your local environment; the experiment uses CPU and does not download data during the cells. Three actions suffice for this empty environment, but not for tasks that require collecting keys or opening doors.
In the indicated execution, the six combinations reached the goal in the 50 evaluation episodes: mean return 0.9613, training coverage 35 positions and evaluation coverage 10. The result leaves both variants unseparated in this empty task and these seeds; it does not demonstrate that RND is unnecessary in other environments nor that it helps to explore here. The environment and evaluation used make this experiment a reproducible check, not a general benchmark.
"""PPO y RND desde cero sobre MiniGrid; sin acceso a la posición en la política."""
import argparse,json,random
import numpy as np
import gymnasium as gym
import minigrid
import torch
from torch import nn
from torch.distributions import Categorical
torch.set_num_threads(1)
ENV='MiniGrid-Empty-8x8-v0'
class RunningStats:
def __init__(self,shape):
self.mean=np.zeros(shape,dtype=np.float64);self.var=np.ones(shape,dtype=np.float64);self.count=1e-4
def update(self,batch):
x=np.asarray(batch,dtype=np.float64);mean=x.mean(axis=0);var=x.var(axis=0);n=len(x)
delta=mean-self.mean;total=self.count+n
self.var=(self.var*self.count+var*n+delta**2*self.count*n/total)/total
self.mean+=delta*n/total;self.count=total
def normalize(self,x):
return np.clip((x-self.mean)/np.sqrt(self.var+1e-8),-5,5).astype(np.float32)
def flatten(obs):return np.asarray(obs['image'],dtype=np.float32).reshape(-1)
class Net(nn.Module):
def __init__(self,dim,actions):
super().__init__();self.body=nn.Sequential(nn.Linear(dim,128),nn.Tanh(),nn.Linear(128,128),nn.Tanh())
self.actor=nn.Linear(128,actions);self.ext=nn.Linear(128,1);self.intr=nn.Linear(128,1)
def forward(self,x):
h=self.body(x);return self.actor(h),self.ext(h).squeeze(-1),self.intr(h).squeeze(-1)
def feature_net(dim):return nn.Sequential(nn.Linear(dim,128),nn.ReLU(),nn.Linear(128,64))
def gae(rewards,values,next_values,ends,gamma,lam=.95):
result=torch.zeros_like(rewards);last=torch.zeros(rewards.shape[1])
for t in reversed(range(len(rewards))):
delta=rewards[t]+gamma*next_values[t]-values[t]
last=delta+gamma*lam*(1-ends[t])*last;result[t]=last
return result
def evaluate(policy,seed,episodes=50):
env=gym.make(ENV);scores=[];success=[];visited=set()
for episode in range(episodes):
obs,_=env.reset(seed=seed+episode);done=False;total=0.
while not done:
visited.add(tuple(map(int,env.unwrapped.agent_pos)))
x=torch.tensor(flatten(obs)/10.)[None]
with torch.no_grad():action=int(policy(x)[0].argmax(-1).item())
obs,reward,terminated,truncated,_=env.step(action);total+=float(reward);done=terminated or truncated
scores.append(total);success.append(total>0)
env.close()
return {'evaluation_episodes':episodes,'return_mean':float(np.mean(scores)),
'successes':int(sum(success)),'evaluation_coverage':len(visited)}
def train(use_rnd,seed,steps=102400):
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed)
n=8;horizon=64;envs=[gym.make(ENV) for _ in range(n)]
obs=[env.reset(seed=seed*100+i)[0] for i,env in enumerate(envs)]
dim=len(flatten(obs[0]));actions=3 # girar izquierda, girar derecha, avanzar
obs_stats=RunningStats((dim,));reward_stats=RunningStats(())
# Calentamiento para observaciones: acciones aleatorias independientes de la política.
for t in range(128):
obs_stats.update(np.stack([flatten(o) for o in obs]))
for i,env in enumerate(envs):
action=int(np.random.randint(actions));o,_,term,trunc,_=env.step(action)
obs[i]=env.reset()[0] if term or trunc else o
policy=Net(dim,actions);target=feature_net(dim);predictor=feature_net(dim)
for p in target.parameters():p.requires_grad_(False)
optimizer=torch.optim.Adam(list(policy.parameters())+list(predictor.parameters()),lr=3e-4,eps=1e-5)
visited=set();returns_filter=np.zeros(n);updates=steps//(n*horizon)
for update in range(updates):
xs=[];rnd_xs=[];acts=[];logs=[];ext_v=[];int_v=[];ext_r=[];int_r=[];ext_next=[];int_next=[];ends=[]
for _ in range(horizon):
for env in envs:visited.add(tuple(map(int,env.unwrapped.agent_pos)))
x=np.stack([flatten(o) for o in obs]);pt=torch.tensor(x/10.)
with torch.no_grad():
logits,v_e,v_i=policy(pt);distribution=Categorical(logits=logits)
action=distribution.sample();log=distribution.log_prob(action)
transitions=[env.step(int(a)) for env,a in zip(envs,action.numpy())]
finals=np.stack([flatten(row[0]) for row in transitions]);obs_stats.update(finals)
norm=obs_stats.normalize(finals);norm_t=torch.tensor(norm)
with torch.no_grad():raw=((predictor(norm_t)-target(norm_t))**2).mean(-1).numpy()
if use_rnd:
returns_filter=.99*returns_filter+raw;reward_stats.update(returns_filter)
intrinsic=raw/np.sqrt(reward_stats.var+1e-8)
else:intrinsic=np.zeros(n,dtype=np.float32)
next_obs=[];terminal=[];finished=[]
for env,row in zip(envs,transitions):
o,r,term,trunc,_=row;terminal.append(term);finished.append(term or trunc)
next_obs.append(env.reset()[0] if term or trunc else o)
reset_states=np.stack([flatten(o) for o in next_obs])
with torch.no_grad():
_,ve_final,_=policy(torch.tensor(finals/10.))
_,_,vi_next=policy(torch.tensor(reset_states/10.))
ext_bootstrap=ve_final*torch.tensor(np.logical_not(terminal),dtype=torch.float32)
xs.append(pt);rnd_xs.append(norm_t);acts.append(action);logs.append(log);ext_v.append(v_e);int_v.append(v_i)
ext_r.append(torch.tensor([row[1] for row in transitions],dtype=torch.float32));int_r.append(torch.tensor(intrinsic,dtype=torch.float32))
ext_next.append(ext_bootstrap);int_next.append(vi_next);ends.append(torch.tensor(finished,dtype=torch.float32));obs=next_obs
xs=torch.stack(xs);rnd_xs=torch.stack(rnd_xs);acts=torch.stack(acts);logs=torch.stack(logs)
ext_v=torch.stack(ext_v);int_v=torch.stack(int_v);ends=torch.stack(ends)
ae=gae(torch.stack(ext_r),ext_v,torch.stack(ext_next),ends,.99)
ai=gae(torch.stack(int_r),int_v,torch.stack(int_next),torch.zeros_like(ends),.99)
ext_returns=ae+ext_v;int_returns=ai+int_v;adv=ae+(.1*ai if use_rnd else 0.)
adv=(adv-adv.mean())/(adv.std(unbiased=False)+1e-8)
for _ in range(4):
logits,ve,vi=policy(xs);dist=Categorical(logits=logits);ratio=(dist.log_prob(acts)-logs).exp()
actor=-torch.minimum(ratio*adv,ratio.clamp(.8,1.2)*adv).mean()
loss=actor+.5*((ve-ext_returns)**2).mean()+.5*((vi-int_returns)**2).mean()-.01*dist.entropy().mean()
if use_rnd:loss+=((predictor(rnd_xs)-target(rnd_xs))**2).mean()
if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
optimizer.zero_grad();loss.backward();nn.utils.clip_grad_norm_(policy.parameters(),.5);optimizer.step()
for env in envs:env.close()
return {'method':'rnd' if use_rnd else 'ppo','seed':seed,'training_steps':updates*n*horizon,
'warmup_steps':128*n,'training_coverage':len(visited),**evaluate(policy,seed*10000+7000)}npm run lab and open the connection link.rnd_results=[train(use_rnd,seed,102400) for use_rnd in (False,True) for seed in range(3)]
for row in rnd_results: print(row)npm run lab and open the connection link.Commit to a hypothesis
In a bandit, an action reveals information without changing which actions are available afterward. In an MDP, an action also changes future states. Deep exploration through posterior sampling (PSRL) maintains a distribution over models, samples one at the start of an episode, solves that MDP, and follows its policy until the episode ends. An optimistic hypothesis can justify a coherent action sequence; the posterior is updated with observed transitions and rewards. This extends Thompson sampling to sequential decisions, but does not turn a neural approximation into an exact Bayesian sample.
Bootstrapped DQN approximates value diversity using multiple heads trained on experience samples and chooses one head per episode. Fixed random priors can preserve initial diversity, but shared representations or bootstrap masks do not guarantee a calibrated posterior. Osband and colleagues show how temporal persistence can improve exploration on chains; a curve measured at a few sizes does not by itself prove polynomial asymptotic scaling.
Go-Explore separates returning to a promising region from exploring onward: store descriptors of visited states, select one, and reach it before adding exploration. The original version uses simulator capabilities to return, then makes trajectories robust, as described by Ecoffet and colleagues. If a state cannot be restored, returning requires a learned policy and may fail; access to those capabilities must be accounted for when comparing budgets.
Exercises
Step 1 of 4. What happens when you sum the discounted differences up to T?
simhash_bonus(x, planes, counts, beta). planes is a matrix of shape (k,d) and x a vector of length d. Construct a tuple of k integers: bit 1 if the row's dot product with x is nonnegative, 0 otherwise. Use that tuple as a key in counts, calculate the bonus β/sqrt(n+1) using n previous visits, and increment the count. Return (clave, bonus). Do not modify x or planes.import numpy as np
def simhash_bonus(x, planes, counts, beta):
pass