Module contents
Lesson 31 of 33Research 110 min

Generative video, video LLMs and world models

Study causal video tokenizers, latent video diffusion, video language models, action-conditioned world models and model-predictive planning, with critical evaluation of physical consistency.

After this lesson you can

  • Explain causal temporal and spatial compression by video VAEs and treatment of images and video.
  • Describe latent video diffusion with space–time attention and conditioning.
  • Design frame sampling and token compression for a video-LLM context.
  • Implement a small action-conditioned world model and plan using cross-entropy optimization.
  • Evaluate physical consistency and control usefulness of a world model.

Before you start

Imagining is not intervening

A video can look convincing even when a hand passes through an object or a ball reappears elsewhere. Robot control requires something more demanding: when an action changes, predicted consequences must support an effective intervention. A good predictor of observed scenes can ignore the causal effect of actions rarely present in its data.

Compressing time and generating

A video tokenizer transforms an image sequence into a latent grid processed by a later model. A continuous autoencoder learns an encoder and decoder; a discrete one quantizes vectors using a codebook. A causal temporal convolution in the encoder consults present and past, not future frames. This allows online representations and prevents a feature at one instant leaking future information; it does not guarantee physically correct reconstruction or generation. The first image is often treated separately because it lacks the same temporal context. The specific shape depends on padding, kernel size, and model convention.

InteractiveLatent budget
121 frames31 time positions

At 24 fps duration is assumed to be 121/24 seconds. The matrix is materialized global attention: 148.800² scores per head; this is not total model memory.

Synthetic originalGroup average

Constructed example: the point moves and the second row replaces each group by its mean position, keeping the first image separate. It illustrates motion loss; it is not VAE reconstruction.

121
4
8
16
Shape time × height × width × channels31 × 60 × 80 × 16
Latent values2.380.800
fp16 latent4.5 MiB
Positions/s at 24 fps29.514
fp16 matrix per head41.24 GiB
The calculator assumes an independent first image, padded temporal groups and fp16; the attention matrix represents materialized scores per head, not total memory. The averaging example is synthetic, not VAE output.

Compressing fourfold in time after the first image and eightfold in each spatial direction, 121 images of 480×640 yield 31×60×80 positions. With 16 channels this is 2380800 numbers, about 4.54 MiB in fp16. This example divides evenly: for other shapes declare boundary handling. Fewer positions reduce some computation, but the decoder can erase details and brief motion; more compression does not ensure better control.

A single image can be treated as a length-one sequence: the causal encoder’s first output needs no later frames. This allows part of the encoder to be shared between images and videos if architecture, padding, and scales are defined for both. It does not mean an image supplies video motion information or that any 3D VAE works without adapting dimensions. In a continuous stream, check delay introduced by temporal grouping: a token summarizing four frames is available only after all four arrive.

The memory figure above stores only one latent. Global attention over every position in this example would have 148800 queries and as many keys: 22141440000 scores per head if the whole matrix were materialized. In fp16 that is about 41.24 GiB for the matrix alone. Blockwise implementations that do not materialize it, local attention, or factorized attention can change actual consumption, but do not model selected dependencies for free. Channel count changes latent size and projection cost; it does not itself change query–key pair count in that calculation.

Causality must be checked throughout the path. A causal convolution followed by normalization mixing future-time statistics can leak information into training. It also matters whether the decoder reconstructs each image using later latents. To evaluate causal prediction, encode only what is observed by decision time and check that changing future input does not alter past representation. An autoencoder trained on full clips can be useful for offline generation, but that does not establish an online control interface.

Video diffusion learns to denoise a sequence, often in latent space. Another family learns a velocity field through flow matching; it shares the idea of transforming noise into data but uses a different training formulation. Generators can be conditioned on text, an initial image, or actions. Layers combine spatial and temporal information; generating each image independently does not impose identity, motion, or occlusion consistency. Video Diffusion Models studied joint image–video generation and temporal extension. Action conditioning permits intervention, but reliability outside seen actions must be measured in the environment.

In a common diffusion formulation, noise is added to clean latent z0z_0 to obtain zk=αˉkz0+1−αˉkϵz_k=\sqrt{\bar\alpha_k}z_0+\sqrt{1-\bar\alpha_k}\epsilon, with Gaussian ϵ\epsilon. A network receives zkz_k, noise index, and conditioning, and learns to estimate ϵ\epsilon by minimizing squared error. Generation starts from noise and applies multiple approximate reverse steps. This objective alone imposes neither object conservation nor contact constraints: these properties must be measured or incorporated into model and data.

Conditioning must match what is available at decision time. If predicting after an initial image and action sequence, giving future frames during evaluation would leak the answer. Align the interval between actions and frames too: a command held for four images is not four independent commands. This problem appears in training, inference, and comparing prediction with a simulator.

Asking about long videos

A video-LLM converts selected frames into visual features, adds temporal position, and combines them with text. If context admits 2048 visual tokens and each image contributes 256, eight images fit before reserving instructions and response. A half-second event in ten minutes can fall between eight uniform samples: to locate it, use hierarchical sampling, a proposal detector, or overlapping windows and then refine times. Temporal compression saves context but can merge decisive changes. Evaluate temporal localization, order questions, brief events, and absence of evidence; a fluent linguistic answer does not prove the model saw the event.

