Skip to content
VDAI with VD

Phase 04 · Computer Vision

World Models & Video Diffusion

A video model that predicts the next seconds of a scene is a world simulator. Condition that prediction on actions and you have a learned game engine.

  • Learn + Build
  • Python
  • 75 minutes
  • Before this: Phase 4 Lesson 10 (Diffusion), Phase 4 Lesson 12 (Video Understanding), Phase 4 Lesson 23 (DiT + Rectified Flow)

Learning Objectives

  • Explain the difference between a pure video generation model (Sora 2) and an action-conditioned world model (Genie 3, DreamerV3)
  • Describe a video DiT: spatio-temporal patches, 3D position encoding, joint attention across (T, H, W) tokens
  • Trace how a world model plugs into robotics: VLM plans → video model simulates → inverse dynamics emits actions
  • Pick between Sora 2, Genie 3, Runway GWM-1 Worlds, Wan-Video, and HunyuanVideo for a given use case (creative video, interactive sim, autonomous-driving synthesis)

The Problem

Video generation and world modelling converged in 2026. A model that can generate a coherent minute of video has, in some sense, learned how the world moves: object permanence, gravity, causality, style. If you condition that prediction on actions (walk left, open the door), the video model becomes a learnable simulator that can replace a game engine, a driving simulator, or a robotics environment.

The stakes are concrete. Genie 3 generates playable environments from a single image. Runway GWM-1 Worlds synthesises infinite explorable scenes. Sora 2 produces minute-long videos with synchronised audio and modelled physics. NVIDIA Cosmos-Drive, Wayve Gaia-2, and Tesla DrivingWorld generate realistic driving video for autonomous-vehicle training data. The world-model paradigm is quietly taking over sim-to-real for robotics.

This lesson is the "big picture" lesson for Phase 4. It connects image generation, video understanding, and agentic reasoning into the architecture pattern dominant research is moving toward.

The Concept

Three families of world-modelling

flowchart LR
    subgraph GEN["Pure video generation"]
        G1["Text / image prompt"] --> G2["Video DiT"] --> G3["Video frames"]
    end
    subgraph ACTION["Action-conditioned world model"]
        A1["Past frames + action"] --> A2["Latent-action video DiT"] --> A3["Next frames"]
        A3 --> A1
    end
    subgraph RL["World models for RL (DreamerV3)"]
        R1["State + action"] --> R2["Latent transition model"] --> R3["Next latent + reward"]
        R3 --> R1
    end

    style GEN fill:#dbeafe,stroke:#2563eb
    style ACTION fill:#fef3c7,stroke:#d97706
    style RL fill:#dcfce7,stroke:#16a34a
  • Sora 2 is pure video generation conditioned on prompts. No action interface. You cannot "steer" it mid-rollout.
  • Genie 3, GWM-1 Worlds, Mirage / Magica are action-conditioned world models. Infer latent actions from observed video, then condition future frame predictions on actions. Interactive — you press keys or move a camera and the scene responds.
  • DreamerV3 and the classic RL world-model family predict in a latent space with explicit action conditioning, trained on a reward signal. Less visual; more useful for sample-efficient RL.

Video DiT architecture

Video latent:          (C, T, H, W)
Patchify (spatial):    grid of P_h x P_w patches per frame
Patchify (temporal):   group P_t frames into a temporal patch
Resulting tokens:      (T / P_t) * (H / P_h) * (W / P_w) tokens

Positional encoding is 3D: a rotary or learned embedding per (t, h, w) coordinate. Attention can be:

  • Full joint — all tokens attend to all tokens. O(N^2) with N tokens. Prohibitive for long videos.
  • Divided — alternate temporal attention (same spatial position, across time: (H*W) * T^2) and spatial attention (same timestep, across space: T * (H*W)^2). Used by TimeSformer and most video DiTs.
  • Window — local windows in (t, h, w). Used by Video Swin.

Every 2026 video diffusion model uses one of these three patterns plus AdaLN conditioning (Lesson 23) and rectified flow.

Conditioning on actions: latent action models

