Model-based RL: Dyna, probabilistic ensembles and planning with learned models
Study model-based RL through Dyna, uncertain dynamics ensembles, PETS planning, MBPO branched rollouts and value equivalence.
After this lesson you can
- Classify model-based methods by how they use the model.
- Implement Dyna-Q and measure how planning accelerates learning.
- Train probabilistic dynamics ensembles and distinguish aleatoric and epistemic uncertainty.
- Implement PETS with CEM and MBPO with branched rollouts in MuJoCo.
- Prove the simulation lemma and explain compounding error and model exploitation.
Before you start
- 22Soft actor-criticModel predictive controlTD(0)Experience replayMuJoCo physics simulationQ-learningRobust aggregate metrics
- 14Epistemic and aleatoric uncertainty decompositionGaussian process regression
- 11Bootstrap aggregatingVariance of an average of correlated predictors
- 06Evolution strategiesCovariance matrix adaptation evolution strategy
Learning a simulator
When each interaction with a robot costs time or wear, reusing data can be decisive. In model-based RL, a reward and transition model is learned or supplied and used to choose or improve actions. In model-free RL, a policy or value function is updated directly from experience without an explicit simulator. The boundary is not absolute: a system can combine both kinds of update.
A model can plan an action sequence, generate synthetic transitions for a model-free agent, or differentiate a loss through dynamics. Each use asks a different question: a very accurate one-step predictor can plan poorly if it fails precisely on actions the planner selects. Greater sample efficiency does not imply less total time: fitting networks and simulating many alternatives also costs compute.
Dyna: learn, act and plan
Dyna-Q interleaves a Q-learning update on real data, a tabular model update, and additional updates using transitions sampled from that model. For transition , the update is
The equation is the same for both data types, but their origin is not: a simulated transition does not itself correct a wrong model. In a deterministic environment the model can store the last observed transition per pair; in a stochastic environment one observation does not represent the full distribution. Prioritized sweeping maintains a queue of Bellman errors and propagates changes to predecessors instead of choosing all planning updates uniformly.
In Dyna-Q+ a simulated transition receives bonus , where counts real steps since that action was last tried in that state. Untried actions from a visited state are initialized in the model as staying in the same state with zero reward. The bonus modifies only simulated updates: real reward remains the environment’s. It can help discover a new shortcut, but introduces bias and does not guarantee enough exploration. Sutton and Barto’s book presents blocking and shortcut mazes and explains both modifications.
Learning dynamics and uncertainty
A learned dynamics model receives state and action and predicts the next state or its distribution. A common parametrization predicts increment and adds it to state; this can ease learning when many components change slowly. It is not universal: predicting absolute state may work better in other representations or scales. Normalize inputs and outputs per dimension, save training statistics and apply the same ones at evaluation.
A diagonal Gaussian network produces and . Negative log-likelihood loss, omitting a constant, sums per component
Large variance reduces the residual penalty, but the logarithmic term prevents increasing it without cost. Bounding log variance helps numerical stability and also restricts the model family. Normalization must include its inverse transformation to original units: variance in normalized coordinates is multiplied by the scale squared.
For example, if an increment coordinate is normalized by dividing by standard deviation , a predicted variance of 0.25 on that scale corresponds to in original units. Adding a normalized deviation directly to physical state would mix units. To validate the model, retain separate real data when possible, compare per-component residual and calibration, and evaluate rollouts from states and actions not used in fitting. Small mean error can conceal rare safety-relevant failures.
A probabilistic ensemble combines models with different initializations and training samples. If model predicts mean and variance for one component, uniform-mixture variance is
The first term measures within-model dispersion and is commonly used as an approximation to aleatoric uncertainty; the second measures disagreement among means and is used as an epistemic signal. This is an identity for the mixture, not a calibration guarantee. Every model can err similarly outside the data, and internal variance can absorb approximation errors. Low disagreement does not demonstrate safety.
The figure trains five small Gaussian networks in the browser, each with eight tanh units, 900 descent steps on the loss above, and a fixed bootstrap sample of visible points. Log variance is clipped to . Curves are model means; initial points form an explicit toy dataset and you choose new points. The aleatoric indicator is the square root of mean variance, not the mean standard deviation. Disagreement can rise away from data but need not: initialization, family and optimization can produce misplaced confidence. A maximum of 20 points limits browser work.
Figure data are prerecorded predictions from ten networks actually trained on an explicit simulated pendulum: , . The two datasets contain 64 transitions with or 512 with ; in both, and are uniform on . Gaussian noise with standard deviations 0.002 and 0.01 is added to training increments. Each dataset trains five two-layer 32-unit networks, bootstrap and 350 NLL updates with fixed seed. The actual trajectory starts at and uses for 100 steps, without transition noise. Each network rolls out its mean: trajectory disagreement does not include aleatoric-noise propagation. The last indicator is predicted one-step Gaussian standard deviation, not a 100-step confidence band. One model has zero disagreement by construction, even with large error.
Compounding error and the simulation lemma
Compounding error arises because one prediction becomes the next input. A small deviation can take the rollout outside the training distribution, where error is no longer the measured one-step error. A planner can select actions exploiting an optimistic prediction even if no real action achieves that reward. Uncertainty penalties or a short horizon can help, but neither guarantees avoidance of model exploitation.
For a concrete bound, consider two MDPs with the same stationary policy, , both rewards in , uniform reward difference at most and uniform transition difference , with . Then
The proof begins with Bellman: . The resolvent’s sup norm is at most . Since , the difference in its expectations under two distributions is bounded by total variation times that range. If only is assumed and negative rewards are allowed, ‘s range may double and this total-variation convention gives a factor 2 in the second term. If denotes L1 norm, in discrete spaces; do not mix conventions. The uniform bound is worst-case and does not predict observed error will reach it.
The quadratic factor in has two sources. One power appears when bounding future value multiplying transition error; the other when propagating that error backward through all future steps. If approaches one, the bound can become large even for small error. A shorter rollout limits how many times the model is composed before returning to real data, though it removes neither initial-step error nor bias of a policy seeking model failures.
CEM, PETS and probabilistic models
In sampling-based planning, action sequences are generated, simulated in the model, and higher-return sequences preferred. CEM fits a distribution to elites and repeats. If actions are clipped to bounds before fitting a diagonal Gaussian, this is a practical approximation, not exact fitting of a truncated Gaussian.
The figure uses a point starting at , goal , circular obstacle of radius 0.7 at , and ten two-dimensional displacements bounded per component to . Each sequence pays , 50 per sampled state inside the obstacle and five times terminal squared error. Six batches are generated with a fixed seed, mean and diagonal standard deviation fitted to elites, and minimum standard deviation 0.05 imposed. The mean curve need not be an elite or avoid the obstacle; collision is checked at discrete states and a finite penalty does not guarantee safety.
PETS combines an ensemble of probabilistic dynamics with CEM and particle propagation. In one variant each particle keeps its ensemble member throughout its trajectory; in another the member is resampled at each step. Choice changes temporal uncertainty correlation. Chua and colleagues study these alternatives and the combination of uncertainty and planning. PILCO uses Gaussian processes to learn dynamics and optimize a policy, with different scalability and approximation tradeoffs; not all model-based methods use networks or CEM.
In a Gaussian process, the unknown transition function receives a function prior and data produce a posterior predictive distribution. Its mean and variance depend on kernel, hyperparameters and noise assumption; far from observations uncertainty can grow toward the prior’s, but remains a consequence of the chosen model. Classical dense inference factors a matrix growing with transition count, with generally cubic cost. PILCO approximately propagates uncertainty and optimizes a policy through the model; it does not ensure the kernel or approximations capture all robot dynamics.
MBPO and value equivalence
MBPO trains a model on real data, takes states from a real buffer and generates short rollouts with the current policy. These transitions are mixed with real data to update an agent such as SAC. Starting from real states limits model-rollout length but removes neither bias nor the possibility that generated states and actions are unreliable. Janner and colleagues analyze the tradeoff among length, model error and policy improvement.
Value equivalence changes the model objective: for a family of policies and value functions, it suffices for the model-induced Bellman operator to match the environment’s on that family. Two models can predict different observations and be equivalent for those evaluations. The property depends on which policies and values are included; it does not guarantee fidelity for every future task or make a wrong model physically correct. Grimm and colleagues formalize this principle, helping explain why some planning models predict value-relevant quantities instead of reconstructing every detail.
Lab: a shortcut appears
The next maze adapts Sutton and Barto’s shortcut problem: a 6-by-9 grid, start , goal and barrier in row 3. At real step 1500 a second exit opens in column 8. The agent receives reward 1 upon reaching the goal and returns to start; other steps reward 0. Compare Q-learning without planning, Dyna-Q and Dyna-Q+ with five planning steps per interaction. The plot shows the mean over three seeds and cumulative reward, not independent episodes or a guarantee the bonus always helps. Methods differ in update count, which also costs compute in this small example.
This model stores the last transition for each state–action pair, and planning steps uniformly choose available pairs. Dyna-Q+ adds untried actions from visited states to the model. Compare cumulative-reward slopes before and after the change: a larger slope means more goals per step in that interval, but the result combines exploration, planning and seed randomness. Here the bonus can even reduce reward during part of the run.
import numpy as np
import matplotlib.pyplot as plt
# Cuadrícula 6×9: fila 0 arriba; barrera fila 3, columnas 1...8.
# En el paso 1500 se abre también la columna 8. Inicio (5,3), meta (0,8).
H,W=6,9
start=(5,3); goal=(0,8); moves=((-1,0),(1,0),(0,-1),(0,1))
alpha,gamma,epsilon,kappa=.1,.95,.1,.001
steps,change,planning=3000,1500,5
def transition(state,action,t):
row,col=state; dr,dc=moves[action]
candidate=(min(H-1,max(0,row+dr)),min(W-1,max(0,col+dc)))
blocked={(3,c) for c in range(1,9 if t<change else 8)}
if candidate in blocked: candidate=state
return candidate,float(candidate==goal),candidate==goal
def run(seed,n,plus=False):
rng=np.random.default_rng(seed)
q=np.zeros((H,W,4))
model={}
last=np.zeros((H,W,4),dtype=int)
state=start
cumulative=np.zeros(steps)
total=0
def update(s,a,reward,next_state,terminal):
target=reward+(0 if terminal else gamma*np.max(q[next_state]))
q[s][a]+=alpha*(target-q[s][a])
for t in range(steps):
if rng.random()<epsilon:
action=int(rng.integers(4))
else:
best=np.flatnonzero(q[state]==q[state].max())
action=int(rng.choice(best))
next_state,reward,done=transition(state,action,t)
update(state,action,reward,next_state,done)
if plus:
# Al visitar por primera vez un estado, acciones aún no probadas
# se modelan como permanecer ahí, recompensa cero.
for a in range(4):
model.setdefault((state,a),(state,0.,False))
model[(state,action)]=(next_state,reward,done)
last[state][action]=t+1
keys=list(model)
for _ in range(n):
s,a=keys[int(rng.integers(len(keys)))]
ns,r,terminal=model[(s,a)]
bonus=kappa*np.sqrt((t+1)-last[s][a]) if plus else 0.
update(s,a,r+bonus,ns,terminal)
total+=reward; cumulative[t]=total
state=start if done else next_state
return cumulative
fig,ax=plt.subplots(figsize=(7,3.5))
for name,n,plus in [('Q sin planificación',0,False),('Dyna-Q',planning,False),('Dyna-Q+',planning,True)]:
curves=np.stack([run(seed,n,plus) for seed in range(3)])
print(name,'recompensa acumulada media antes/después del cambio:',
curves[:,change-1].mean(),curves[:,-1].mean())
ax.plot(np.arange(steps),curves.mean(axis=0),label=name)
ax.axvline(change,color='black',linestyle='--',label='se abre atajo')
ax.set_xlabel('pasos reales');ax.set_ylabel('recompensa acumulada media');ax.legend()
fig.tight_layout();plt.show()Lab: PETS and MBPO on HalfCheetah
Install NumPy, PyTorch and gymnasium[mujoco]==1.4.0. The next program uses actual HalfCheetah-v5 and selects GPU if available. ORYON_MODEL_METHOD chooses sac, pets or mbpo; run all three separately with ORYON_MODEL_OUT pointing to a common folder. Full mode uses five seeds and 100000 real transitions per seed for each method. ORYON_QUICK=1 limits each to one seed, 256 transitions and 64-step episodes: it checks the pipeline, not learning.
The ensemble has five diagonal Gaussian networks; it predicts state increments and reward and normalizes each dimension. Scales are fixed using all first-warmup data. Each fit reserves 20% for an indicative normalized squared error; that set is redrawn and may have participated in earlier fits, so it is not an independent external test. Each network learns from a bootstrap of the current fit’s training portion. Log variance is clipped to [−5,1] and normalized samples to [−10,10]; these limits can bias rollouts away from data.
PETS uses CEM on predicted reward: in full mode, 256 sequences, 32 elites, five iterations, horizon 15 and five particles per sequence; each particle fixes a network member throughout its trajectory and samples Gaussian noise. Quick mode uses 32 sequences, four elites, three iterations, horizon 5 and one particle. MBPO generates length-5 branches from real states in full mode, or length 2 in quick mode, and mixes equal real and imagined samples when a synthetic buffer exists. It discards the synthetic buffer after refitting the model. Baseline SAC uses only real transitions; actor, critic and temperature updates are custom. HalfCheetah does not terminate on falling under this contract; the external limit truncates evaluation and is not treated as termination for bootstrap.
import json, math, os, random, time
from pathlib import Path
import gymnasium as gym
import mujoco
import numpy as np
import torch
from torch import nn
from torch.distributions import Normal
from torch.nn import functional as F
torch.set_num_threads(1)
quick=os.getenv('ORYON_QUICK','0')=='1'
method=os.getenv('ORYON_MODEL_METHOD','mbpo')
if method not in ('sac','pets','mbpo'): raise ValueError('Método desconocido')
root=Path(os.getenv('ORYON_MODEL_OUT','oryon-model'))
root.mkdir(parents=True,exist_ok=True)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seeds=[0] if quick else list(range(5))
steps,warmup,interval,episodes=(256,64,128,2) if quick else (100_000,5_000,10_000,5)
model_every=64 if quick else 1000
model_updates=20 if quick else 200
batch=32 if quick else 256
width=64 if quick else 256
rollout_horizon=2 if quick else 5
cem_horizon=5 if quick else 15
population=32 if quick else 256
elite=4 if quick else 32
cem_iters=3 if quick else 5
particles=1 if quick else 5
gamma,tau=.99,.005
def make_env():
return gym.make('HalfCheetah-v5',max_episode_steps=64) if quick else gym.make('HalfCheetah-v5')
def net(inputs,outputs):
return nn.Sequential(nn.Linear(inputs,width),nn.ReLU(),nn.Linear(width,width),nn.ReLU(),nn.Linear(width,outputs))
class Actor(nn.Module):
def __init__(self,od,ad):
super().__init__();self.net=net(od,2*ad)
def sample(self,s):
mu,ls=self.net(s).chunk(2,-1);dist=Normal(mu,ls.clamp(-5,2).exp());u=dist.rsample()
return torch.tanh(u),(dist.log_prob(u)-2*(math.log(2)-u-F.softplus(-2*u))).sum(-1,keepdim=True)
def deterministic(self,s): return torch.tanh(self.net(s).chunk(2,-1)[0])
class Dynamics(nn.Module):
def __init__(self,od,ad):
super().__init__();self.network=net(od+ad,2*(od+1));self.size=od+1
def forward(self,x):
z=self.network(x);return z[:,:self.size],z[:,self.size:].clamp(-5,1)
class Replay:
def __init__(self,capacity,od,ad):
self.capacity=capacity;self.size=0;self.pos=0
self.s=np.empty((capacity,od),np.float32);self.a=np.empty((capacity,ad),np.float32)
self.r=np.empty((capacity,1),np.float32);self.ns=np.empty_like(self.s);self.d=np.empty_like(self.r)
def add(self,s,a,r,ns,d):
i=self.pos;self.s[i]=s;self.a[i]=a;self.r[i]=r;self.ns[i]=ns;self.d[i]=d
self.pos=(i+1)%self.capacity;self.size=min(self.size+1,self.capacity)
def sample(self,n,rng):
i=rng.integers(self.size,size=n)
return tuple(torch.as_tensor(x[i],device=device) for x in (self.s,self.a,self.r,self.ns,self.d))
def run(seed):
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed)
if torch.cuda.is_available():torch.cuda.manual_seed_all(seed)
rng=np.random.default_rng(seed);env=make_env();ev=make_env()
obs,_=env.reset(seed=seed);env.action_space.seed(seed)
low,high=env.action_space.low,env.action_space.high
od,ad=obs.size,low.size
if np.any(high<=low) or not np.isfinite(low).all() or not np.isfinite(high).all(): raise ValueError('Acciones no acotadas')
real=Replay(steps,od,ad);imagined=Replay(10000 if quick else 100_000,od,ad)
actor=Actor(od,ad).to(device)
q1,q2,t1,t2=[net(od+ad,1).to(device) for _ in range(4)]
t1.load_state_dict(q1.state_dict());t2.load_state_dict(q2.state_dict())
ao=torch.optim.Adam(actor.parameters(),lr=3e-4)
qo=torch.optim.Adam(list(q1.parameters())+list(q2.parameters()),lr=3e-4)
log_alpha=torch.tensor(0.,device=device,requires_grad=True)
alpha_opt=torch.optim.Adam([log_alpha],lr=3e-4)
models=[Dynamics(od,ad).to(device) for _ in range(5)] if method!='sac' else []
optimizers=[torch.optim.Adam(m.parameters(),lr=.001) for m in models]
xm=xs=ym=ys=None
model_ready=False;model_mse=None;model_generation=0
history=[];started=time.perf_counter()
def tensor(x):return torch.as_tensor(np.asarray(x),dtype=torch.float32,device=device)
def physical(a):return (low+(a+1)*(high-low)/2).astype(env.action_space.dtype)
def fit_models():
nonlocal xm,xs,ym,ys,model_ready,model_mse,model_generation
n=real.size
x=np.concatenate((real.s[:n],real.a[:n]),axis=1)
y=np.concatenate((real.ns[:n]-real.s[:n],real.r[:n]),axis=1)
# Las escalas se fijan al primer ajuste; la división temporal de holdout
# se vuelve a sortear cada ajuste y nunca entra en el bootstrap de ese ajuste.
if xm is None:
xm=tensor(x.mean(0));xs=tensor(np.maximum(x.std(0),.01))
ym=tensor(y.mean(0));ys=tensor(np.maximum(y.std(0),.01))
permutation=rng.permutation(n);split=max(1,int(.8*n))
train_ix=permutation[:split];hold_ix=permutation[split:]
X=tensor(x);Y=tensor(y);xn=(X-xm)/xs;yn=(Y-ym)/ys
scores=[]
for model,opt in zip(models,optimizers):
boot=rng.choice(train_ix,size=len(train_ix),replace=True)
for _ in range(model_updates):
ix=rng.choice(boot,size=min(batch,len(boot)),replace=True)
mean,lv=model(xn[ix])
loss=.5*((mean-yn[ix]).square()*torch.exp(-lv)+lv).mean()
opt.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),10.);opt.step()
if len(hold_ix):
with torch.no_grad():
pred,_=model(xn[hold_ix]);scores.append(float((pred-yn[hold_ix]).square().mean()))
model_mse=float(np.mean(scores)) if scores else None
model_ready=True;model_generation+=1
def predict_model(states,actions,which,generator=None):
# Cada fila usa su miembro fijado durante la trayectoria; muestrea ruido gaussiano.
x=(torch.cat((states,actions),-1)-xm)/xs
out=torch.empty((states.shape[0],od+1),device=device)
for i,model in enumerate(models):
mask=which==i
if mask.any():
mean,lv=model(x[mask])
sample=mean+torch.exp(.5*lv)*torch.randn(mean.shape,device=device,generator=generator)
out[mask]=sample.clamp(-10,10)*ys+ym
return states+out[:,:od],out[:,od:]
def generate_rollouts():
if not model_ready:return
# Se descartan datos imaginados del modelo anterior tras reentrenarlo.
imagined.size=0;imagined.pos=0
n=64 if quick else 1000
states=real.sample(n,rng)[0]
which=torch.as_tensor(rng.integers(0,5,n),device=device)
with torch.no_grad():
for _ in range(rollout_horizon):
action,_=actor.sample(states);nxt,reward=predict_model(states,action,which)
for s,a,r,ns in zip(states.cpu().numpy(),action.cpu().numpy(),reward.cpu().numpy(),nxt.cpu().numpy()):
imagined.add(s,a,r,ns,0.)
states=nxt
def plan(state,stream,generator=None):
mean=torch.zeros((cem_horizon,ad),device=device);std=torch.ones_like(mean)*.6
with torch.no_grad():
for _ in range(cem_iters):
actions=(mean+std*torch.randn((population,cem_horizon,ad),device=device,generator=generator)).clamp(-1,1)
states=tensor(np.repeat(np.asarray(state)[None],population*particles,axis=0))
which=torch.as_tensor(stream.integers(0,5,population*particles),device=device)
score=torch.zeros(population*particles,device=device)
for t in range(cem_horizon):
expanded=actions[:,t,:].repeat_interleave(particles,dim=0)
states,reward=predict_model(states,expanded,which,generator)
score+=reward[:,0]*(gamma**t)
candidate_score=score.reshape(population,particles).mean(dim=1)
top=actions[torch.topk(candidate_score,elite).indices]
mean=top.mean(0);std=top.std(0,unbiased=False).clamp_min(.05)
return mean[0].cpu().numpy()
def update_sac():
n_real=batch if method!='mbpo' or imagined.size==0 else batch//2
parts=[real.sample(n_real,rng)]
if n_real<batch:parts.append(imagined.sample(batch-n_real,rng))
s,a,r,ns,d=[torch.cat([p[i] for p in parts]) for i in range(5)]
alpha=log_alpha.exp().detach()
with torch.no_grad():
na,nlogp=actor.sample(ns);x=torch.cat((ns,na),-1)
target=r+gamma*(1-d)*(torch.minimum(t1(x),t2(x))-alpha*nlogp)
x=torch.cat((s,a),-1)
loss=F.mse_loss(q1(x),target)+F.mse_loss(q2(x),target)
qo.zero_grad();loss.backward();qo.step()
for p in list(q1.parameters())+list(q2.parameters()):p.requires_grad_(False)
pa,logp=actor.sample(s);x=torch.cat((s,pa),-1)
aloss=(alpha*logp-torch.minimum(q1(x),q2(x))).mean()
ao.zero_grad();aloss.backward();ao.step()
for p in list(q1.parameters())+list(q2.parameters()):p.requires_grad_(True)
alpha_loss=-(log_alpha*(logp.detach()-ad)).mean()
alpha_opt.zero_grad();alpha_loss.backward();alpha_opt.step()
with torch.no_grad():
for target_net,online in ((t1,q1),(t2,q2)):
for tp,p in zip(target_net.parameters(),online.parameters()):tp.lerp_(p,tau)
if not torch.isfinite(loss+aloss+alpha_loss):raise FloatingPointError('Pérdida no finita')
def evaluate():
out=[]
for ep in range(episodes):
state,_=ev.reset(seed=100000+1000*seed+ep);total=0.;length=0
eval_rng=np.random.default_rng(900000+1000*seed+ep)
eval_gen=torch.Generator(device=device).manual_seed(900000+1000*seed+ep)
while True:
if method=='pets':a=plan(state,eval_rng,eval_gen) if model_ready else eval_rng.uniform(-1,1,ad)
else:
with torch.no_grad():a=actor.deterministic(tensor(state).unsqueeze(0))[0].cpu().numpy()
state,r,term,trunc,_=ev.step(physical(a));total+=float(r);length+=1
if term or trunc:break
out.append({'return':total,'length':length,'terminated':bool(term),'truncated':bool(trunc)})
return out
try:
for step in range(1,steps+1):
if step<=warmup:
a=rng.uniform(-1,1,ad).astype(np.float32)
elif method=='pets':a=plan(obs,rng)
else:
with torch.no_grad():a=actor.sample(tensor(obs).unsqueeze(0))[0][0].cpu().numpy()
nxt,reward,term,trunc,_=env.step(physical(a))
real.add(obs,a,reward,nxt,float(term))
obs=env.reset()[0] if term or trunc else nxt
if method!='sac' and step>=warmup and (step-warmup)%model_every==0:
fit_models()
if method=='mbpo':generate_rollouts()
if method!='pets' and step>warmup:update_sac()
if step%interval==0:
result=evaluate()
row={'step':step,'seconds':time.perf_counter()-started,'episodes':result,
'model_holdout_normalized_mse':model_mse,'model_generation':model_generation,
'real_buffer':real.size,'imagined_buffer':imagined.size}
history.append(row);print(method,seed,row,flush=True)
return {'method':method,'environment':'HalfCheetah-v5','quick':quick,'seed':seed,'steps':steps,
'device':str(device),'gymnasium':gym.__version__,'mujoco':mujoco.__version__,
'torch':torch.__version__,'numpy':np.__version__,'particles':particles,'history':history}
finally:
env.close();ev.close()
for seed in seeds:
report=run(seed)
(root/f'{method}-seed{seed}.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')npm run lab and open the connection link.Analysis requires reports from all three methods, checks method, seeds, budget, evaluation points, versions and device, and plots return per real transition and per mean wall time. First average each training run’s episodes, then calculate interquartile mean across seeds. One seed in quick mode is only a functional check; five seeds still make a small comparison. Time includes evaluation and model training but depends on load and hardware. The time curve uses mean time at each transition count without interpolation to a common instant. Methods have different computational costs, and the program does not claim full-benchmark results before execution.
import json, os
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
root=Path(os.getenv('ORYON_MODEL_OUT','oryon-model'))
quick=os.getenv('ORYON_QUICK','0')=='1'
seeds=[0] if quick else list(range(5))
steps=256 if quick else 100_000
every=128 if quick else 10_000
episodes=2 if quick else 5
methods=('sac','pets','mbpo')
def iqm(values):
x=np.sort(np.asarray(values,dtype=float))
n=x.size
weights=np.maximum(0,np.minimum(np.arange(n)+1,.75*n)-np.maximum(np.arange(n),.25*n))
return float(np.sum(weights*x)/weights.sum())
all_data={};versions=set();devices=set()
for method in methods:
runs=[]
for seed in seeds:
path=root/f'{method}-seed{seed}.json'
if not path.exists():raise FileNotFoundError('Ejecuta primero '+method+' y conserva '+str(path))
report=json.loads(path.read_text(encoding='utf-8'))
if (report['method']!=method or report['environment']!='HalfCheetah-v5' or
report['quick']!=quick or report['seed']!=seed or report['steps']!=steps):
raise ValueError('Informe incompatible: '+str(path))
versions.add(tuple(report[k] for k in ('gymnasium','mujoco','numpy','torch')))
devices.add(report['device'])
hist=report['history']
if [x['step'] for x in hist]!=list(range(every,steps+1,every)):
raise ValueError('Faltan puntos de evaluación: '+str(path))
if any(len(x['episodes'])!=episodes for x in hist):raise ValueError('Faltan episodios: '+str(path))
runs.append(hist)
all_data[method]=runs
if len(versions)!=1 or len(devices)!=1:raise ValueError('Versiones o dispositivos distintos')
fig,axes=plt.subplots(1,2,figsize=(10,3.5))
for method,runs in all_data.items():
scores=np.array([[np.mean([e['return'] for e in x['episodes']]) for x in run] for run in runs])
seconds=np.array([[x['seconds'] for x in run] for run in runs])
central=np.array([iqm(scores[:,i]) for i in range(scores.shape[1])])
axes[0].plot(range(every,steps+1,every),central,label=method)
axes[1].plot(seconds.mean(axis=0),central,label=method)
print(method,'retornos finales por semilla',scores[:,-1],'segundos finales',seconds[:,-1])
axes[0].set_xlabel('transiciones reales')
axes[1].set_xlabel('segundos medios con evaluaciones')
for ax in axes:ax.set_ylabel('IQM de retornos por semilla');ax.legend()
fig.suptitle('HalfCheetah-v5'+(' (comprobación corta)' if quick else ''))
fig.tight_layout();plt.show()npm run lab and open the connection link.To reproduce the prerecorded pendulum data, this program saves pendulum_traces.json in the current directory. It requires NumPy and PyTorch; the 100 evaluation steps and two training distributions are defined in the code. Output is a figure data file, not HalfCheetah training.
import json, math
from pathlib import Path
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
dt=.05
def transition(state,action):
theta,omega=state[...,0],state[...,1]
return np.stack([theta+dt*omega,omega+dt*(-np.sin(theta)-.1*omega+action)],axis=-1)
def train(kind):
rng=np.random.default_rng(25+(kind=='amplios'))
n=64 if kind=='locales' else 512
angle=.5 if kind=='locales' else 3.2
states=np.column_stack([rng.uniform(-angle,angle,n),rng.uniform(-2,2,n)])
actions=rng.uniform(-2,2,n)
inp=np.column_stack([states,actions]).astype('float32')
delta=(transition(states,actions)-states+rng.normal(0,[.002,.01],(n,2))).astype('float32')
xm=inp.mean(0); xs=inp.std(0)+1e-6; ym=delta.mean(0); ys=delta.std(0)+1e-6
x=torch.tensor((inp-xm)/xs); y=torch.tensor((delta-ym)/ys)
models=[]
for seed in range(5):
torch.manual_seed(seed+7); ix=rng.integers(n,size=n)
net=nn.Sequential(nn.Linear(3,32),nn.Tanh(),nn.Linear(32,32),nn.Tanh(),nn.Linear(32,4))
opt=torch.optim.Adam(net.parameters(),lr=.003)
for epoch in range(350):
output=net(x[ix]); mean,logvar=output[:,:2],output[:,2:].clamp(-8,2)
loss=.5*((mean-y[ix]).square()*torch.exp(-logvar)+logvar).mean()
opt.zero_grad(); loss.backward(); opt.step()
models.append(net)
state=np.array([1.2,0.]); truth=[state.tolist()]
controls=[.5*math.sin(t*.1) for t in range(100)]
for u in controls:
state=transition(state,u); truth.append(state.tolist())
predictions=[]; one_step_variances=[]
for net in models:
s=np.array([1.2,0.]); path=[s.tolist()]; var_path=[]
with torch.no_grad():
for u in controls:
v=(np.r_[s,u].astype('float32')-xm)/xs
out=net(torch.tensor(v)).numpy(); delta=out[:2]*ys+ym
variance=np.exp(np.clip(out[2:],-8,2))*ys**2
s=s+delta; path.append(s.tolist()); var_path.append(variance.tolist())
predictions.append(path);one_step_variances.append(var_path)
return {'n':n,'angle_range':[-angle,angle],'truth':truth,'predictions':predictions,
'one_step_variances':one_step_variances,'controls':controls}
result={kind:train(kind) for kind in ('locales','amplios')}
Path('pendulum_traces.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
for kind,d in result.items():
print(kind, 'paso 100 theta real',d['truth'][-1][0], 'predicciones',[p[-1][0] for p in d['predictions']])
Exercises
Step 1 of 4. What identity follows by subtracting Bellman equations?
import numpy as np
def cem_plan(model, cost, state, horizon, pop, elites, iters):
pass