Suppose eight images are distributed uniformly over ten minutes. Consecutive sample spacing is about 75 to 86 seconds depending on whether endpoints are included, much greater than half a second. Without an assumption about event position there is no capture guarantee. A hierarchical system can first inspect blocks at low resolution and then increase density for candidates; success depends on the first stage not discarding the correct block. Measure proposal detection and final localization separately, along with tokens and time for both passes.

Timestamps are not ornamental. If neighboring selected samples have different intervals, a representation retaining only order index can confuse speed and duration. Record actual times and evaluate whether the system can answer “before or after,” estimate duration, and recognize an event is outside the samples. A good answer can be abstention when observed video contains no evidence.

From actions to futures

An action-conditioned world model approximates p(ot+1∣o≤t,a≤t)p(o_{t+1}\mid o_{\leq t},a_{\leq t}) or predicts latent state zt+1=fθ(zt,at)z_{t+1}=f_\theta(z_t,a_t). Under partial observation it needs memory or belief: one image can hide velocity, occlusions, and contact properties. In open loop its own prediction feeds the next step and error accumulates; near contact a small position error can change whether a push succeeds. A planner also searches extreme sequences exploiting model errors, so low mean one-step error does not certify safe plans.

A simple bound clarifies when horizon matters. Assume fully observed state, uniform local error at most ϵ\epsilon, and true dynamics LL-Lipschitz in state for the same action. Starting both models from the same state, hh-step error satisfies eh≤ϵ∑i=0h−1Lie_h\leq\epsilon\sum_{i=0}^{h-1}L^i. For L=1L=1 it grows at most linearly, hϵh\epsilon; for L>1L>1 the bound grows geometrically. This is a guarantee only under those assumptions, not a universal prediction: discontinuous contact can violate regularity and a uniform bound may be unknown. Replanning limits steps without observation, but partial or faulty observation need not restore true state.

Latent actions can be inferred from image pairs without control labels: an inverse model assigns a code helping predict the next frame. Genie combines video tokenization, autoregressive dynamics, and latent actions learned from unlabeled video. Codes identify changes useful for prediction, not necessarily robot commands: camera motion, another agent, or hidden variables can explain change. Converting them into executable actions requires additional alignment and evaluation.

The same visual change can have several causes. A moving box may have been pushed, pulled, or moved by someone off camera; two different physical actions can also produce nearly identical frames from one view. Therefore an inverse code is not uniquely identified merely by requiring good next-frame prediction. The representation can be useful for generating controllable changes within observed data, but one must measure whether a learned interface translates codes to valid actions for each body and camera.

Conversely, one action can produce different futures because of contact, hidden state, or noise. A deterministic predictor minimizing squared error tends to average compatible futures; that mean may correspond to none of the physically possible outcomes. A probabilistic predictor can represent several hypotheses if calibration and coverage are evaluated. To plan under uncertainty, compare mean cost, worst case, and fraction of trajectories violating constraints; choosing only the most favorable future can exploit uncertainty rather than reduce it.

Plan and observe again

Latent-space planning seeks an action sequence bringing a prediction close to a target-image representation. The cross-entropy method (CEM) samples sequences from a distribution, simulates futures, retains the lowest-cost ones, and fits elite mean and deviation. This repeats and the first action is executed; the environment is then observed and planning repeated. Optimization is approximate: it depends on budget, horizon, noise, cost function, and model fidelity.

For a diagonal Gaussian, a common update computes elite-action mean and deviation per instant and dimension. With too few elites, spread can collapse before exploring an alternative; a minimum deviation or smoothed update retains exploration, though it can delay convergence. Clipping actions to physical limits changes the effective distribution: many candidates can end exactly at the boundary. Compare imagined cost of chosen candidates with observed outcome, and record how many actions saturate.

A world-model experiment must separate predictor quality from planner quality. First hold out complete trajectories and apply actually recorded actions to the model from the same observation; this measures open-loop drift without CEM selecting actions. Then execute chosen plans in the simulator with re-observation and record prediction errors at planner-visited states. Those states can differ from random training data: a planner may seek precisely the regions where the model is least constrained.

Embedding distance is also an objective choice. Two images can be close because they share table and background even if the object is far from goal; if the encoder does not retain orientation or grasp, optimizing that distance may reward an unsuitable state. A useful test changes one relevant property and checks distance response, versus lighting changes that ideally should not dominate it. However, invariance should not be confused with removing all lighting: in some scenes a shadow helps estimate depth or contact.

InteractivePlanning by dreaming
  • candidate trajectories
  • elites
  • goal

The dashed line shows the trajectory produced by updated mean actions. The next iteration resamples with that mean and new spread. Actions are bounded to ±0.25; minimum deviation 0.025.

Iteration
Stage
Sequences45
Elites6
Mean elite distance0.271
New mean spread0.145
A deterministic synthetic example simulates four actions per trajectory. Explore three iterations of sampling, selection, and update in action space; these are not robot predictions.

V-JEPA 2 pretrains prediction in video embeddings; its AC variant incorporates robot trajectories for action-conditioned prediction and visual-goal planning. The paper presents Franka arm results under its protocol, not a guarantee for any robot or scene. Latent space can ignore irrelevant texture and save decoding, but also discard an important small detail such as a finger’s position. A pixel model allows inspection of predicted images, though visual fidelity and control usefulness are not equivalent. DreamerV3 is another example of learning behavior from imagined futures, with different architecture and evaluation.