Genie learns a latent action per frame by discriminatively predicting the action between a pair of consecutive frames. The model's decoder then conditions on the inferred latent action — not on explicit keyboard keys. At inference, a user can specify a latent action (or sample one from a fresh prior) and the model generates the next frame consistent with that action.

Sora skips the action interface entirely. Its decoder predicts next spacetime tokens from past spacetime tokens. Prompt conditions the start; nothing steers it mid-generation.

Physical plausibility

Sora 2's 2026 release explicitly advertised physical plausibility: weight, balance, object permanence, cause-and-effect. Measured by the team via hand-rated plausibility scores; the model visibly improves on dropped objects, characters colliding, and failures-on-purpose (a missed jump) versus Sora 1.

Plausibility remains the dominant failure mode. 2024-2025 videos of people eating spaghetti or drinking from glasses revealed the model's lack of persistent object representation. 2026 models (Sora 2, Runway Gen-5, HunyuanVideo) reduce but do not eliminate these.

Autonomous driving world models

Driving world models generate realistic road scenes conditioned on trajectories, bounding boxes, or navigation maps. Usage:

  • Cosmos-Drive-Dreams (NVIDIA) — generates minutes of driving video for RL training.
  • Gaia-2 (Wayve) — trajectory-conditioned scene synthesis for policy evaluation.
  • DrivingWorld (Tesla) — simulates varied weather, time-of-day, traffic conditions.
  • Vista (ByteDance) — reactive driving scene synthesis.

They replace expensive real-world data collection for corner cases — pedestrian jaywalks at night, icy intersections, unusual vehicle types — that would otherwise require millions of miles of driving.

Robotics stack: VLM + video model + inverse dynamics

The emerging three-component robotics loop:

  1. VLM parses the goal ("pick up the red cup"), plans a high-level action sequence.
  2. Video generation model simulates what executing each action would look like — predicts observations N frames ahead.
  3. Inverse dynamics model extracts the concrete motor commands that would produce those observations.

This replaces reward shaping and sample-heavy RL. The world model does the imagination; the inverse dynamics closes the loop on actuation. Genie Envisioner is one instantiation; many research groups are converging on this structure.

