Latent world models: World Models, PlaNet and Dreamer
Study latent world models from World Models and PlaNet to Dreamer, DreamerV3 techniques, TD-MPC2 and transformer or diffusion alternatives.
After this lesson you can
- Describe an RSSM and derive its sequential ELBO.
- Explain imagination training with lambda returns and gradients through dynamics.
- Implement symlog, two-hot and DreamerV3 return normalization.
- Train a reduced Dreamer within 8 GB of VRAM.
- Compare Dreamer, TD-MPC2 and model-free methods by problem and budget.
Before you start
- 22Learned dynamics modelsValue-equivalent modelsActor-criticSampling-based planningλ-returnValue learning as classificationCompounding model error
- 19Variational autoencoderDecompositions of the VAE ELBOGumbel-softmax relaxation
- 17Gated recurrent unitRecurrent neural network (Elman network)
- 14Linear Gaussian state-space modelKalman filter
Practicing in a latent space
An image contains many pixels that are not decisive for action. A latent world model compresses observation–action history into an internal state, learns its evolution and predicts useful signals. The agent can rehearse decisions in that state without executing every action in the environment. Imagination adds no new information about a region the model never learned: it can amplify its errors too.
World Models combined a visual VAE, a recurrent network predicting a mixture of latent futures, and a controller trained using the model. PlaNet introduced stochastic recurrent dynamics and planned action sequences with CEM in that space. Dreamer retains latent dynamics and learns a policy and critic from imagined trajectories.
Frames come from a local CartPole-v1 run converted to grayscale . The lab’s reduced model was trained with 2048 real transitions from a random policy and 300 updates, seed 0. For the sequence shown, an auxiliary state-based policy recorded 16 frames and their actions; this is not an evaluation of the learned actor. Through the selected step the model uses the posterior conditioned on the real image. Thereafter it keeps the same action sequence but uses its prior without receiving new images. Reconstruction is approximate and can ignore relevant details; a plausible image does not prove dynamics or policy correct. The lab program can reproduce the images.
The RSSM and its ELBO
An RSSM combines deterministic memory with stochastic variable . One convention is
The prior predicts the next latent without seeing the new observation; the posterior incorporates it via an encoder. Recurrent memory summarizes historical information and the stochastic part represents alternatives not determined by that memory. Architecture does not guarantee that learned state suffices for the task or that its uncertainty is calibrated.
Distinguish three operations often all called “prediction.” During collection the agent acts in the environment and receives real images and rewards. During fitting the posterior uses those images to propose latent states explaining the sequence, while the prior learns to anticipate them from history. During open-loop imagination, no image corrects each step: the prior sample feeds the next transition. Thus good observation-conditioned reconstruction does not prove accurate long prediction. The figure shows where the regime changes.
The problem can also be partially observable. Two similar pendulum images could correspond to opposite velocities and require different actions. Recurrent memory can integrate successive images and prior actions to distinguish them, though a short training sequence or poorly inferred initial state can limit that advantage. The stochastic model represents multiple possible futures; its samples alone are not reliable confidence intervals. Observed variation can reflect real uncertainty as well as insufficient representation or fitting errors.
Assume given actions and a generative model factorizing emissions and priors , with computed deterministically. The amortized posterior factorizes as a product of . Multiply and divide the likelihood integral by that posterior and apply Jensen to the logarithm. With expectations over the sequential posterior,
The outer expectation of each KL is necessary because depends on previously sampled latents. At the initial instant omit reward and continuation emissions, or fix them as constants, since there is no previous transition. For episodes, denotes continuation: true termination may set , while an external time limit must not be confused with an absorbing state. Reward and action indexing must match the data; in the lab reward observed after is predicted from posterior state at .
The bound reveals a useful tension. Emission rewards states able to explain data; KL penalizes differences between the state inferred after seeing an observation and the state the prior would anticipate. If the posterior ignores observations completely, the prior can match it with small KL, but predictions may lose necessary information. If the posterior encodes unpredictable details of each image, reconstruction can improve while the prior cannot follow open-loop. Term weights, latent size and sequence length influence this tradeoff.
In a batch of subsequences, initializing and to zero simplifies implementation but introduces artificial history at the start of every fragment. An alternative is burn-in that updates state with previous observations before calculating main losses. A subsequence must also not cross a reset as if it were an ordinary transition. The lab keeps episodes separate and explicitly shows the initial-state simplification; its results are not an isolated measure of the full method.
The diagram summarizes one instant and its connection to the next. “Previous” combines prior state and action. The prior branch predicts from ; the posterior also uses the observation. Heads use both and and the next state also receives and the current action, though these connections are omitted from the diagram. Color highlights local paths, not all backpropagation-through-time dependencies. In dynamics KL the posterior is stopped and the prior updated; in representation KL the prior is stopped and the posterior updated. Since feeds both branches, it can receive gradients through the branch remaining active. Reconstruction and reward heads have distinct parameters and signals.
Acting inside the dream
In imagination training, start from a replay-inferred state and alternate actor action, model transition, and reward and continuation prediction. For horizon , one return form is
The critic learns with appropriately detached targets and the actor seeks high-value actions. In the original Dreamer formulation, differentiable dynamics propagate gradients from rewards and values to actions. Freezing model parameters during the actor step does not mean cutting derivatives with respect to model input. With categorical latents or actions, an ordinary discrete sample has no useful derivative; a straight-through estimator provides a biased approximation, whereas REINFORCE uses a score-function estimator with a different variance tradeoff.
Not all versions use the same estimator. The DreamerV3 paper presents REINFORCE for discrete and continuous actions, with stopped advantages and normalization; it should not be described as identical to original Dreamer’s pathwise gradient. The lab uses a reduced version with straight-through categorical samples and gradients through the model to make the mechanism visible. This is a pedagogical choice, not a faithful reproduction of all V3 decisions.
To interpret return, consider two extremes. With , the target uses one-step reward and bootstraps from predicted next-state value. With near 1, it incorporates more imagined rewards before depending on the final critic. This changes the balance between value errors and accumulated dynamics and reward errors. Predicted continuation reduces later-step contribution after a likely ending; errors in that head also bias targets. Neither extreme removes every model error.
An actor can exploit regions where the model is optimistic even if physically impossible. More imagined steps do not necessarily solve this: the actor itself can seek erroneous predictions. Evaluate in the environment, retain separate seeds and compare with an agent learning from the same real interactions. Inspect predicted rewards, continuations and errors at different horizons to locate discrepancy. The lab’s evaluated policy receives real observations at every step and uses the posterior, not a succession of self-generated images.
Robustness, scale and categorical losses
DreamerV3 uses categorical latents and mixes their probabilities with a small uniform mass to avoid exact zeros. It separates the two KL terms using stop-gradient and uses free bits: in the cited formulation, each KL loss is lower-bounded at one nat. Below threshold that branch gives no gradient, avoiding forced compression when KL is already small. Reconstruction, reward and continuation still train. Each term’s scale and where thresholding applies matter.
The symmetric transformation and its inverse are
Near zero they approximate the identity; for large magnitudes symlog compresses positive and negative values. In symlog regression, the network predicts on transformed scale and symexp is applied when reading output. Squared loss and gradient on that scale have different units from direct regression.
For two-hot, choose an increasing support of values , for example with equally spaced . If , assign weights and to those two bins. Their weighted average exactly reconstructs inside support. Outside, a choice is required; here clip to the endpoint. Loss is cross-entropy of these weights against logits, whose per-logit gradient is predicted probability minus target weight. This gradient is bounded componentwise, although the expected value read from bins can be large.
The example uses 17 bins with from −4 to 4. The target moves on symlog scale from −6 to 6, so can lie outside two-hot support; the readout shows clipped value. For comparison, direct and symlog regression use the same number as network output but interpret it on different scales. In classification only the central logit varies and others are zero; the displayed gradient is for that logit, not a scalar prediction. The three losses are not directly comparable as if they had the same units.
V3 normalizes return scale using a moving average of the range between 5th and 95th percentiles, with denominator at least 1: this avoids amplifying small advantages when rewards are sparse. The paper uses a shared configuration across many domains and describes agents obtaining Minecraft diamonds without human data; its experimental budget is not equivalent to a home GPU or this reduced lab.
Without a decoder and with other models
TD-MPC2 learns a control-oriented representation through latent consistency, reward and value without reconstructing future observations, and plans locally in that space. This can save capacity spent on irrelevant visual details but also lose information another task needs. Hansen and colleagues describe the model and its evaluation across continuous-control tasks.
A transformer can replace part of recurrent dynamics: IRIS combines a discrete autoencoder and autoregressive model. DIAMOND studies a diffusion world model; Genie learns a latent action space from video without action labels. These systems address different problems and budgets. A convincing visual sequence does not guarantee physically correct consequences of an action, and generating many futures can make real-time planning difficult.
Representation choice depends on information the decision needs. A visual decoder offers an understandable check but can spend capacity on backgrounds irrelevant to control. Latent consistency and value loss avoid requiring full reconstruction, though their quality must be judged by reward prediction, planning and control, not pixels. A fair comparison states available observation: physical state and image are different inputs, and the former supplies variables the latter must infer. Reduced visual CartPole and state-based HalfCheetah comparison answer different questions.
When designing an experiment, record environment interactions as well as optimization updates, evaluation, time and memory. Model-based methods can reuse each transition many times, so equal real steps do not imply equal computation. Shared hardware and compilation times also affect observed seconds. For comparison reserve evaluation seeds, report distributions across multiple training seeds, and specify episode limits, terminations and simulator versions. A short run detects program failures; it does not support a general algorithm ranking.
Lab: a reduced visual model
This lab implements a small RSSM with categorical latents, image encoder and decoder, reward and continuation heads, actor and critic. It collects real CartPole-v1 episodes using a random policy, stores them whole and trains on subsequences. Memory starts at zero in each subsequence, with no burn-in. Continuation distinguishes true termination from time limit. It then evaluates the actor in the real environment using each image’s posterior and saves both checkpoint and imagination images.
Loss sums pixel mean squared error, two-hot reward cross-entropy, binary continuation entropy, and separated KL terms with one-nat free bits. The actor is trained by straight-through pathwise gradient through frozen dynamics; the critic receives detached returns. This is an offline example on random replay: it adds no policy experience during learning and does not reproduce DreamerV3 training or results. The model can learn to predict a static image and still fail at control.
Install PyTorch, NumPy, Pillow and Gymnasium with classic-control extras. On Windows or a headless server, set SDL_VIDEODRIVER=dummy. ORYON_QUICK=1 uses 512 transitions, 30 updates and two evaluation episodes of up to 64 steps; ORYON_QUICK=0 uses 20,000 transitions, 3000 updates and five episodes of up to 200 steps. ORYON_DREAM_STEPS and ORYON_DREAM_UPDATES adjust those budgets; ORYON_DREAM_SEED and ORYON_DREAM_OUT control seed and directory. CUDA memory limit is set to at most 7 GiB per process; actual allocation and time depend on hardware.
import json, math, os, random, time
from pathlib import Path
import gymnasium as gym
import numpy as np
from PIL import Image
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1)
quick=os.getenv('ORYON_QUICK','0')=='1'
root=Path(os.getenv('ORYON_DREAM_OUT','oryon-dream'))
root.mkdir(parents=True,exist_ok=True)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type=='cuda':
total=torch.cuda.get_device_properties(0).total_memory
torch.cuda.set_per_process_memory_fraction(min(1.,7*1024**3/total))
torch.cuda.reset_peak_memory_stats()
seed=int(os.getenv('ORYON_DREAM_SEED','0'))
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed)
if device.type=='cuda':torch.cuda.manual_seed_all(seed)
rng=np.random.default_rng(seed)
real_steps=int(os.getenv('ORYON_DREAM_STEPS',str(512 if quick else 20_000)))
updates=int(os.getenv('ORYON_DREAM_UPDATES',str(30 if quick else 3000)))
batch=8 if quick else 16
length=8 if quick else 16
imag_horizon=5 if quick else 10
deter,groups,classes,hidden=64,4,8,128
gamma,lam=.99,.95
if real_steps<length or updates<1:raise ValueError('Datos o actualizaciones insuficientes')
def symlog(x):return torch.sign(x)*torch.log1p(torch.abs(x))
def symexp(x):return torch.sign(x)*torch.expm1(torch.abs(x))
bins=symexp(torch.linspace(-7,7,51,device=device))
def twohot(target):
y=target.clamp(bins[0],bins[-1]).reshape(-1)
high=torch.searchsorted(bins,y).clamp(1,len(bins)-1)
low=high-1; weight=(y-bins[low])/(bins[high]-bins[low])
out=torch.zeros((len(y),len(bins)),device=target.device)
out.scatter_(1,low[:,None],(1-weight)[:,None])
out.scatter_add_(1,high[:,None],weight[:,None])
return out
def cross_entropy(logits,target):
return -(twohot(target)*F.log_softmax(logits,dim=-1)).sum(-1).mean()
def readout(logits):return (logits.softmax(-1)*bins).sum(-1)
def mlp(inp,out):return nn.Sequential(nn.Linear(inp,hidden),nn.ELU(),nn.Linear(hidden,out))
def zero_output(module):
nn.init.zeros_(module[-1].weight);nn.init.zeros_(module[-1].bias)
def frame(env):
rgb=env.render()
return np.array(Image.fromarray(rgb).convert('L').resize((64,64),Image.Resampling.BILINEAR),dtype=np.uint8)
class World(nn.Module):
def __init__(self):
super().__init__()
self.encoder=mlp(4096,hidden)
self.gru=nn.GRUCell(groups*classes+2,deter)
self.prior=mlp(deter,groups*classes)
self.posterior=mlp(deter+hidden,groups*classes)
self.decoder=mlp(deter+groups*classes,4096)
self.reward=mlp(deter+groups*classes,len(bins))
self.continue_head=mlp(deter+groups*classes,1)
zero_output(self.reward)
def probabilities(self,logits):
p=logits.reshape(-1,groups,classes).softmax(-1)
return .99*p+.01/classes
def sample(self,prob):
return F.gumbel_softmax(prob.log(),tau=1,hard=True,dim=-1).reshape(-1,groups*classes)
def advance(self,h,z,action):
h=self.gru(torch.cat((z,action),-1),h)
prior=self.probabilities(self.prior(h))
return h,prior
def observe(self,h,z,action,obs):
h,prior=self.advance(h,z,action)
embed=self.encoder(obs.reshape(obs.shape[0],-1))
posterior=self.probabilities(self.posterior(torch.cat((h,embed),-1)))
return h,prior,posterior,self.sample(posterior)
def features(self,h,z):return torch.cat((h,z),-1)
world=World().to(device)
actor=mlp(deter+groups*classes,2).to(device)
critic=mlp(deter+groups*classes,len(bins)).to(device);zero_output(critic)
world_opt=torch.optim.Adam(world.parameters(),lr=3e-4)
actor_opt=torch.optim.Adam(actor.parameters(),lr=3e-4)
critic_opt=torch.optim.Adam(critic.parameters(),lr=3e-4)
env=gym.make('CartPole-v1',render_mode='rgb_array',max_episode_steps=64 if quick else 200)
episodes=[];count=0;start_time=time.perf_counter()
try:
while count<real_steps:
_,_=env.reset(seed=seed*100000+len(episodes));obs=[frame(env)]
acts=[];rewards=[];terms=[]
while count<real_steps:
a=int(rng.integers(2));_,r,term,trunc,_=env.step(a)
acts.append(a);rewards.append(float(r));terms.append(bool(term));obs.append(frame(env));count+=1
if term or trunc:break
if len(acts)>=length:episodes.append((np.array(obs),np.array(acts),np.array(rewards),np.array(terms)))
finally:env.close()
if not episodes:raise RuntimeError('No hay secuencias suficientemente largas')
def batch_data():
obs=[];acts=[];rews=[];terms=[]
for _ in range(batch):
ep=episodes[int(rng.integers(len(episodes)))]
start=int(rng.integers(0,len(ep[1])-length+1))
obs.append(ep[0][start:start+length+1]);acts.append(ep[1][start:start+length])
rews.append(ep[2][start:start+length]);terms.append(ep[3][start:start+length])
return (torch.tensor(np.array(obs),device=device,dtype=torch.float32)/255.,
torch.tensor(np.array(acts),device=device,dtype=torch.long),
torch.tensor(np.array(rews),device=device,dtype=torch.float32),
torch.tensor(np.array(terms),device=device,dtype=torch.float32))
def kl(q,p):return (q*(q.log()-p.log())).sum((-1,-2))
metrics=[];scale_ema=0.
for update in range(1,updates+1):
obs,acts,rewards,terms=batch_data()
h=torch.zeros(batch,deter,device=device);z=torch.zeros(batch,groups*classes,device=device)
previous=torch.zeros(batch,2,device=device)
recs=[];rews=[];conts=[];dyns=[];reps=[]
for t in range(length+1):
h,p,q,z=world.observe(h,z,previous,obs[:,t])
f=world.features(h,z)
recs.append(F.mse_loss(torch.sigmoid(world.decoder(f)),obs[:,t].reshape(batch,-1)))
dyns.append(kl(q.detach(),p).clamp_min(1.).mean())
reps.append(kl(q,p.detach()).clamp_min(1.).mean())
if t:
rews.append(cross_entropy(world.reward(f),rewards[:,t-1]))
conts.append(F.binary_cross_entropy_with_logits(world.continue_head(f).squeeze(-1),1-terms[:,t-1]))
if t<length:previous=F.one_hot(acts[:,t],2).float()
rec=torch.stack(recs).mean();rew=torch.stack(rews).mean();con=torch.stack(conts).mean()
dyn=torch.stack(dyns).mean();rep=torch.stack(reps).mean()
model_loss=rec+rew+con+.5*dyn+.1*rep
world_opt.zero_grad();model_loss.backward();nn.utils.clip_grad_norm_(world.parameters(),100.);world_opt.step()
h=h.detach();z=z.detach()
for p in world.parameters():p.requires_grad_(False)
for p in critic.parameters():p.requires_grad_(False)
imag_features=[];imag_rewards=[];imag_cont=[];values=[];entropies=[]
for t in range(imag_horizon):
f=world.features(h,z);logits=actor(f)
dist=torch.distributions.Categorical(logits=logits);entropies.append(dist.entropy())
action=F.gumbel_softmax(logits,tau=1,hard=True,dim=-1)
h,prior=world.advance(h,z,action);z=world.sample(prior)
f=world.features(h,z);imag_features.append(f)
imag_rewards.append(readout(world.reward(f)))
imag_cont.append(torch.sigmoid(world.continue_head(f)).squeeze(-1))
values.append(readout(critic(f)))
returns=[];carry=values[-1]
for t in range(imag_horizon-1,-1,-1):
carry=imag_rewards[t]+gamma*imag_cont[t]*((1-lam)*values[t]+lam*carry)
returns.append(carry)
returns=torch.stack(list(reversed(returns)))
q05,q95=torch.quantile(returns.detach().flatten(),torch.tensor([.05,.95],device=device))
scale_ema=.99*scale_ema+.01*float(q95-q05)
actor_loss=-(returns.mean()/max(1.,scale_ema)+.001*torch.stack(entropies).mean())
actor_opt.zero_grad();actor_loss.backward();nn.utils.clip_grad_norm_(actor.parameters(),100.);actor_opt.step()
for p in world.parameters():p.requires_grad_(True)
for p in critic.parameters():p.requires_grad_(True)
f=torch.stack(imag_features).detach().reshape(-1,deter+groups*classes)
value_target=returns.detach().reshape(-1)
critic_loss=cross_entropy(critic(f),value_target)
critic_opt.zero_grad();critic_loss.backward();nn.utils.clip_grad_norm_(critic.parameters(),100.);critic_opt.step()
if not all(torch.isfinite(x) for x in (model_loss,actor_loss,critic_loss)):raise FloatingPointError('Pérdida no finita')
if update==1 or update%max(1,updates//5)==0:
row={'update':update,'reconstruction':float(rec.detach()),'reward_loss':float(rew.detach()),
'continuation_loss':float(con.detach()),'dyn_kl':float(dyn.detach()),'rep_kl':float(rep.detach()),
'actor_loss':float(actor_loss.detach()),'critic_loss':float(critic_loss.detach()),'scale':scale_ema}
metrics.append(row);print(row,flush=True)
torch.save({'world':world.state_dict(),'actor':actor.state_dict(),'critic':critic.state_dict(),
'seed':seed,'quick':quick,'real_steps':real_steps,'updates':updates},root/'dreamer-small.pt')
# Evaluación real: el posterior recibe cada imagen nueva, no fotogramas soñados.
evaluation=gym.make('CartPole-v1',render_mode='rgb_array',max_episode_steps=64 if quick else 200)
evaluation_records=[]
world.eval();actor.eval()
try:
for i in range(2 if quick else 5):
torch.manual_seed(100000+1000*seed+i)
if device.type=='cuda':torch.cuda.manual_seed_all(100000+1000*seed+i)
evaluation.reset(seed=100000+1000*seed+i)
h=torch.zeros(1,deter,device=device);z=torch.zeros(1,groups*classes,device=device)
previous=torch.zeros(1,2,device=device);total_reward=0.;episode_length=0
with torch.no_grad():
while True:
pixels=torch.as_tensor(frame(evaluation),device=device,dtype=torch.float32).unsqueeze(0)/255.
h,_,_,z=world.observe(h,z,previous,pixels)
action=int(actor(world.features(h,z)).argmax(-1).item())
_,reward,term,trunc,_=evaluation.step(action)
total_reward+=float(reward);episode_length+=1
previous=F.one_hot(torch.tensor([action],device=device),2).float()
if term or trunc:break
evaluation_records.append({'return':total_reward,'length':episode_length,'terminated':bool(term),'truncated':bool(trunc)})
finally:evaluation.close()
peak=torch.cuda.max_memory_allocated()/1024**3 if device.type=='cuda' else None
report={'seed':seed,'quick':quick,'device':str(device),'real_steps':real_steps,'updates':updates,
'elapsed_seconds':time.perf_counter()-start_time,'peak_cuda_gib':peak,'episodes_collected':len(episodes),
'gymnasium':gym.__version__,'torch':torch.__version__,'numpy':np.__version__,
'gamma':gamma,'lambda':lam,'evaluation':evaluation_records,'history':metrics}
(root/'dreamer-report.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
print('Informe',report)
# Una secuencia real con acciones registradas; se abre el lazo tras 0, 4, 8 o 12 observaciones.
env=gym.make('CartPole-v1',render_mode='rgb_array',max_episode_steps=64)
try:
for rollout_seed in range(1000,1100):
observation,_=env.reset(seed=rollout_seed)
frames=[frame(env)];actions=[]
for _ in range(15):
# Control solo para obtener una secuencia larga y documentada; no mide al actor.
action=int(observation[2]+.1*observation[3]>0)
observation,_,term,trunc,_=env.step(action)
actions.append(action);frames.append(frame(env))
if term or trunc:break
if len(frames)==16:break
if len(frames)!=16:raise RuntimeError('No se pudo obtener secuencia de 16 fotogramas')
finally:env.close()
world.eval()
for opening in (0,4,8,12):
torch.manual_seed(seed+9000+opening)
if device.type=='cuda':torch.cuda.manual_seed_all(seed+9000+opening)
h=torch.zeros(1,deter,device=device);z=torch.zeros(1,groups*classes,device=device)
previous=torch.zeros(1,2,device=device)
sheet=Image.new('L',(64*16,64*2))
with torch.no_grad():
for t in range(16):
if t<=opening:
pixels=torch.as_tensor(frames[t],device=device,dtype=torch.float32).unsqueeze(0)/255.
h,_,_,z=world.observe(h,z,previous,pixels)
else:
h,prior=world.advance(h,z,previous);z=world.sample(prior)
predicted=torch.sigmoid(world.decoder(world.features(h,z))).reshape(64,64)
pred=(predicted.cpu().numpy()*255).clip(0,255).astype(np.uint8)
sheet.paste(Image.fromarray(frames[t]),(64*t,0))
sheet.paste(Image.fromarray(pred),(64*t,64))
if t<15:previous=F.one_hot(torch.tensor([actions[t]],device=device),2).float()
sheet.save(root/f'dream-opening-{opening}.png')
(root/'dream-trajectory.json').write_text(json.dumps({'environment':'CartPole-v1','seed':rollout_seed,
'actions':actions,'frames':16,'openings':[0,4,8,12],'training_steps':real_steps,
'updates':updates,'checkpoint':'dreamer-small.pt'},indent=2),encoding='utf-8')
print('Secuencia real y predicciones guardadas con semilla',rollout_seed)npm run lab and open the connection link.The opening figure comes from an additional run with ORYON_QUICK=1, 2048 transitions and 300 updates. Default quick mode is smaller still and does not aim to reach those results. In the verification run, the actor obtained returns 11 and 8 in two episodes; this checks the whole pipeline, not a competitive learned policy. The figure sequence uses an auxiliary controller and recorded actions, not that actor.
Lab: compare TD-MPC2 and SAC
Next, custom SAC and official TD-MPC2 classes are compared on HalfCheetah-v4. Both receive state observations, the same interaction budgets and the same evaluation seeds. Official TD-MPC2 uses its real model and update; the loop, sequence replay and Gymnasium connection are local adaptations, not the complete official trainer. TD-MPC2 planning evaluates actions by sampling, while SAC evaluates its actor’s deterministic mean. Architecture, hyperparameter and evaluation differences prevent attributing every difference to one choice. Version v4 is retained to match official code even though Gymnasium indicates a newer version.
Use an isolated Python environment. The tested run used PyTorch 2.11.0+cu128, Gymnasium 1.4.0, MuJoCo 4.0.1, NumPy 2.5.4, PyYAML and tensordict==0.8.3; TD-MPC2 requires CUDA. In particular, a newer tensordict failed when moving this model to CUDA in that combination. Download official code pinned to commit 332f19e4aba4bffe2dc736f45ea7f7bdc585903a and set ORYON_TDMPC_SRC to the inner tdmpc2 folder containing tdmpc2.py and config.yaml. This download uses GitHub’s published archive and requires no Git:
from pathlib import Path
from urllib.request import urlretrieve
from zipfile import ZipFile
revision = '332f19e4aba4bffe2dc736f45ea7f7bdc585903a'
archive = Path('tdmpc2-source.zip')
urlretrieve(f'https://github.com/nicklashansen/tdmpc2/archive/{revision}.zip', archive)
with ZipFile(archive) as source:
source.extractall('tdmpc2-source')
print('ORYON_TDMPC_SRC =', (Path('tdmpc2-source') / f'tdmpc2-{revision}' / 'tdmpc2').resolve())
Set ORYON_SAC_OUT, ORYON_TDMPC_OUT and ORYON_COMPARE_OUT to the same folder. ORYON_QUICK=1 uses one seed, 256 steps, 64-step warmup and two evaluation episodes up to 64 steps. The proposed experiment uses ORYON_QUICK=0, 100,000 steps, warmup 5000 and five episodes of up to 1000 steps per evaluation. SAC runs five seeds; TD-MPC2 runs one per process: repeat the cell with ORYON_TDMPC_SEED from 0 to 4. The full five-seed test was not run here and must not be confused with published experiments. Files record curves, versions, cumulative time, peak allocated CUDA memory and, for TD-MPC2, a checkpoint.
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
quick = os.getenv('ORYON_QUICK', '0') == '1'
env_id = 'HalfCheetah-v4'
target_factor = float(os.getenv('ORYON_SAC_TARGET_FACTOR', '1'))
if not math.isfinite(target_factor):
raise ValueError('El factor de entropía debe ser finito')
out = Path(os.getenv('ORYON_SAC_OUT', 'oryon-sac'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
if device.type == "cuda":
total = torch.cuda.get_device_properties(0).total_memory
torch.cuda.set_per_process_memory_fraction(min(1., 7*1024**3/total))
steps = 256 if quick else 100_000
warmup = 64 if quick else 5000
interval = 128 if quick else 10_000
episodes = 2 if quick else 5
seeds = [0] if quick else list(range(5))
batch_size = 32 if quick else 256
capacity = 10000 if quick else 1_000_000
gamma, tau = .99, .005
def network(inputs, outputs):
return nn.Sequential(nn.Linear(inputs,256),nn.ReLU(),nn.Linear(256,256),nn.ReLU(),nn.Linear(256,outputs))
class Actor(nn.Module):
def __init__(self, obs, act):
super().__init__()
self.net = network(obs, 2*act)
def sample(self, state):
mu, log_std = self.net(state).chunk(2, dim=-1)
dist = Normal(mu, log_std.clamp(-5,2).exp())
u = dist.rsample(); action = torch.tanh(u)
correction = 2*(math.log(2)-u-F.softplus(-2*u))
logp = (dist.log_prob(u)-correction).sum(-1,keepdim=True)
return action, logp
def deterministic(self, state):
mu, _ = self.net(state).chunk(2, dim=-1)
return torch.tanh(mu)
def make_env():
return gym.make(env_id, max_episode_steps=64) if quick else gym.make(env_id)
def train(seed):
if device.type == "cuda": torch.cuda.reset_peak_memory_stats()
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(); evaluation = make_env()
try:
obs, _ = env.reset(seed=seed); env.action_space.seed(seed)
low, high = env.action_space.low, env.action_space.high
if not np.isfinite(low).all() or not np.isfinite(high).all() or np.any(high <= low):
raise ValueError('Límites de acción inválidos')
od, ad = obs.size, low.size
actor = Actor(od,ad).to(device)
q1, q2, t1, t2 = [network(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)
target_entropy = -target_factor*ad
states = np.empty((capacity,od),np.float32); actions = np.empty((capacity,ad),np.float32)
rewards = np.empty((capacity,1),np.float32); nexts = np.empty_like(states); terms = np.empty_like(rewards)
history=[]; start=time.perf_counter()
def tensor(x): return torch.as_tensor(x,dtype=torch.float32,device=device)
def physical(a): return (low+(a+1)*(high-low)/2).astype(env.action_space.dtype)
def evaluate():
results=[]
for i in range(episodes):
state,_=evaluation.reset(seed=100000+1000*seed+i); total=0.
while True:
with torch.no_grad(): a=actor.deterministic(tensor(state).unsqueeze(0))[0].cpu().numpy()
state,r,term,trunc,_=evaluation.step(physical(a)); total+=float(r)
if term or trunc: break
results.append(total)
return results
for step in range(1, steps+1):
if step <= warmup:
action = rng.uniform(-1,1,ad).astype(np.float32)
else:
with torch.no_grad(): action=actor.sample(tensor(obs).unsqueeze(0))[0][0].cpu().numpy()
nxt,reward,term,trunc,_=env.step(physical(action))
ix=(step-1)%capacity
states[ix]=obs; actions[ix]=action; rewards[ix]=reward; nexts[ix]=nxt; terms[ix]=float(term)
obs=nxt
if term or trunc: obs,_=env.reset()
if step > warmup:
ix=rng.integers(0,min(step,capacity),size=batch_size)
s,a,r,ns,d=map(tensor,(states[ix],actions[ix],rewards[ix],nexts[ix],terms[ix]))
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)
qloss=F.mse_loss(q1(x),target)+F.mse_loss(q2(x),target)
qo.zero_grad(); qloss.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()+target_entropy)).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(qloss+aloss+alpha_loss): raise FloatingPointError('Pérdida no finita')
if step%interval==0:
ix=rng.integers(0,min(step,capacity),size=batch_size)
with torch.no_grad(): entropy=float(-actor.sample(tensor(states[ix]))[1].mean())
returns=evaluate()
history.append({'step':step,'seconds':time.perf_counter()-start,'alpha':float(log_alpha.exp().detach()),
'entropy':entropy,'target_entropy':target_entropy,'returns':returns,
'mean_return':float(np.mean(returns))})
print(env_id,seed,history[-1],flush=True)
return {'environment':env_id,'seed':seed,'quick':quick,'device':str(device),'steps':steps,
'gymnasium':gym.__version__,'mujoco':mujoco.__version__,'torch':torch.__version__,'numpy':np.__version__,
'target_factor':target_factor,'peak_cuda_gib':torch.cuda.max_memory_allocated()/1024**3 if device.type == 'cuda' else None,'history':history}
finally:
env.close(); evaluation.close()
for seed in seeds:
result=train(seed)
(out / f'{env_id}-seed{seed}-target{target_factor:g}.json').write_text(json.dumps(result,indent=2),encoding='utf-8')npm run lab and open the connection link.import json, os, random, sys, time
from pathlib import Path
from types import SimpleNamespace
import gymnasium as gym
import mujoco
import numpy as np
import torch
import yaml
import tensordict
# Ruta del código oficial descargado a una carpeta propia, fijado al commit indicado en la lección.
source=os.environ.get('ORYON_TDMPC_SRC')
if not source:raise ValueError('Define ORYON_TDMPC_SRC como la carpeta tdmpc2 del código oficial')
source=Path(source).resolve()
if not (source/'tdmpc2.py').is_file():raise FileNotFoundError('Falta tdmpc2.py en '+str(source))
sys.path.insert(0,str(source))
from tdmpc2 import TDMPC2
from common import MODEL_SIZE
quick=os.getenv('ORYON_QUICK','0')=='1'
root=Path(os.getenv('ORYON_TDMPC_OUT','oryon-tdmpc'));root.mkdir(parents=True,exist_ok=True)
if not torch.cuda.is_available():raise RuntimeError('La clase oficial requiere CUDA')
torch.set_num_threads(1)
total=torch.cuda.get_device_properties(0).total_memory
torch.cuda.set_per_process_memory_fraction(min(1.,7*1024**3/total))
torch.cuda.reset_peak_memory_stats()
steps,warmup,interval,eval_episodes=(256,64,128,2) if quick else (100_000,5000,10_000,5)
episode_limit=64 if quick else 1000
seed=int(os.getenv('ORYON_TDMPC_SEED','0'))
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed);torch.cuda.manual_seed_all(seed)
rng=np.random.default_rng(seed)
cfg_data=yaml.safe_load((source/'config.yaml').read_text(encoding='utf-8'))
cfg_data['lr']=float(cfg_data['lr'])
cfg_data['entropy_coef']=float(cfg_data['entropy_coef'])
cfg_data.update(MODEL_SIZE[1])
cfg_data.update(multitask=False,task_dim=0,task='mujoco-halfcheetah',tasks=['mujoco-halfcheetah'],
obs='state',obs_shape={'state':(17,)},action_dim=6,episode_length=episode_limit,
episodic=False,compile=False,mpc=True,batch_size=8 if quick else 256,
horizon=3,num_samples=32 if quick else 512,num_elites=4 if quick else 64,
num_pi_trajs=4 if quick else 24,iterations=2 if quick else 6,
discount_min=.99,discount_max=.99,bin_size=(10-(-10))/(101-1))
cfg=SimpleNamespace(**cfg_data)
agent=TDMPC2(cfg)
env=gym.make('HalfCheetah-v4',max_episode_steps=episode_limit)
ev=gym.make('HalfCheetah-v4',max_episode_steps=episode_limit)
episodes=[];current=[];obs,_=env.reset(seed=seed);env.action_space.seed(seed)
start=time.perf_counter();history=[];last_metrics={}
def sample_batch():
valid=[ep for ep in episodes+[current] if len(ep)>=cfg.horizon]
if not valid:raise RuntimeError('No hay secuencias de replay suficientes')
obs_b=[];act_b=[];rew_b=[];done_b=[]
for _ in range(cfg.batch_size):
ep=valid[int(rng.integers(len(valid)))]
i=int(rng.integers(len(ep)-cfg.horizon+1));part=ep[i:i+cfg.horizon]
obs_b.append(np.stack([part[0][0]]+[x[3] for x in part]))
act_b.append(np.stack([x[1] for x in part]))
rew_b.append(np.array([[x[2]] for x in part],np.float32))
done_b.append(np.array([[x[4]] for x in part],np.float32))
def tensor(x):return torch.as_tensor(np.stack(x,axis=1),device='cuda',dtype=torch.float32)
return tensor(obs_b),tensor(act_b),tensor(rew_b),tensor(done_b)
def evaluate():
records=[];cpu_state=torch.get_rng_state();cuda_states=torch.cuda.get_rng_state_all()
previous_mean=agent._prev_mean.clone()
try:
for ep in range(eval_episodes):
eval_seed=100000+1000*seed+ep
torch.manual_seed(eval_seed);torch.cuda.manual_seed_all(eval_seed)
s,_=ev.reset(seed=eval_seed);value=0.;length=0
while True:
a=agent.act(torch.as_tensor(s,dtype=torch.float32),t0=length==0,eval_mode=True).numpy()
s,r,term,trunc,_=ev.step(a);value+=float(r);length+=1
if term or trunc:break
records.append({'return':value,'length':length,'terminated':bool(term),'truncated':bool(trunc)})
return records
finally:
torch.set_rng_state(cpu_state);torch.cuda.set_rng_state_all(cuda_states)
agent._prev_mean.copy_(previous_mean)
try:
for step in range(1,steps+1):
if step<=warmup:a=env.action_space.sample()
else:a=agent.act(torch.as_tensor(obs,dtype=torch.float32),t0=(len(current)==0)).numpy()
nxt,r,term,trunc,_=env.step(a)
current.append((obs,np.asarray(a,np.float32),float(r),nxt,float(term)))
obs=nxt
if term or trunc:
episodes.append(current);current=[];obs,_=env.reset()
if step>warmup:
batch=sample_batch()
metrics=agent._update(*batch)
last_metrics={k:float(v.detach().cpu()) for k,v in metrics.items()}
if not all(np.isfinite(v) for v in last_metrics.values()):raise FloatingPointError('Pérdida no finita')
if step%interval==0:
records=evaluate()
row={'step':step,'seconds':time.perf_counter()-start,'episodes':records,
'updates':max(0,step-warmup),'metrics':last_metrics.copy()}
history.append(row);print('tdmpc2',seed,row,flush=True)
elapsed=time.perf_counter()-start
report={'method':'tdmpc2_official_core','source_commit':'332f19e4aba4bffe2dc736f45ea7f7bdc585903a',
'environment':'HalfCheetah-v4','quick':quick,'seed':seed,'steps':steps,'device':'cuda',
'torch':torch.__version__,'tensordict':tensordict.__version__,'numpy':np.__version__,
'gymnasium':gym.__version__,'mujoco':mujoco.__version__,'elapsed_seconds':elapsed,
'peak_cuda_gib':torch.cuda.max_memory_allocated()/1024**3,'history':history}
(root/f'tdmpc2-seed{seed}.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
agent.save(root/f'tdmpc2-seed{seed}.pt')
print('Reporte',report)
finally:
env.close();ev.close()npm run lab and open the connection link.import json, os
from pathlib import Path
import numpy as np
root=Path(os.getenv('ORYON_COMPARE_OUT','oryon-compare'))
quick=os.getenv('ORYON_QUICK','0')=='1'
seeds=[0] if quick else range(5)
rows=[]
for seed in seeds:
sac=json.loads((root/f'HalfCheetah-v4-seed{seed}-target1.json').read_text(encoding='utf-8'))
td=json.loads((root/f'tdmpc2-seed{seed}.json').read_text(encoding='utf-8'))
for key in ('environment','seed','quick','steps','gymnasium','mujoco','torch','numpy','device'):
if sac[key]!=td[key]:raise ValueError(f'Datos incompatibles: {key}: {sac[key]} != {td[key]}')
if len(sac['history'])!=len(td['history']):raise ValueError('Distinto número de evaluaciones')
for s,t in zip(sac['history'],td['history']):
if s['step']!=t['step']:raise ValueError('Pasos de evaluación distintos')
rows.append((seed,float(np.mean(sac['history'][-1]['returns'])),
float(np.mean([e['return'] for e in td['history'][-1]['episodes']]))))
print('semilla, SAC, TD-MPC2:',rows[-1])
print('segundos acumulados:',sac['history'][-1]['seconds'],td['elapsed_seconds'])
print('GiB pico asignado CUDA:',sac['peak_cuda_gib'],td['peak_cuda_gib'])
if quick:
print('Prueba de funcionamiento: una semilla, sin conclusión estadística.')
else:
# El IQM de un único entorno resume las medias por semilla, no tareas heterogéneas.
a=np.array(rows,dtype=float)
def iqm(values):
ordered=np.sort(values);n=len(ordered)
weights=np.maximum(0,np.minimum(np.arange(1,n+1),.75*n)-np.maximum(np.arange(n),.25*n))
return float(np.dot(ordered,weights)/weights.sum())
for col,name in ((1,'SAC'),(2,'TD-MPC2')):
print(name,'IQM entre semillas',iqm(a[:,col]))npm run lab and open the connection link.The IQM displayed in the full experiment is the mean of the central 50% interval of per-seed averages in this single environment; it is not an aggregate across tasks and has no confidence interval. Time includes evaluation and depends on machine load. Memory is PyTorch’s maximum allocation for each process, not all GPU-reserved or shared memory. If multiple cells run in one kernel it can include tensors still alive from earlier cells; to measure each method separately, restart the kernel before each run and keep reports in the same folder.
Exercises
Step 1 of 4. Which distributions are introduced inside the likelihood integral?
import numpy as np
def symlog(x):
pass
def symexp(x):
pass
def two_hot(values, bins):
pass