InteractivePrediction drifts

Environment

Environment, horizon 1

Prediction

Prediction, horizon 1

The same image error can affect contact or success differently. Also compare executed plans and do not select only the most favorable frame.

Horizon
Mean RGB MSE [0,1]0.000823
Held-out windows600
An example of a model trained on 200 MuJoCo episodes: the same actions are applied to environment and predictor. Mean errors aggregate 600 windows from 50 held-out episodes; they are not success rates.

In an in-house run with 64×64 RGB images and random actions, an autoencoder and action-conditioned predictor trained on 200 episodes and were evaluated on 50 different ones. With 600 held-out windows per horizon, mean normalized RGB MSE was 0.000823 at one step, 0.000845 at four, and 0.000874 at eight. Only one seed was trained and error averages all pixels: background dominates the count and can hide errors on a small object. The figure shows the first held-out window without selecting a favorable reconstruction: the pusher appears blurred in prediction. Do not infer control success from these numbers.

To distinguish plausibility from usefulness, hold out episodes, objects, and conditions; compare one- and multi-step predictions with actual observations, task success, collisions, and cost against a reference policy or simulator. Apply the same actions to model and environment, then evaluate executed plans with re-observation. Report seeds, intervals, and failures, including contact, occlusion, and distribution shift. A realistic-looking clip alone is not evidence of correct physics.

A rollout comparison should start from the same state and apply exactly the same action sequence to simulator and predictor. At each horizon measure position and orientation distance if reference state is available, as well as image error. Image error can rise from a small camera displacement without affecting the right action; it can also be low while a small object crosses a forbidden zone. Report state metrics, contact events, and plan success rather than choosing one as a substitute for the rest.

Data collection matters too. Random actions can explore states an expert policy never visits, but if they rarely cause contact the predictor sees few effective pushes. Expert demonstrations cover useful trajectories but may omit recovery after failure. Count transitions with and without contact, hold out complete episodes, and compare both regimes without presenting either as universally superior. Collection and evaluation seeds serve different roles and should be recorded separately.

Replanning is evaluated in closed loop: the chosen action is executed in the reference environment and the next observation replaces imagined state before planning again. If one method receives exact physical state and another only images, they solve different information problems. Comparing them can show the value of a privileged sensor but does not isolate planner quality. A fair control-method comparison fixes observations, goals, episodes, limits, and compute budget, or states why equalization was impossible.

Lab: MLP and CEM in two dimensions

State contains pusher and object positions. A known rule moves the object on contact; an MLP learns the change from transitions. Test data are held out before training. Goal distance uses object position and each plan executes one action before observing again. The simulation is deliberately simple: it is not MuJoCo and does not demonstrate sim2real. Initialization, dataset, and twelve episodes are small, so rates do not support a general conclusion about horizons.

[ ]Learning and planningBrowser
import numpy as np

rng=np.random.default_rng(31)
# Estado: posición del empujador (2), posición del objeto (2).
def step(s,a):
    p=s[...,:2]; q=s[...,2:]; a=np.clip(a,-.12,.12)
    p2=np.clip(p+a,-1,1)
    contact=(np.linalg.norm(p-q,axis=-1,keepdims=True)<.22)
    q2=np.clip(q+contact*a*.8,-1,1)
    return np.concatenate([p2,q2],axis=-1)

# Cada muestra es una transición independiente; reservar distribución igual para prueba.
n=10000
s=rng.uniform(-.8,.8,(n,4)); close=rng.random(n)<.45
s[close,:2]=s[close,2:]+rng.normal(0,.10,(close.sum(),2))
a=rng.uniform(-.12,.12,(n,2)); y=step(s,a)-s
x=np.concatenate([s,a],axis=1)
train=np.arange(8000); test=np.arange(8000,n)
W1=rng.normal(0,.2,(6,48)); b1=np.zeros(48)
W2=rng.normal(0,.04,(48,4)); b2=np.zeros(4)
for iteration in range(2500):
    ix=rng.choice(train,256,replace=False); xx=x[ix]; target=y[ix]
    h=np.tanh(xx@W1+b1); pred=h@W2+b2; d=2*(pred-target)/len(ix)
    dW2=h.T@d; db2=d.sum(axis=0); dh=([email protected])*(1-h*h)
    dW1=xx.T@dh; db1=dh.sum(axis=0)
    # Adam se omite para dejar visible la actualización completa.
    W1-=.08*dW1; b1-=.08*db1; W2-=.08*dW2; b2-=.08*db2
def model(s,a):
    h=np.tanh(np.concatenate([s,a],axis=-1)@W1+b1)
    return s+h@W2+b2
print('RMSE un paso por componente:',round(float(np.sqrt(np.mean((model(s[test],a[test])-step(s[test],a[test]))**2))),5))

def cem_plan(model,z0,zgoal,horizon,n_samples,n_elites,iters,rng):
    mean=np.zeros((horizon,2)); std=np.full_like(mean,.12)
    for _ in range(iters):
        acts=np.clip(rng.normal(mean,std,(n_samples,horizon,2)),-.12,.12)
        state=np.repeat(np.asarray(z0)[None,:],n_samples,axis=0)
        for t in range(horizon): state=model(state,acts[:,t])
        costs=((state[:,2:]-zgoal)**2).sum(axis=1)
        elite=acts[np.argsort(costs)[:n_elites]]
        mean=elite.mean(axis=0);std=np.maximum(elite.std(axis=0),.01)
    return mean