Evaluation

  • Visual quality — FVD (Fréchet Video Distance), user studies.
  • Prompt alignment — CLIPScore per frame, VQA-style evaluation.
  • Physical plausibility — hand-rated on a benchmark suite (Sora 2's internal benchmark, VBench).
  • Controllability (for interactive world models) — action → observation consistency; can you go back to a prior state?

Model landscape in 2026

ModelUseParametersOutputLicense
Sora 2text-to-video, audio—1-min 1080p + audioAPI only
Runway Gen-5text/image-to-video—10s clipsAPI
Runway GWM-1 Worldsinteractive world—infinite 3D rolloutAPI
Genie 3interactive world from image11B+playable framesresearch preview
Wan-Video 2.1open text-to-video14Bhigh-quality clipsnon-commercial
HunyuanVideoopen text-to-video13B10s clipspermissive
Cosmos / Cosmos-Driveautonomous driving sim7-14Bdriving scenesNVIDIA open
Magica / Mirage 2AI-native game engine—modifiable worldsproduct

Interactive figure coming later.

Build It

Step 1: 3D patchify for video

import torch
import torch.nn as nn


class VideoPatch3D(nn.Module):
    def __init__(self, in_channels=4, dim=64, patch_t=2, patch_h=2, patch_w=2):
        super().__init__()
        self.proj = nn.Conv3d(
            in_channels, dim,
            kernel_size=(patch_t, patch_h, patch_w),
            stride=(patch_t, patch_h, patch_w),
        )
        self.patch_t = patch_t
        self.patch_h = patch_h
        self.patch_w = patch_w

    def forward(self, x):
        # x: (N, C, T, H, W)
        x = self.proj(x)
        n, c, t, h, w = x.shape
        tokens = x.reshape(n, c, t * h * w).transpose(1, 2)
        return tokens, (t, h, w)

A 3D conv with stride equal to kernel acts as the spatio-temporal patchifier. (T, H, W) -> (T/2, H/2, W/2) grid of tokens.

Step 2: 3D rotary position encoding

Rotary Position Embeddings (RoPE) separately applied along t, h, w axes:

def rope_3d(tokens, t_dim, h_dim, w_dim, grid):
    """
    tokens: (N, T*H*W, D)
    grid: (T, H, W) sizes
    t_dim + h_dim + w_dim == D
    """
    T, H, W = grid
    n, seq, d = tokens.shape
    if t_dim + h_dim + w_dim != d:
        raise ValueError(f"t_dim+h_dim+w_dim ({t_dim}+{h_dim}+{w_dim}) must equal D={d}")
    assert seq == T * H * W
    t_idx = torch.arange(T, device=tokens.device).repeat_interleave(H * W)
    h_idx = torch.arange(H, device=tokens.device).repeat_interleave(W).repeat(T)
    w_idx = torch.arange(W, device=tokens.device).repeat(T * H)
    # Simplified: just scale channels by frequencies. Real RoPE rotates pairs.
    freqs_t = torch.exp(-torch.log(torch.tensor(10000.0)) * torch.arange(t_dim // 2, device=tokens.device) / (t_dim // 2))
    freqs_h = torch.exp(-torch.log(torch.tensor(10000.0)) * torch.arange(h_dim // 2, device=tokens.device) / (h_dim // 2))
    freqs_w = torch.exp(-torch.log(torch.tensor(10000.0)) * torch.arange(w_dim // 2, device=tokens.device) / (w_dim // 2))
    emb_t = torch.cat([torch.sin(t_idx[:, None] * freqs_t), torch.cos(t_idx[:, None] * freqs_t)], dim=-1)
    emb_h = torch.cat([torch.sin(h_idx[:, None] * freqs_h), torch.cos(h_idx[:, None] * freqs_h)], dim=-1)
    emb_w = torch.cat([torch.sin(w_idx[:, None] * freqs_w), torch.cos(w_idx[:, None] * freqs_w)], dim=-1)
    return tokens + torch.cat([emb_t, emb_h, emb_w], dim=-1)

Simplified additive form. Real RoPE rotates paired channels at frequencies; the positional information is the same.

Step 3: Divided attention block

class DividedAttentionBlock(nn.Module):
    def __init__(self, dim=64, heads=2):
        super().__init__()
        self.time_attn = nn.MultiheadAttention(dim, heads, batch_first=True)
        self.space_attn = nn.MultiheadAttention(dim, heads, batch_first=True)
        self.ln1 = nn.LayerNorm(dim)
        self.ln2 = nn.LayerNorm(dim)
        self.ln3 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))

    def forward(self, x, grid):
        T, H, W = grid
        n, seq, d = x.shape
        # time attention: same (h, w), across t
        xt = x.view(n, T, H * W, d).permute(0, 2, 1, 3).reshape(n * H * W, T, d)
        a, _ = self.time_attn(self.ln1(xt), self.ln1(xt), self.ln1(xt), need_weights=False)
        xt = (xt + a).reshape(n, H * W, T, d).permute(0, 2, 1, 3).reshape(n, seq, d)
        # space attention: same t, across (h, w)
        xs = xt.view(n, T, H * W, d).reshape(n * T, H * W, d)
        a, _ = self.space_attn(self.ln2(xs), self.ln2(xs), self.ln2(xs), need_weights=False)
        xs = (xs + a).reshape(n, T, H * W, d).reshape(n, seq, d)
        xs = xs + self.mlp(self.ln3(xs))
        return xs

The time attention attends within each spatial position across time; the space attention attends within each frame across positions. Two O(T^2 + (HW)^2) operations instead of one O((THW)^2). This is the core of TimeSformer and every modern video DiT.

Step 4: Compose a tiny video DiT

class TinyVideoDiT(nn.Module):
    def __init__(self, in_channels=4, dim=64, depth=2, heads=2):
        super().__init__()
        self.patch = VideoPatch3D(in_channels=in_channels, dim=dim, patch_t=2, patch_h=2, patch_w=2)
        self.blocks = nn.ModuleList([DividedAttentionBlock(dim, heads) for _ in range(depth)])
        self.out = nn.Linear(dim, in_channels * 2 * 2 * 2)

    def forward(self, x):
        tokens, grid = self.patch(x)
        for blk in self.blocks:
            tokens = blk(tokens, grid)
        return self.out(tokens), grid

Not a working video generator; a structural demo that every piece shapes correctly.

Step 5: Check shapes

vid = torch.randn(1, 4, 8, 16, 16)  # (N, C, T, H, W)
model = TinyVideoDiT()
out, grid = model(vid)
print(f"input  {tuple(vid.shape)}")
print(f"tokens grid {grid}")
print(f"output {tuple(out.shape)}")

Expect grid = (4, 8, 8) and out = (1, 256, 32) after patching; the head then projects to per-token spatio-temporal patches, ready to be un-patchified back into a video.

Use It

Production access patterns for 2026:

  • Sora 2 API (OpenAI) — text-to-video, synchronized audio. Premium pricing.
  • Runway Gen-5 / GWM-1 (Runway) — image-to-video, interactive worlds.
  • Wan-Video 2.1 / HunyuanVideo — open-source self-host.
  • Cosmos / Cosmos-Drive (NVIDIA) — driving simulation open weights.
  • Genie 3 — research preview, request access.

For building an interactive world-model demo: start with Wan-Video for quality, layer on a latent-action adapter for interactivity. For autonomous driving simulation: Cosmos-Drive is the 2026 open reference.

For robotics, the stack in the wild:

  1. Language goal -> VLM (Qwen3-VL) -> high-level plan.
  2. Plan -> latent-action video model -> imagined rollout.
  3. Rollout -> inverse dynamics model -> low-level actions.
  4. Actions executed -> observation fed back into step 1.

Ship It

This lesson produces:

  • outputs/prompt-video-model-picker.md — picks between Sora 2 / Runway / Wan / HunyuanVideo / Cosmos given task, license, and latency.
  • outputs/skill-physical-plausibility-checks.md — a skill that defines automated checks (object permanence, gravity, continuity) to run on any generated video before shipping.

Exercises

  1. (Easy) Compute the token count for a 5-second 360p video at patch-t=2, patch-h=8, patch-w=8. Reason about memory for attention at this size.
  2. (Medium) Swap the divided attention block above for a full joint attention block and measure the shape and parameter count. Explain why divided attention is necessary for real video models.
  3. (Hard) Build a minimal latent-action video model: take a dataset of (frame_t, action_t, frame_{t+1}) triples (any simple 2D game), train a tiny video DiT conditioned on action embeddings, and show that different actions produce different next frames.

Key Terms

TermWhat people sayWhat it actually means
World model"Learned simulator"A model that predicts future observations given state and action
Video DiT"Spacetime transformer"Diffusion transformer with 3D patchification and divided attention
Latent action"Inferred control"Discrete or continuous action latent inferred from frame pairs; used to condition next-frame generation
Divided attention"Time then space"Two attention operations per block — across time then across space — to keep O(N^2) manageable
Object permanence"Things stay real"Scene property that video models must learn; classic failure mode on food, glassware
FVD"Fréchet Video Distance"Video equivalent of FID; primary visual quality metric
Inverse dynamics model"Observations to actions"Given (state, next state), output the action that connects them; closes robotics loop
Cosmos-Drive"NVIDIA driving sim"Open-weights autonomous-driving world model for RL and evaluation

Further Reading

Code

  • main.py

    python phases/04-computer-vision/28-world-models-video-diffusion/code/main.pyOpen on GitHub ↗

Take-away files

prompt-video-model-picker.md

---
name: prompt-video-model-picker
description: Pick Sora 2 / Runway Gen-5 / Wan-Video / HunyuanVideo / Cosmos for a given task, license, and latency target
phase: 4
lesson: 28
---

You are a video model selector.

## Inputs

- `task`: creative_video | interactive_world | driving_sim | robotics_sim | product_ad | explainer
- `duration_s`: length needed
- `interactivity`: static | mid-rollout-steerable
- `license_need`: permissive | commercial_ok | research_ok | api_ok
- `quality_target`: prototype | production | premium

## Decision

Apply in order; first matching rule wins.

1. `interactivity == mid-rollout-steerable` -> **Runway GWM-1 Worlds** (production) or **Genie 3 research preview**.
2. `task == driving_sim` -> **NVIDIA Cosmos-Drive**.
3. `task == robotics_sim` -> **Genie Envisioner** or a latent-action-tuned **HunyuanVideo**.
4. `quality_target == premium` and `license_need == api_ok` -> **Sora 2** (best quality + synchronised audio) or **Runway Gen-5**.
5. `quality_target in [prototype, production]` and `license_need == permissive` -> **HunyuanVideo** (13B) or **Wan-Video 2.1** (14B).
6. `duration_s > 30` -> **Sora 2** only; open models top out at ~10-20 seconds.
7. default -> **Runway Gen-5** (API) for static video generation.

## Output

```
[video model]
  name:           <id>
  duration_cap:   <seconds>
  resolution_cap: <H x W>
  interactivity:  static | steerable

[deployment]
  hosting:     <API | self-host GPU cluster>
  compute:     <GPUs needed>
  cost estimate: <per video>

[caveats]
  - license notes
  - quality failures to watch for (object permanence, motion artefacts)
  - audio availability
```

## Rules

- For `task == product_ad`, prefer Sora 2 or Runway Gen-5 for quality; open models currently trail.
- For `task == robotics_sim`, the video model alone is not enough; name the required inverse-dynamics model.
- Always flag physical-plausibility failure modes; video models in 2026 still mishandle subtle physics.
- Never recommend generating public-use content with proprietary-data-trained models without the customer checking training-data licenses.

skill-physical-plausibility-checks.md

---
name: skill-physical-plausibility-checks
description: Automated checks for object permanence, gravity, and continuity on any generated video before shipping
version: 1.0.0
phase: 4
lesson: 28
tags: [video-generation, quality, physics, evaluation]
---

# Physical Plausibility Checks

Production deployments of generated video need automated guardrails. Human review does not scale; physics checks catch the classic failure modes.

## When to use

- Any product that generates video from text or image prompts.
- Automating QA on a video generation API endpoint.
- Monitoring a video model's quality drift after fine-tuning or a base-model update.

## Inputs

- `video`: a tensor `(T, H, W, 3)` or a path to an mp4.
- Optional reference info: expected number of objects, initial scene description.

## Checks

### 1. Object permanence
Track every detection across frames with SAM 3.1 Object Multiplex. Flag when a stable track disappears for <=3 frames and reappears — the model lost the object temporarily. Hard fail when an object disappears near the frame centre (not at an edge); soft fail at edges.

### 2. Motion smoothness
Optical flow between consecutive frames should be mostly continuous. Sudden per-pixel flow spikes indicate teleportation. Compute flow with RAFT; flag frames where the 99th-percentile flow magnitude exceeds the median by a factor > 10.

### 3. Gravity / support
For objects detected as solid (food, balls, tools), check that their vertical position is non-increasing in the absence of a lifting action. Flag upward drift unless a "grasping hand" is detected near the object.

### 4. Identity consistency
For people or characters, use a face-recognition embedding across frames. Cosine similarity should stay > 0.8 across 5-frame windows for a persistent identity. Below threshold means the character morphed.

### 5. Hands and limbs
Run a pose estimator (Lesson 21). Flag frames where a hand has > 5 or < 4 visible fingers; where an arm length doubles between frames; where limbs intersect the body through a surface.

### 6. Text rendering (if prompt asked for text)
If the user prompt included a string in quotes, OCR the generated frames and compute CER against the requested string. Flag > 20% CER.

## Report

```
[plausibility]
  video frames:           <T>
  permanence violations:  <N>
  smoothness violations:  <N>
  gravity violations:     <N>
  identity drift:         <N of 5-frame windows>
  limb anomalies:         <N>
  OCR CER vs requested:   <float>

[verdict]
  ship | hold | reject

[samples for review]
  frame ranges where each failure occurred
```

## Rules

- Do not hard-block on any single check; aggregate scores and hold the video for review when total anomalies exceed a threshold.
- Weight identity drift and permanence violations highest — users notice them first.
- Log per-check failure rates over time; a rising trend usually means the base model was updated or the prompt distribution shifted.
- Never delete the flagged video; keep it for model debugging and post-mortems.
- For sensitive content (people, children, public figures), require human review of every video regardless of score.