def evaluate(horizon):
    successes=0; distances=[]
    for i in range(12):
        local=np.random.default_rng(1000+i)
        q=local.uniform(-.35,.35,2); goal=np.clip(q+local.uniform(-.3,.3,2),-.8,.8)
        state=np.r_[q+local.normal(0,.08,2),q]
        for _ in range(8):
            plan=cem_plan(model,state,goal,horizon,96,12,3,local)
            state=step(state,plan[0]) # ejecutar una acción y volver a observar
        d=np.linalg.norm(state[2:]-goal);distances.append(d);successes+=d<.1
    return successes,round(float(np.mean(distances)),3)
for h in (1,4,8): print('horizonte, éxitos/12, distancia media:',h,*evaluate(h))

Held-out transition RMSE measures a different component from control success. Try several training sets and seeds, include states near contact, and compare executed plans against imagined cost. Sequences are clipped to action bounds, and minimum deviation prevents exploration collapsing completely. The horizon comparison here also changes the total number of imagined actions; it is descriptive and does not equalize compute budget.

Local lab: video and control

This experiment runs the lesson 13 MuJoCo scene, collects 250 episodes with random actions, and holds out the last 50 complete episodes. An image autoencoder and 32-dimensional dynamics each receive 3000 updates with batches of 64. The planner observes the current and goal images, searches 256 horizon-8 sequences for four iterations, retains 32 elites, and executes one action before observing again. The diffusion baseline comes from 100 expert demonstrations in lesson 13 and receives privileged physical state: the comparison describes different systems and does not isolate planner effect. Both use the same 50 initial states. In the CPU run with one training seed, CEM achieved 0/50 successes and the diffusion policy 0/50; each episode ended after 100 actions. For each proportion, the 95% Wilson interval is approximately [0 %, 7.1 %]. Both left mean final distance near 0.1502 m. This does not demonstrate equivalence: observations, data, and computation differ, and one training seed cannot estimate variability. CEM’s goal observation is constructed by temporarily placing the object at the goal for rendering, without a future frame from the episode.

First run the lesson 13 diffusion lab: by default oryon-l13-residual/diffusion_state.pt is loaded. If elsewhere, specify the path with ORYON_L13_CHECKPOINT. Install numpy, torch, gymnasium and mujoco locally, plus OpenGL drivers needed for rendering. The measured run used CPU and one thread for training and planning, with OpenGL rendering and no CUDA training. To reproduce that choice set ORYON_WORLD_DEVICE=cpu and ORYON_THREADS=1; ORYON_L31_OUT and ORYON_L31_CACHE choose result and data folders. Collection saves each episode; ORYON_WORLD_RESUME=1 resumes training from the last 500-update checkpoint and ORYON_CEM_RESUME=1 resumes evaluation after each episode batch. Keep parameters and versions unchanged when resuming. The full process needs time and storage; budget variables allow experimentation, but changing them no longer reproduces the published measurement.

[ ]Video, dynamics and control in MuJoCoLocal GPU
"""Experimento de empuje MuJoCo para m24-l13. Ejecución autónoma; no usa Push-T."""
import os, json, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
import gymnasium as gym
from gymnasium import spaces
import mujoco

torch.set_num_threads(int(os.environ.get('ORYON_THREADS','1')))
torch.manual_seed(13)
rng = np.random.default_rng(13)
device = os.environ.get('ORYON_DEVICE','cuda' if torch.cuda.is_available() else 'cpu')
XML = '''<mujoco model="push"><option timestep="0.002"/><worldbody>
<light pos="0 0 2"/><camera name="top" pos="0 0 .5" xyaxes="1 0 0 0 1 0"/>
<geom name="table" type="plane" size="1 1 .1" friction="1 .005 .0001"/>
<body name="pusher" pos="-.15 0 .025"><joint name="px" type="slide" axis="1 0 0" damping="5"/><joint name="py" type="slide" axis="0 1 0" damping="5"/><geom type="sphere" size=".015" mass="1" rgba=".2 .4 .8 1"/><site name="tip" size=".005"/></body>
<body name="block" pos="0 0 .025"><freejoint name="blockjoint"/><geom name="box" type="box" size=".025 .025 .025" mass=".1" rgba=".8 .3 .2 1"/></body>
</worldbody><actuator><velocity joint="px" kv="100" ctrlrange="-.2 .2"/><velocity joint="py" kv="100" ctrlrange="-.2 .2"/></actuator></mujoco>'''

class Push(gym.Env):
    metadata = {'render_modes':['rgb_array'], 'render_fps':10}
    def __init__(self, mode='nominal', residual=None, capture=False, xml=XML):
        self.model = mujoco.MjModel.from_xml_string(xml); self.data = mujoco.MjData(self.model)
        self.tip = mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_SITE,'tip')
        self.block = mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_BODY,'block')
        self.box = mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_GEOM,'box')
        self.table = mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_GEOM,'table')
        self.mode=mode; self.residual=residual; self.capture=capture; self.renderer=None
        self.action_space=spaces.Box(-1.,1.,(2,),dtype=np.float32)
        self.observation_space=spaces.Box(-np.inf,np.inf,(6,),dtype=np.float32)
        self.goal=np.array([.15,0.]); self.steps=0
    def state(self):
        return np.r_[self.data.qpos[:2]+[-.15,0],self.data.xpos[self.block,:2],self.goal].astype(np.float32)
    def image(self):
        if self.renderer is None:self.renderer=mujoco.Renderer(self.model,64,64)
        self.renderer.update_scene(self.data,camera='top');return self.renderer.render().copy()
    def reset(self,*,seed=None,options=None):
        super().reset(seed=seed);mujoco.mj_resetData(self.model,self.data);self.steps=0
        if self.mode=='random':
            mass=self.np_random.uniform(.08,.22);friction=self.np_random.uniform(.4,1.4)
        elif self.mode=='target':mass=.20;friction=.45
        else:mass=.1;friction=1.
        self.model.body_mass[self.block]=mass;self.model.geom_friction[self.box,0]=friction
        self.model.geom_friction[self.table,0]=friction
        mujoco.mj_setConst(self.model,self.data)
        self.data.qpos[3]=self.np_random.uniform(-.015,.015)
        mujoco.mj_forward(self.model,self.data)
        return self.state(),{}
    def step(self,action):
        if self.residual is not None:action=np.clip(self.residual(self.state())+0.25*np.asarray(action),-1,1)
        action=np.clip(np.asarray(action,dtype=np.float32),-1,1)
        self.data.ctrl[:]=.2*action
        for _ in range(50):mujoco.mj_step(self.model,self.data)
        mujoco.mj_forward(self.model,self.data);self.steps+=1
        distance=float(np.linalg.norm(self.data.xpos[self.block,:2]-self.goal))
        done=distance<.035;truncated=self.steps>=100 and not done
        return self.state(),-distance+float(done),done,truncated,{'success':done,'distance':distance}
    def close(self):
        if self.renderer is not None:self.renderer.close();self.renderer=None

def expert(s):
    tip,block,goal=s[:2],s[2:4],s[4:]; direction=goal-block
    direction=direction/max(np.linalg.norm(direction),1e-8);behind=block-.045*direction
    target=behind if np.linalg.norm(tip-behind)>.025 and tip[0]<block[0]-.02 else goal
    return np.clip(6*(target-tip),-1,1).astype(np.float32)

def collect(num=100):
    episodes=[];env=Push()
    for seed in range(num):
        s,_=env.reset(seed=seed);episode=[]
        for t in range(100):
            a=expert(s);ns,r,term,trunc,info=env.step(a)
            episode.append((s.copy(),a.copy()));s=ns
            if term or trunc:break
        episodes.append(episode)
    env.close();return episodes


class Denoiser(nn.Module):
    def __init__(self):
        super().__init__();self.net=nn.Sequential(nn.Linear(23,128),nn.SiLU(),nn.Linear(128,128),nn.SiLU(),nn.Linear(128,16))
    def forward(self,x,s,t):return self.net(torch.cat([x,s,t[:,None]],-1))


def diffusion(model,abar,s):
    # Fijar el ruido permite observar el mismo estado como política determinista al entrenar PPO.
    with torch.no_grad():
        infer_device=next(model.parameters()).device
        state=torch.tensor(s[None],device=infer_device)
        fixed_noise=np.random.default_rng(73).standard_normal((1,16)).astype(np.float32)
        x=torch.tensor(fixed_noise,device=infer_device)
        indices=[19,15,11,7,3,0]
        for j,k in enumerate(indices):
            noise=model(x,state,torch.tensor([k/19],device=infer_device));a=abar[k]
            clean=(x-(1-a).sqrt()*noise)/a.sqrt();prev=abar[indices[j+1]] if j+1<len(indices) else torch.tensor(1.,device=infer_device)
            x=prev.sqrt()*clean+(1-prev).sqrt()*noise
        return np.clip(x[0,:2].cpu().numpy(),-1,1)


"""Experimento MuJoCo de l31: vídeo, predictor y CEM. Requiere el Push de l13."""
import os,sys,json,hashlib
from pathlib import Path
import numpy as np
import torch
from torch import nn
import mujoco

torch.set_num_threads(int(os.environ.get('ORYON_THREADS','1')));torch.manual_seed(31);rng=np.random.default_rng(31)
device=os.environ.get('ORYON_WORLD_DEVICE','cuda' if torch.cuda.is_available() else 'cpu')
out=Path(os.environ.get('ORYON_L31_OUT','oryon-l31-world'));out.mkdir(parents=True,exist_ok=True)

def collect(count):
    # Cada episodio y su estado RNG se guardan al terminar; no se altera el
    # número de episodios ni se reinicia la secuencia aleatoria al reanudar.
    cache=Path(os.environ.get('ORYON_L31_CACHE','oryon-l31-cache'));cache.mkdir(parents=True,exist_ok=True)
    manifest=cache/'manifest.json';contract={'count':count,'xml_sha256':hashlib.sha256(XML.encode()).hexdigest(),
        'seed_start':0,'max_steps':100,'resolution':64,'fps':10,'action_rule':'clip(.75*a+normal(0,.35),-1,1)',
        'numpy':np.__version__,'mujoco':mujoco.__version__}
    records=[];episodes=[]
    if manifest.exists():
        saved=json.loads(manifest.read_text(encoding='utf8'))
        if saved['contract']!=contract:raise ValueError('Contrato de recogida incompatible')
        records=saved['records'];rng.bit_generator.state=saved['rng_state']
        if len(records)>count:raise ValueError('Caché con demasiados episodios')
        for i,row in enumerate(records):
            file=cache/row['file']
            if row['seed']!=i or hashlib.sha256(file.read_bytes()).hexdigest()!=row['sha256']:raise ValueError('Episodio de caché alterado')
            with np.load(file,allow_pickle=False) as data:frames=data['frames'];actions=data['actions']
            if frames.shape!=(len(actions)+1,64,64,3) or actions.shape[1:]!=(2,):raise ValueError('Formas de caché incompatibles')
            episodes.append((frames,actions))
        print('recogida reanudada desde',len(records),'episodios',flush=True)
    env=Push()
    try:
        for seed in range(len(records),count):
            env.reset(seed=seed);frames=[env.image()];actions=[];a=np.zeros(2)
            for _ in range(100):
                a=np.clip(.75*a+rng.normal(0,.35,2),-1,1)
                _,_,done,cut,_=env.step(a);actions.append(a.astype('float32'));frames.append(env.image())
                if done or cut:break
            frames=np.stack(frames);actions=np.stack(actions);episodes.append((frames,actions))
            file=cache/f'episode-{seed:04d}.npz';temp=file.with_suffix('.npz.tmp')
            with temp.open('wb') as stream:np.savez_compressed(stream,frames=frames,actions=actions)
            temp.replace(file);records.append({'seed':seed,'steps':len(actions),'file':file.name,'sha256':hashlib.sha256(file.read_bytes()).hexdigest()})
            temp_manifest=manifest.with_suffix('.json.tmp');temp_manifest.write_text(json.dumps({'contract':contract,'records':records,'rng_state':rng.bit_generator.state},indent=2),encoding='utf8');temp_manifest.replace(manifest)
            if (seed+1)%25==0:print('episodios',seed+1,flush=True)
    finally:env.close()
    return episodes

class Autoencoder(nn.Module):
    def __init__(self):
        super().__init__()
        self.enc=nn.Sequential(nn.Conv2d(3,16,4,2,1),nn.ReLU(),nn.Conv2d(16,32,4,2,1),nn.ReLU(),nn.Conv2d(32,64,4,2,1),nn.ReLU(),nn.Flatten(),nn.Linear(64*8*8,32))
        self.lin=nn.Linear(32,64*8*8)
        self.dec=nn.Sequential(nn.ConvTranspose2d(64,32,4,2,1),nn.ReLU(),nn.ConvTranspose2d(32,16,4,2,1),nn.ReLU(),nn.ConvTranspose2d(16,3,4,2,1),nn.Sigmoid())
    def encode(self,x):return self.enc(x)
    def decode(self,z):return self.dec(self.lin(z).reshape(-1,64,8,8))
    def forward(self,x):return self.decode(self.encode(x))
class Dynamics(nn.Module):
    def __init__(self):
        super().__init__();self.net=nn.Sequential(nn.Linear(34,128),nn.ReLU(),nn.Linear(128,128),nn.ReLU(),nn.Linear(128,32))
    def forward(self,z,a):return z+self.net(torch.cat([z,a],dim=-1))
def tensor(images):return torch.from_numpy(np.asarray(images)).to(device).permute(0,3,1,2).float()/255

def train(episodes):
    frames=np.concatenate([f[:-1] for f,a in episodes]);nextframes=np.concatenate([f[1:] for f,a in episodes]);actions=np.concatenate([a for f,a in episodes])
    ae_updates=int(os.environ.get('ORYON_AE_UPDATES','3000'));dyn_updates=int(os.environ.get('ORYON_DYN_UPDATES','3000'))
    save_every=int(os.environ.get('ORYON_WORLD_SAVE_EVERY','500'))
    if min(ae_updates,dyn_updates,save_every)<1:raise ValueError('Presupuestos deben ser positivos')
    manifest=Path(os.environ.get('ORYON_L31_CACHE','oryon-l31-cache'))/'manifest.json'
    contract={'data_manifest_sha256':hashlib.sha256(manifest.read_bytes()).hexdigest(),'train_episodes':len(episodes),
              'ae_updates':ae_updates,'dyn_updates':dyn_updates,'batch':64,'device':str(device),'torch':torch.__version__}
    resume=out/'training-resume.pt';state=None
    if os.environ.get('ORYON_WORLD_RESUME')=='1' and resume.exists():
        state=torch.load(resume,map_location='cpu',weights_only=False)
        if state['contract']!=contract:raise ValueError('Contrato de entrenamiento incompatible')
        print('Reanudando',state['stage'],state['step'],flush=True)
    def save(stage,step,ae,optimizer,dynamics=None):
        value={'contract':contract,'stage':stage,'step':step,'ae':ae.state_dict(),'optimizer':optimizer.state_dict(),
               'dynamics':None if dynamics is None else dynamics.state_dict(),'numpy_rng':rng.bit_generator.state,
               'torch_rng':torch.get_rng_state(),'cuda_rng':torch.cuda.get_rng_state(device) if str(device).startswith('cuda') else None}
        temporary=resume.with_suffix('.pt.tmp');torch.save(value,temporary);temporary.replace(resume)
    def restore_random(value):
        rng.bit_generator.state=value['numpy_rng'];torch.set_rng_state(value['torch_rng'].cpu())
        if str(device).startswith('cuda'):torch.cuda.set_rng_state(value['cuda_rng'].cpu(),device)
    ae=Autoencoder().to(device);opt=torch.optim.Adam(ae.parameters(),lr=3e-4);start_ae=0
    if state is not None:
        ae.load_state_dict(state['ae'])
        if state['stage']=='ae':opt.load_state_dict(state['optimizer']);start_ae=state['step'];restore_random(state)
        elif state['stage'] in ('ae_complete','dynamics'):start_ae=ae_updates
        else:raise ValueError('Etapa de checkpoint desconocida')
    for update in range(start_ae,ae_updates):
        idx=rng.integers(len(frames),size=64);x=tensor(frames[idx]);loss=(ae(x)-x).square().mean()
        opt.zero_grad();loss.backward();opt.step()
        if (update+1)%save_every==0 or update+1==ae_updates:
            print('AE',update+1,float(loss.detach()),flush=True);save('ae',update+1,ae,opt)
    if state is None or state['stage']=='ae':save('ae_complete',0,ae,opt)
    ae.eval();[p.requires_grad_(False) for p in ae.parameters()]
    if state is not None and state['stage']=='ae_complete':restore_random(state)
    dynamics=Dynamics().to(device);opt=torch.optim.Adam(dynamics.parameters(),lr=3e-4);start_dyn=0
    if state is not None and state['stage']=='dynamics':
        dynamics.load_state_dict(state['dynamics']);opt.load_state_dict(state['optimizer']);start_dyn=state['step'];restore_random(state)
    for update in range(start_dyn,dyn_updates):
        idx=rng.integers(len(frames),size=64)
        with torch.no_grad():z=ae.encode(tensor(frames[idx]));zn=ae.encode(tensor(nextframes[idx]))
        a=torch.tensor(actions[idx],device=device);loss=(dynamics(z,a)-zn).square().mean()
        opt.zero_grad();loss.backward();opt.step()
        if (update+1)%save_every==0 or update+1==dyn_updates:
            print('dinámica',update+1,float(loss.detach()),flush=True);save('dynamics',update+1,ae,opt,dynamics)
    dynamics.eval();temporary=out/'world.pt.tmp';torch.save({'ae':ae.state_dict(),'dynamics':dynamics.state_dict(),'contract':contract},temporary);temporary.replace(out/'world.pt');return ae,dynamics

def target_image(env):
    # Fotografía de meta en la misma escena. No utiliza la imagen futura real.
    saved=env.data.qpos.copy();env.data.qpos[2:4]=env.goal;mujoco.mj_forward(env.model,env.data)
    result=env.image();env.data.qpos[:]=saved;mujoco.mj_forward(env.model,env.data);return result

@torch.no_grad()
def plan(ae,model,image,goal,horizon=8,samples=256,elites=32,iters=4):
    z0=ae.encode(tensor(image[None]));zg=ae.encode(tensor(goal[None]));mean=torch.zeros(horizon,2,device=device);std=torch.ones_like(mean)
    for _ in range(iters):
        actions=(mean+std*torch.randn(samples,horizon,2,device=device)).clamp(-1,1);z=z0.expand(samples,-1)
        for t in range(horizon):z=model(z,actions[:,t])
        costs=(z-zg).square().mean(-1);ids=costs.argsort()[:elites];best=actions[ids];mean=best.mean(0);std=best.std(0,unbiased=False).clamp_min(.05)
    return mean[0].cpu().numpy()

@torch.no_grad()
def plan_batch(ae,model,images,goals,generators,horizon=8,samples=256,elites=32,iters=4):
    batch=len(images)
    if len(generators)!=batch:raise ValueError('Un generador por episodio')
    z0=ae.encode(tensor(np.stack(images)));zg=ae.encode(tensor(np.stack(goals)))
    mean=torch.zeros(batch,horizon,2,device=device);std=torch.ones_like(mean)
    for _ in range(iters):
        noise=torch.stack([torch.randn(samples,horizon,2,device=device,generator=g) for g in generators])
        actions=(mean[:,None]+std[:,None]*noise).clamp(-1,1)
        z=z0[:,None,:].expand(-1,samples,-1).reshape(batch*samples,-1)
        for t in range(horizon):z=model(z,actions[:,:,t,:].reshape(batch*samples,2))
        costs=(z.reshape(batch,samples,-1)-zg[:,None,:]).square().mean(-1)
        ids=costs.argsort(dim=1)[:,:elites,None,None].expand(-1,-1,horizon,2)
        best=actions.gather(1,ids);mean=best.mean(1);std=best.std(1,unbiased=False).clamp_min(.05)
    return mean[:,0].cpu().numpy()

def evaluate(ae,model,n=50):
    # Se agrupan entornos para ejecutar la misma búsqueda CEM por lotes. Cada
    # episodio tiene su propio RNG; la agrupación no comparte candidatos.
    records=[];batch_size=int(os.environ.get('ORYON_CEM_BATCH','8'))
    if batch_size<1:raise ValueError('ORYON_CEM_BATCH debe ser positivo')
    partial=out/'cem-partial.json';checkpoint=out/'world.pt'
    contract={'checkpoint_sha256':hashlib.sha256(checkpoint.read_bytes()).hexdigest(),'episodes':n,'seed_start':10000,
              'batch':batch_size,'horizon':8,'samples':256,'elites':32,'iterations':4,'device':str(device),'torch':torch.__version__}
    if os.environ.get('ORYON_CEM_RESUME')=='1' and partial.exists():
        saved=json.loads(partial.read_text(encoding='utf8'))
        if saved['contract']!=contract:raise ValueError('Contrato de CEM parcial incompatible')
        records=saved['records']
        if [r['seed'] for r in records]!=list(range(10000,10000+len(records))) or len(records)>n:raise ValueError('Semillas parciales incompatibles')
        if len(records)!=n and len(records)%batch_size:raise ValueError('Lote parcial incompleto')
        print('CEM reanudado desde',len(records),'episodios',flush=True)
    for first in range(10000+len(records),10000+n,batch_size):
        seeds=list(range(first,min(first+batch_size,10000+n)));envs=[Push() for _ in seeds]
        generators=[torch.Generator(device=device).manual_seed(seed+100000) for seed in seeds]
        try:
            goals=[]
            for env,seed in zip(envs,seeds):env.reset(seed=seed);goals.append(target_image(env))
            active=list(range(len(envs)));finished={}
            for step in range(100):
                if not active:break
                actions=plan_batch(ae,model,[envs[i].image() for i in active],[goals[i] for i in active],[generators[i] for i in active])
                next_active=[]
                for i,action in zip(active,actions):
                    _,_,done,cut,info=envs[i].step(action)
                    if done or cut:finished[i]={'seed':seeds[i],'success':bool(done),'steps':step+1,'distance':info['distance']}
                    else:next_active.append(i)
                active=next_active
            if active:raise RuntimeError('Hay episodios sin terminar tras el límite')
            for i in range(len(envs)):
                records.append(finished[i]);print('CEM',seeds[i],finished[i]['success'],finished[i]['distance'],flush=True)
            temporary=partial.with_suffix('.json.tmp');temporary.write_text(json.dumps({'contract':contract,'records':records},indent=2),encoding='utf8');temporary.replace(partial)
        finally:
            for env in envs:env.close()
    return records

def baseline(n=50):
    ckpt=Path(os.environ.get('ORYON_L13_CHECKPOINT','oryon-l13-residual/diffusion_state.pt'));policy=Denoiser().to(device);policy.load_state_dict(torch.load(ckpt,map_location=device,weights_only=True));policy.eval()
    abar=torch.cumprod(1-torch.linspace(.01,.2,20,device=device),0);env=Push();records=[]
    for seed in range(10000,10000+n):
        state,_=env.reset(seed=seed)
        for step in range(100):
            action=diffusion(policy,abar,state)
            state,_,done,cut,info=env.step(action)
            if done or cut:break
        records.append({'seed':seed,'success':bool(done),'steps':step+1,'distance':info['distance']})
        (out/'diffusion-partial.json').write_text(json.dumps(records,indent=2),encoding='utf8')
    env.close();return records

@torch.no_grad()
def drift(ae,model,episodes):
    metrics={str(h):[] for h in (1,4,8)};visual=[]
    for frames,actions in episodes:
        if len(actions)<8:continue
        for start in range(0,len(actions)-7,8):
            z=ae.encode(tensor(frames[start:start+1]));row={'frames':[]}
            for t in range(8):
                z=model(z,torch.tensor(actions[start+t:start+t+1],device=device));pred=ae.decode(z)[0].permute(1,2,0).cpu().numpy()
                if t+1 in (1,4,8):
                    truth=frames[start+t+1]/255;metrics[str(t+1)].append(float(np.mean((pred-truth)**2)))
                    if not visual:row['frames'].append({'horizon':t+1,'truth':frames[start+t+1].tolist(),'prediction':np.rint(pred*255).clip(0,255).astype('uint8').tolist()})
            if not visual:visual.append(row)
    return {k:{'mse':float(np.mean(v)),'count':len(v)} for k,v in metrics.items()},visual

if __name__=='__main__':
    all_episodes=collect(int(os.environ.get('ORYON_COLLECT','250')));ntrain=int(len(all_episodes)*.8)
    ae,model=train(all_episodes[:ntrain]);errors,visual=drift(ae,model,all_episodes[ntrain:])
    (out/'drift.json').write_text(json.dumps(errors,indent=2),encoding='utf8')
    (out/'visual.json').write_text(json.dumps(visual,separators=(',',':')),encoding='utf8')
    records={'drift':errors,'cem':evaluate(ae,model),'diffusion_privileged':baseline()}
    (out/'results.json').write_text(json.dumps(records,indent=2),encoding='utf8')
    print('errores',errors,'éxitos', {k:sum(x['success'] for x in records[k]) for k in ('cem','diffusion_privileged')})
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
With 121 frames of 480×640, first image separate, temporal compression 4 and spatial compression 8×8, how many values are there with 16 channels?
Quiz
Why is an accurate average one-step prediction insufficient to validate a plan?
Quiz
What is a reasonable comparison for manipulation planning?
Quiz
What best distinguishes a control-useful model from plausible video?
Code
Implement cem_plan(world_model,z0,z_goal,horizon,n_samples,n_elites,iters). world_model receives states of shape (n,d) and actions (n,d), and returns next states. Actions are bounded to [-1,1]. Return a (horizon,d) sequence using final squared distance and a fixed seed. Fit elite mean and deviation each iteration.
def cem_plan(world_model,z0,z_goal,horizon,n_samples,n_elites,iters):
  pass
Shift+Enter to run
Key idea
A world model is useful for control when it predicts action consequences well enough to select and execute decisions; visual plausibility is different evidence.