Skip to content

torch_world.models ​

INFO

本页尚未翻译。 阅读英文版

class JEPA ​

torch_world.models.JEPA GitHub

python
JEPA()

Joint-embedding predictive architecture: predict the embedding of a target from the embedding of a context.

Subclasses implement forward returning a dict with a scalar "loss" and its components.

Source code in torch_world/models/base.py
python
class JEPA(nn.Module):
    """Joint-embedding predictive architecture: predict the embedding of a target from the embedding of a context.

    Subclasses implement ``forward`` returning a dict with a scalar ``"loss"`` and its components.
    """

    def make_target_encoder(self, encoder: nn.Module) -> nn.Module:
        """Frozen copy of ``encoder`` updated by exponential moving average."""
        return copy.deepcopy(encoder).requires_grad_(False)

    def update_target(self, momentum: float):
        ema_update(self.target_encoder, self.encoder, momentum)

method make_target_encoder ​

torch_world.models.JEPA.make_target_encoder GitHub

python
make_target_encoder(encoder: nn.Module) -> nn.Module

Frozen copy of encoder updated by exponential moving average.

Source code in torch_world/models/base.py
python
def make_target_encoder(self, encoder: nn.Module) -> nn.Module:
    """Frozen copy of ``encoder`` updated by exponential moving average."""
    return copy.deepcopy(encoder).requires_grad_(False)

class WorldModel ​

torch_world.models.WorldModel GitHub

python
WorldModel()

Action-conditioned latent world model.

Latents are (B, T, ...). predict(z, actions) maps z[:, t] and actions[:, t] to a prediction of z[:, t + 1] for every t (teacher forcing). rollout and cost build on it for planning.

Members

MemberDescription
rolloutUnroll from T0 context latents with T >= T0 actions; returns T + 1 latents.
costSquared distance between the final latent of each rollout (B, T, ...) and the goal latent (B, ...).
Source code in torch_world/models/base.py
python
class WorldModel(nn.Module):
    """Action-conditioned latent world model.

    Latents are ``(B, T, ...)``. ``predict(z, actions)`` maps ``z[:, t]`` and ``actions[:, t]`` to a prediction of
    ``z[:, t + 1]`` for every ``t`` (teacher forcing). ``rollout`` and ``cost`` build on it for planning.
    """

    history: int | None = None

    def encode(self, *args, **kwargs) -> Tensor:
        raise NotImplementedError

    def predict(self, z: Tensor, actions: Tensor, **cond) -> Tensor:
        raise NotImplementedError

    def rollout(self, z: Tensor, actions: Tensor, **cond) -> Tensor:
        """Unroll from ``T0`` context latents with ``T >= T0`` actions; returns ``T + 1`` latents."""
        for t in range(z.size(1), actions.size(1) + 1):
            s = slice(max(0, t - self.history) if self.history else 0, t)
            z = torch.cat([z, self.predict(z[:, s], actions[:, s], **cond)[:, -1:]], dim=1)
        return z

    def cost(self, z: Tensor, goal: Tensor) -> Tensor:
        """Squared distance between the final latent of each rollout ``(B, T, ...)`` and the goal latent ``(B, ...)``."""
        return (z[:, -1] - goal).square().flatten(1).mean(1)

method rollout ​

torch_world.models.WorldModel.rollout GitHub

python
rollout(z: Tensor, actions: Tensor, **cond) -> Tensor

Unroll from T0 context latents with T >= T0 actions; returns T + 1 latents.

Source code in torch_world/models/base.py
python
def rollout(self, z: Tensor, actions: Tensor, **cond) -> Tensor:
    """Unroll from ``T0`` context latents with ``T >= T0`` actions; returns ``T + 1`` latents."""
    for t in range(z.size(1), actions.size(1) + 1):
        s = slice(max(0, t - self.history) if self.history else 0, t)
        z = torch.cat([z, self.predict(z[:, s], actions[:, s], **cond)[:, -1:]], dim=1)
    return z

method cost ​

torch_world.models.WorldModel.cost GitHub

python
cost(z: Tensor, goal: Tensor) -> Tensor

Squared distance between the final latent of each rollout (B, T, ...) and the goal latent (B, ...).

Source code in torch_world/models/base.py
python
def cost(self, z: Tensor, goal: Tensor) -> Tensor:
    """Squared distance between the final latent of each rollout ``(B, T, ...)`` and the goal latent ``(B, ...)``."""
    return (z[:, -1] - goal).square().flatten(1).mean(1)

class WorldActionModel ​

torch_world.models.WorldActionModel GitHub

python
WorldActionModel()

World model that also outputs actions: a policy and a dynamics model in one network.

sample_actions(z, goal) draws an action chunk from context latents, predict_future(z, actions) predicts the latents that chunk leads to, and imagine(z, goal) samples both jointly. decode maps latents back to pixels when the latent space has a decoder, and returns None otherwise.

Source code in torch_world/models/base.py
python
class WorldActionModel(WorldModel):
    """World model that also *outputs* actions: a policy and a dynamics model in one network.

    ``sample_actions(z, goal)`` draws an action chunk from context latents, ``predict_future(z, actions)`` predicts
    the latents that chunk leads to, and ``imagine(z, goal)`` samples both jointly. ``decode`` maps latents back to
    pixels when the latent space has a decoder, and returns ``None`` otherwise.
    """

    def sample_actions(self, z: Tensor, goal: Tensor | None = None, **kwargs) -> Tensor:
        raise NotImplementedError

    def predict_future(self, z: Tensor, actions: Tensor, goal: Tensor | None = None, **kwargs) -> Tensor:
        raise NotImplementedError

    def imagine(self, z: Tensor, goal: Tensor | None = None, **kwargs) -> tuple[Tensor, Tensor]:
        raise NotImplementedError

    def decode(self, z: Tensor) -> Tensor | None:
        return None

class IJEPA ​

torch_world.models.IJEPA GitHub

python
IJEPA(encoder: VisionTransformer, predictor: MaskedPredictor)

I-JEPA: predict the target encoder's features of masked image blocks from a visible context block.

Targets are layer-normalized features of an EMA target encoder, and the loss is smooth L1. Call update_target(momentum) after each optimizer step (reference schedule: 0.996 to 1.0).

Assran et al., "Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture", CVPR 2023. Paper: https://arxiv.org/abs/2301.08243 Code: https://github.com/facebookresearch/ijepa

Example::

encoder = VisionTransformer.from_size("huge", img_size=224, patch_size=14)
model = IJEPA(encoder, MaskedPredictor(encoder.grid, encoder.embed_dim, 384, depth=12, num_heads=12))
masks_enc, masks_pred = MultiBlockMask(encoder.grid)(batch_size)
loss = model(images, masks_enc, masks_pred)["loss"]
Source code in torch_world/models/jepa/_ijepa.py
python
class IJEPA(JEPA):
    """I-JEPA: predict the target encoder's features of masked image blocks from a visible context block.

    Targets are layer-normalized features of an EMA target encoder, and the loss is smooth L1. Call
    ``update_target(momentum)`` after each optimizer step (reference schedule: 0.996 to 1.0).

    Assran et al., "Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture", CVPR 2023.
    Paper: https://arxiv.org/abs/2301.08243
    Code: https://github.com/facebookresearch/ijepa

    Example::

        encoder = VisionTransformer.from_size("huge", img_size=224, patch_size=14)
        model = IJEPA(encoder, MaskedPredictor(encoder.grid, encoder.embed_dim, 384, depth=12, num_heads=12))
        masks_enc, masks_pred = MultiBlockMask(encoder.grid)(batch_size)
        loss = model(images, masks_enc, masks_pred)["loss"]
    """

    def __init__(self, encoder: VisionTransformer, predictor: MaskedPredictor):
        super().__init__()
        self.encoder = encoder
        self.predictor = predictor
        self.target_encoder = self.make_target_encoder(encoder)

    @torch.no_grad()
    def targets(self, x: Tensor, masks_enc: list[Tensor], masks_pred: list[Tensor]) -> Tensor:
        h = self.target_encoder(x)
        h = F.layer_norm(h, h.shape[-1:])
        return repeat_interleave_batch(apply_masks(h, masks_pred), len(x), len(masks_enc))

    def forward(self, x: Tensor, masks_enc: list[Tensor], masks_pred: list[Tensor]) -> dict[str, Tensor]:
        h = self.targets(x, masks_enc, masks_pred)
        z = self.predictor(self.encoder(x, masks_enc), masks_enc, masks_pred)
        return {"loss": F.smooth_l1_loss(z, h)}

class VJEPA ​

torch_world.models.VJEPA GitHub

python
VJEPA(
    encoder: VisionTransformer,
    predictor: MaskedPredictor,
    loss_exp: float = 1.0,
    reg_coeff: float = 0.0,
)

V-JEPA: predict EMA target features of masked spatio-temporal tubes of a video.

masks_enc and masks_pred hold one (B, K) context/target pair per masking strategy (short-range and long-range in the paper), and strategy i uses the predictor's mask token i. The loss is mean(|z - h| ** loss_exp) / loss_exp, averaged over strategies, plus reg_coeff times a variance hinge on the predictions. V-JEPA 2 keeps this objective with 3D RoPE: build the encoder and predictor with use_rope=True.

Bardes et al., "Revisiting Feature Prediction for Learning Visual Representations from Video", 2024. Paper: https://arxiv.org/abs/2404.08471 Code: https://github.com/facebookresearch/jepa

Assran et al., "V-JEPA 2: Self-Supervised Video Models Enable Understanding, Prediction and Planning", 2025. Paper: https://arxiv.org/abs/2506.09985 Code: https://github.com/facebookresearch/vjepa2

Source code in torch_world/models/jepa/_vjepa.py
python
class VJEPA(JEPA):
    """V-JEPA: predict EMA target features of masked spatio-temporal tubes of a video.

    ``masks_enc`` and ``masks_pred`` hold one ``(B, K)`` context/target pair per masking strategy (short-range and
    long-range in the paper), and strategy ``i`` uses the predictor's mask token ``i``. The loss is
    ``mean(|z - h| ** loss_exp) / loss_exp``, averaged over strategies, plus ``reg_coeff`` times a variance hinge on
    the predictions. V-JEPA 2 keeps this objective with 3D RoPE: build the encoder and predictor with ``use_rope=True``.

    Bardes et al., "Revisiting Feature Prediction for Learning Visual Representations from Video", 2024.
    Paper: https://arxiv.org/abs/2404.08471
    Code: https://github.com/facebookresearch/jepa

    Assran et al., "V-JEPA 2: Self-Supervised Video Models Enable Understanding, Prediction and Planning", 2025.
    Paper: https://arxiv.org/abs/2506.09985
    Code: https://github.com/facebookresearch/vjepa2
    """

    def __init__(
        self, encoder: VisionTransformer, predictor: MaskedPredictor, loss_exp: float = 1.0, reg_coeff: float = 0.0
    ):
        super().__init__()
        self.encoder = encoder
        self.predictor = predictor
        self.target_encoder = self.make_target_encoder(encoder)
        self.loss_exp = loss_exp
        self.reg_coeff = reg_coeff

    def forward(self, x: Tensor, masks_enc: list[Tensor], masks_pred: list[Tensor]) -> dict[str, Tensor]:
        with torch.no_grad():
            h = self.target_encoder(x)
            h = F.layer_norm(h, h.shape[-1:])
        jepa, reg = 0.0, 0.0
        for i, (m_enc, m_pred) in enumerate(zip(masks_enc, masks_pred)):
            z = self.predictor(self.encoder(x, [m_enc]), [m_enc], [m_pred], mask_index=i)
            jepa = jepa + (z - apply_masks(h, [m_pred])).abs().pow(self.loss_exp).mean() / self.loss_exp
            reg = reg + F.relu(1.0 - (z.var(dim=1) + 1e-4).sqrt()).mean()
        jepa, reg = jepa / len(masks_pred), reg / len(masks_pred)
        return {"loss": jepa + self.reg_coeff * reg, "jepa_loss": jepa, "reg_loss": reg}

class VJEPA21 ​

torch_world.models.VJEPA21 GitHub

python
VJEPA21(
    encoder: VJEPA21Encoder,
    predictor: VJEPA21Predictor,
    context_coeff: float = 0.5,
    distance_weighting: bool = True,
    loss_exp: float = 1.0,
)

V-JEPA 2.1: V-JEPA 2 with a dense loss on every token and deep self-supervision of several encoder levels.

The predictor reads the context tokens' encoder levels and predicts the EMA target's levels, each layer-normalized, at both the masked tokens and the visible context tokens. With p = loss_exp, the loss is

mean(|z - h| ** p) / p + context_coeff * mean(w * |z_ctx - h_ctx| ** p) / p

averaged over masking strategies, where w = 1 / sqrt(d) and d is the distance on the token grid from a context token to the nearest masked token (w = 1 without distance_weighting). The paper warms context_coeff up linearly from 0 and uses 0.5 for videos and 0.7 for images; pass context_coeff to forward to schedule it. Images (B, C, H, W) train the same way when the encoder has images=True.

Mur-Labadia et al., "V-JEPA 2.1: Unlocking Dense Features in Video Self-Supervised Learning", 2026. Paper: https://arxiv.org/abs/2603.14482 Code: https://github.com/facebookresearch/vjepa2

Source code in torch_world/models/jepa/_vjepa21.py
python
class VJEPA21(JEPA):
    """V-JEPA 2.1: V-JEPA 2 with a dense loss on every token and deep self-supervision of several encoder levels.

    The predictor reads the context tokens' encoder levels and predicts the EMA target's levels, each layer-normalized,
    at both the masked tokens and the visible context tokens. With ``p = loss_exp``, the loss is

    ``mean(|z - h| ** p) / p  +  context_coeff * mean(w * |z_ctx - h_ctx| ** p) / p``

    averaged over masking strategies, where ``w = 1 / sqrt(d)`` and ``d`` is the distance on the token grid from a
    context token to the nearest masked token (``w = 1`` without ``distance_weighting``). The paper warms
    ``context_coeff`` up linearly from 0 and uses 0.5 for videos and 0.7 for images; pass ``context_coeff`` to
    ``forward`` to schedule it. Images ``(B, C, H, W)`` train the same way when the encoder has ``images=True``.

    Mur-Labadia et al., "V-JEPA 2.1: Unlocking Dense Features in Video Self-Supervised Learning", 2026.
    Paper: https://arxiv.org/abs/2603.14482
    Code: https://github.com/facebookresearch/vjepa2
    """

    def __init__(
        self,
        encoder: VJEPA21Encoder,
        predictor: VJEPA21Predictor,
        context_coeff: float = 0.5,
        distance_weighting: bool = True,
        loss_exp: float = 1.0,
    ):
        super().__init__()
        self.encoder = encoder
        self.predictor = predictor
        self.target_encoder = self.make_target_encoder(encoder)
        self.context_coeff = context_coeff
        self.distance_weighting = distance_weighting
        self.loss_exp = loss_exp

    def distance_weights(self, mask_enc: Tensor, mask_pred: Tensor) -> Tensor:
        """``1 / sqrt(d)`` ``(B, K)``, ``d`` the grid distance from each context token to its nearest target token."""
        coords = self.encoder.coords.expand(mask_enc.size(0), -1, -1)
        d = torch.cdist(apply_masks(coords, [mask_enc]), apply_masks(coords, [mask_pred])).amin(-1)
        return d.clamp_min(1.0).rsqrt()

    def forward(
        self, x: Tensor, masks_enc: list[Tensor], masks_pred: list[Tensor], context_coeff: float | None = None
    ) -> dict[str, Tensor]:
        L, D, p = len(self.encoder.levels), self.encoder.embed_dim, self.loss_exp
        image = x.dim() == 4
        with torch.no_grad():
            h = self.target_encoder(x, all_levels=True).unflatten(-1, (L, D))
            h = F.layer_norm(h, (D,)).flatten(-2)
        pred, context = 0.0, 0.0
        for i, (m_enc, m_pred) in enumerate(zip(masks_enc, masks_pred)):
            z, c = self.predictor(self.encoder(x, [m_enc], all_levels=True), [m_enc], [m_pred], i, image=image)
            pred = pred + (z - apply_masks(h, [m_pred])).abs().pow(p).mean() / p
            err = (c - apply_masks(h, [m_enc])).abs().pow(p)
            if self.distance_weighting:
                err = err * self.distance_weights(m_enc, m_pred)[..., None]
            context = context + err.mean() / p
        pred, context = pred / len(masks_pred), context / len(masks_pred)
        coeff = self.context_coeff if context_coeff is None else context_coeff
        return {"loss": pred + coeff * context, "pred_loss": pred, "context_loss": context}

method distance_weights ​

torch_world.models.VJEPA21.distance_weights GitHub

python
distance_weights(mask_enc: Tensor, mask_pred: Tensor) -> Tensor

1 / sqrt(d) (B, K), d the grid distance from each context token to its nearest target token.

Source code in torch_world/models/jepa/_vjepa21.py
python
def distance_weights(self, mask_enc: Tensor, mask_pred: Tensor) -> Tensor:
    """``1 / sqrt(d)`` ``(B, K)``, ``d`` the grid distance from each context token to its nearest target token."""
    coords = self.encoder.coords.expand(mask_enc.size(0), -1, -1)
    d = torch.cdist(apply_masks(coords, [mask_enc]), apply_masks(coords, [mask_pred])).amin(-1)
    return d.clamp_min(1.0).rsqrt()

class VJEPA21Encoder ​

torch_world.models.VJEPA21Encoder GitHub

python
VJEPA21Encoder(*args, levels: int = 4, images: bool = False, **kwargs)

The video ViT of V-JEPA 2.1: multi-level outputs and, with images, a separate image tokenizer.

levels evenly spaced blocks, the last one the final block (blocks [2, 5, 8, 11] of a 12-block ViT), each have their own layer norm. forward(x, all_levels=True) concatenates their outputs into (B, N, levels * D), the input of the predictor and the target of the loss; by default it returns only the normalized final output, as a V-JEPA encoder does. With images, images (B, C, H, W) go through a 2D patch embedding onto the first frame of the grid instead of being repeated over time, and a learned modality embedding marks images and videos.

Source code in torch_world/models/jepa/_vjepa21.py
python
class VJEPA21Encoder(VisionTransformer):
    """The video ViT of V-JEPA 2.1: multi-level outputs and, with ``images``, a separate image tokenizer.

    ``levels`` evenly spaced blocks, the last one the final block (blocks ``[2, 5, 8, 11]`` of a 12-block ViT), each
    have their own layer norm. ``forward(x, all_levels=True)`` concatenates their outputs into ``(B, N, levels * D)``,
    the input of the predictor and the target of the loss; by default it returns only the normalized final output, as
    a V-JEPA encoder does. With ``images``, images ``(B, C, H, W)`` go through a 2D patch embedding onto the first
    frame of the grid instead of being repeated over time, and a learned modality embedding marks images and videos.
    """

    def __init__(self, *args, levels: int = 4, images: bool = False, **kwargs):
        super().__init__(*args, **kwargs)
        depth = len(self.transformer.blocks)
        self.levels = [(i + 1) * depth // levels - 1 for i in range(levels)]
        self.norms = nn.ModuleList([LayerNorm(self.embed_dim) for _ in self.levels[:-1]] + [self.transformer.norm])
        conv = self.patch_embed.proj
        self.image_embed = PatchEmbed(conv.kernel_size[-1], conv.in_channels, self.embed_dim) if images else None
        self.modality_embed = nn.Parameter(1e-6 * torch.randn(2, 1, self.embed_dim)) if images else None

    def forward(self, x: Tensor, masks: list[Tensor] | None = None, all_levels: bool = False) -> Tensor:
        image = self.image_embed is not None and x.dim() == 4
        if image:
            x = self.image_embed(x)
            x, coords = x + self.pos_embed[:, : x.size(1)], self.coords[: x.size(1)]
        else:
            x, coords = self.embed(x)
        if self.modality_embed is not None:
            x = x + self.modality_embed[int(image)]
        pos = None
        if masks is not None:
            x = apply_masks(x, masks)
        if self.use_rope:
            pos = coords if masks is None else apply_masks(coords.expand(x.size(0), -1, -1), masks)
        outs = []
        for i, block in enumerate(self.transformer.blocks):
            x = block(x, pos=pos)
            if i in self.levels:
                outs.append(self.norms[self.levels.index(i)](x))
        return torch.cat(outs, dim=-1) if all_levels else outs[-1]

class VJEPA21Predictor ​

torch_world.models.VJEPA21Predictor GitHub

python
VJEPA21Predictor(
    grid: tuple[int, ...],
    embed_dim: int,
    predictor_dim: int = 384,
    levels: int = 4,
    images: bool = False,
    init_std: float = 0.02,
    **kwargs,
)

V-JEPA 2.1 predictor: reads and predicts levels encoder levels, for target and context tokens alike.

An MLP fuses the concatenated levels of the context tokens. forward returns (z_pred, z_context): the predictions at the target positions and, through a separate head, at the context positions, each with levels * embed_dim channels. With images, a learned modality embedding is added to every token.

Source code in torch_world/models/jepa/_vjepa21.py
python
class VJEPA21Predictor(MaskedPredictor):
    """V-JEPA 2.1 predictor: reads and predicts ``levels`` encoder levels, for target and context tokens alike.

    An MLP fuses the concatenated levels of the context tokens. ``forward`` returns ``(z_pred, z_context)``: the
    predictions at the target positions and, through a separate head, at the context positions, each with
    ``levels * embed_dim`` channels. With ``images``, a learned modality embedding is added to every token.
    """

    def __init__(
        self,
        grid: tuple[int, ...],
        embed_dim: int,
        predictor_dim: int = 384,
        levels: int = 4,
        images: bool = False,
        init_std: float = 0.02,
        **kwargs,
    ):
        super().__init__(grid, embed_dim, predictor_dim, init_std=init_std, **kwargs)
        self.embed = MLP([levels * embed_dim, embed_dim, predictor_dim])
        self.proj = nn.Linear(predictor_dim, levels * embed_dim)
        self.proj_context = nn.Linear(predictor_dim, levels * embed_dim)
        for m in (self.embed, self.proj, self.proj_context):
            init_weights(m, init_std)
        self.modality_embed = nn.Parameter(1e-6 * torch.randn(2, 1, 1, predictor_dim)) if images else None

    def forward(
        self, x: Tensor, masks_x: list[Tensor], masks_y: list[Tensor], mask_index: int = 0, image: bool = False
    ) -> tuple[Tensor, Tensor]:
        B = x.size(0) // len(masks_x)
        pos_embed = self.pos_embed.expand(B, -1, -1)
        x = self.embed(x) + apply_masks(pos_embed, masks_x)
        y = self.mask_tokens[mask_index] + repeat_interleave_batch(apply_masks(pos_embed, masks_y), B, len(masks_x))
        n = x.size(1)
        x = torch.cat([x.repeat(len(masks_y), 1, 1), y], dim=1)
        if self.modality_embed is not None:
            x = x + self.modality_embed[int(image)]
        pos = None
        if self.use_rope:
            coords = self.coords.expand(B, -1, -1)
            pos_x = apply_masks(coords, masks_x).repeat(len(masks_y), 1, 1)
            pos_y = repeat_interleave_batch(apply_masks(coords, masks_y), B, len(masks_x))
            pos = torch.cat([pos_x, pos_y], dim=1)
        x = self.transformer(x, pos=pos)
        return self.proj(x[:, n:]), self.proj_context(x[:, :n])

class LeJEPA ​

torch_world.models.LeJEPA GitHub

python
LeJEPA(
    encoder: nn.Module,
    projector: nn.Module,
    lamb: float = 0.05,
    sigreg: SIGReg | None = None,
)

LeJEPA: multi-view prediction with SIGReg, with no teacher, stop-gradient or schedules.

Each view's projection predicts the mean projection of the num_global global views, and SIGReg pushes the projections of every view toward an isotropic Gaussian. lamb trades the two terms: (1 - lamb) * prediction + lamb * sigreg.

Balestriero & LeCun, "LeJEPA: Provable and Scalable Self-Supervised Learning Without the Heuristics", 2025. Paper: https://arxiv.org/abs/2511.08544 Code: https://github.com/galilai-group/lejepa

Source code in torch_world/models/jepa/_lejepa.py
python
class LeJEPA(JEPA):
    """LeJEPA: multi-view prediction with SIGReg, with no teacher, stop-gradient or schedules.

    Each view's projection predicts the mean projection of the ``num_global`` global views, and SIGReg pushes the
    projections of every view toward an isotropic Gaussian. ``lamb`` trades the two terms:
    ``(1 - lamb) * prediction + lamb * sigreg``.

    Balestriero & LeCun, "LeJEPA: Provable and Scalable Self-Supervised Learning Without the Heuristics", 2025.
    Paper: https://arxiv.org/abs/2511.08544
    Code: https://github.com/galilai-group/lejepa
    """

    def __init__(self, encoder: nn.Module, projector: nn.Module, lamb: float = 0.05, sigreg: SIGReg | None = None):
        super().__init__()
        self.encoder = encoder
        self.projector = projector
        self.lamb = lamb
        self.sigreg = sigreg or SIGReg()

    def forward(self, views: Tensor | Sequence[Tensor], num_global: int | None = None) -> dict[str, Tensor]:
        """``views`` is ``(B, V, ...)`` or a list of ``(B, ...)`` tensors whose first ``num_global`` are global views."""
        views = views.unbind(1) if isinstance(views, Tensor) else views
        z = torch.stack([self.projector(self.encoder(v)) for v in views])
        pred = (z[:num_global].mean(0) - z).square().mean()
        sigreg = self.sigreg(z)
        return {"loss": (1 - self.lamb) * pred + self.lamb * sigreg, "pred_loss": pred, "sigreg_loss": sigreg}

method forward ​

torch_world.models.LeJEPA.forward GitHub

python
forward(
    views: Tensor | Sequence[Tensor], num_global: int | None = None
) -> dict[str, Tensor]

views is (B, V, ...) or a list of (B, ...) tensors whose first num_global are global views.

Source code in torch_world/models/jepa/_lejepa.py
python
def forward(self, views: Tensor | Sequence[Tensor], num_global: int | None = None) -> dict[str, Tensor]:
    """``views`` is ``(B, V, ...)`` or a list of ``(B, ...)`` tensors whose first ``num_global`` are global views."""
    views = views.unbind(1) if isinstance(views, Tensor) else views
    z = torch.stack([self.projector(self.encoder(v)) for v in views])
    pred = (z[:num_global].mean(0) - z).square().mean()
    sigreg = self.sigreg(z)
    return {"loss": (1 - self.lamb) * pred + self.lamb * sigreg, "pred_loss": pred, "sigreg_loss": sigreg}

class LeVJEPA ​

torch_world.models.LeVJEPA GitHub

python
LeVJEPA(
    encoder: nn.Module,
    projector: nn.Module,
    lamb: float = 0.02,
    sigreg: SIGReg | None = None,
)

LeVJEPA: LeJEPA for video, with one global view, V local views and no teacher, stop-gradient or predictor.

Every view of a clip is encoded by the same encoder, read out at its [cls] token and projected. Each projection predicts the projection of the global view, and SIGReg pushes the projections of every view toward an isotropic Gaussian: prediction + lamb * sigreg. Gradients flow through both sides of the prediction term. Use it with a LeVJEPAEncoder, or any encoder whose output starts with a [cls] token.

Kuhn et al., "LeVJEPA: Efficient & Scalable Video Pretraining without the Heuristics", 2026. Paper: https://arxiv.org/abs/2608.27395 Code: https://github.com/galilai-group/levjepa

Members

MemberDescription
encodeClip embedding (B, D): the encoder's [cls] token, before the projector.
forwardglobal_view is (B, C, T, H, W); local_views is (B, V, C, T, h, w) or V tensors (B, C, T, h, w).
Source code in torch_world/models/jepa/_levjepa.py
python
class LeVJEPA(JEPA):
    """LeVJEPA: LeJEPA for video, with one global view, ``V`` local views and no teacher, stop-gradient or predictor.

    Every view of a clip is encoded by the same encoder, read out at its [cls] token and projected. Each projection
    predicts the projection of the global view, and SIGReg pushes the projections of every view toward an isotropic
    Gaussian: ``prediction + lamb * sigreg``. Gradients flow through both sides of the prediction term. Use it with a
    ``LeVJEPAEncoder``, or any encoder whose output starts with a [cls] token.

    Kuhn et al., "LeVJEPA: Efficient & Scalable Video Pretraining without the Heuristics", 2026.
    Paper: https://arxiv.org/abs/2608.27395
    Code: https://github.com/galilai-group/levjepa
    """

    def __init__(self, encoder: nn.Module, projector: nn.Module, lamb: float = 0.02, sigreg: SIGReg | None = None):
        super().__init__()
        self.encoder = encoder
        self.projector = projector
        self.lamb = lamb
        self.sigreg = sigreg or SIGReg()

    def encode(self, x: Tensor) -> Tensor:
        """Clip embedding ``(B, D)``: the encoder's [cls] token, before the projector."""
        return self.encoder(x)[:, 0]

    def forward(self, global_view: Tensor, local_views: Tensor | Sequence[Tensor]) -> dict[str, Tensor]:
        """``global_view`` is ``(B, C, T, H, W)``; ``local_views`` is ``(B, V, C, T, h, w)`` or ``V`` tensors ``(B, C, T, h, w)``."""
        if isinstance(local_views, Tensor):
            B, V = local_views.shape[:2]
            local = self.encode(local_views.flatten(0, 1)).unflatten(0, (B, V)).transpose(0, 1)
        else:
            local = torch.stack([self.encode(v) for v in local_views])
        h = torch.cat([self.encode(global_view)[None], local])
        z = self.projector(h.flatten(0, 1)).unflatten(0, h.shape[:2])
        pred = (z[0] - z).square().mean()
        sigreg = self.sigreg(z)
        return {"loss": pred + self.lamb * sigreg, "pred_loss": pred, "sigreg_loss": sigreg}

method encode ​

torch_world.models.LeVJEPA.encode GitHub

python
encode(x: Tensor) -> Tensor

Clip embedding (B, D): the encoder's [cls] token, before the projector.

Source code in torch_world/models/jepa/_levjepa.py
python
def encode(self, x: Tensor) -> Tensor:
    """Clip embedding ``(B, D)``: the encoder's [cls] token, before the projector."""
    return self.encoder(x)[:, 0]

method forward ​

torch_world.models.LeVJEPA.forward GitHub

python
forward(
    global_view: Tensor, local_views: Tensor | Sequence[Tensor]
) -> dict[str, Tensor]

global_view is (B, C, T, H, W); local_views is (B, V, C, T, h, w) or V tensors (B, C, T, h, w).

Source code in torch_world/models/jepa/_levjepa.py
python
def forward(self, global_view: Tensor, local_views: Tensor | Sequence[Tensor]) -> dict[str, Tensor]:
    """``global_view`` is ``(B, C, T, H, W)``; ``local_views`` is ``(B, V, C, T, h, w)`` or ``V`` tensors ``(B, C, T, h, w)``."""
    if isinstance(local_views, Tensor):
        B, V = local_views.shape[:2]
        local = self.encode(local_views.flatten(0, 1)).unflatten(0, (B, V)).transpose(0, 1)
    else:
        local = torch.stack([self.encode(v) for v in local_views])
    h = torch.cat([self.encode(global_view)[None], local])
    z = self.projector(h.flatten(0, 1)).unflatten(0, h.shape[:2])
    pred = (z[0] - z).square().mean()
    sigreg = self.sigreg(z)
    return {"loss": pred + self.lamb * sigreg, "pred_loss": pred, "sigreg_loss": sigreg}

class LeVJEPAEncoder ​

torch_world.models.LeVJEPAEncoder GitHub

python
LeVJEPAEncoder(
    img_size: int | tuple[int, int] = 224,
    patch_size: int = 16,
    num_frames: int = 16,
    tubelet_size: int = 1,
    token_drop: float = 0.95,
    block_causal: bool = True,
    init_std: float = 0.02,
    **kwargs,
)

The video ViT of LeVJEPA: a [cls] readout, 3D RoPE, random token dropping and block-causal attention.

Videos are (B, C, T, H, W), with one token per frame by default (tubelet_size=1). RoPE positions come from the input's own grid, so global and local views of different sizes share the encoder. In training, a fraction token_drop of patch tokens is dropped uniformly at random after patch embedding; in evaluation every token is kept. With block_causal, patches attend bidirectionally within a frame and causally across frames, so a clip can be encoded incrementally. forward returns (B, 1 + N, D) tokens, [cls] first.

Source code in torch_world/models/jepa/_levjepa.py
python
class LeVJEPAEncoder(VisionTransformer):
    """The video ViT of LeVJEPA: a [cls] readout, 3D RoPE, random token dropping and block-causal attention.

    Videos are ``(B, C, T, H, W)``, with one token per frame by default (``tubelet_size=1``). RoPE positions come from
    the input's own grid, so global and local views of different sizes share the encoder. In training, a fraction
    ``token_drop`` of patch tokens is dropped uniformly at random after patch embedding; in evaluation every token is
    kept. With ``block_causal``, patches attend bidirectionally within a frame and causally across frames, so a clip
    can be encoded incrementally. ``forward`` returns ``(B, 1 + N, D)`` tokens, [cls] first.
    """

    def __init__(
        self,
        img_size: int | tuple[int, int] = 224,
        patch_size: int = 16,
        num_frames: int = 16,
        tubelet_size: int = 1,
        token_drop: float = 0.95,
        block_causal: bool = True,
        init_std: float = 0.02,
        **kwargs,
    ):
        super().__init__(
            img_size,
            patch_size,
            num_frames=num_frames,
            tubelet_size=tubelet_size,
            cls_token=True,
            use_rope=True,
            init_std=init_std,
            **kwargs,
        )
        nn.init.trunc_normal_(self.cls_token, std=init_std)
        self.token_drop = token_drop
        self.block_causal = block_causal

    def forward(self, x: Tensor, masks: list[Tensor] | None = None) -> Tensor:
        """``masks`` are ``(B, K)`` indices of patches to keep; by default random in training and all in evaluation."""
        grid = tuple(s // k for s, k in zip(x.shape[2:], self.patch_embed.proj.kernel_size))
        x = self.patch_embed(x)
        B, N, _ = x.shape
        pos = grid_coords(grid).to(x.device).expand(B, -1, -1)
        if masks is None and self.training and self.token_drop > 0:
            keep = max(1, round(N * (1 - self.token_drop)))
            masks = [torch.rand(B, N, device=x.device).argsort(dim=1)[:, :keep]]
        if masks is not None:
            x, pos = apply_masks(x, masks), apply_masks(pos, masks)
        attn_mask = block_causal_mask(pos[..., 0]) if self.block_causal and len(grid) == 3 else None
        x = torch.cat([self.cls_token.expand(x.size(0), -1, -1), x], dim=1)
        pos = torch.cat([pos.new_zeros(pos.size(0), 1, pos.size(-1)), pos], dim=1)
        return self.transformer(x, attn_mask=attn_mask, pos=pos)

method forward ​

torch_world.models.LeVJEPAEncoder.forward GitHub

python
forward(x: Tensor, masks: list[Tensor] | None = None) -> Tensor

masks are (B, K) indices of patches to keep; by default random in training and all in evaluation.

Source code in torch_world/models/jepa/_levjepa.py
python
def forward(self, x: Tensor, masks: list[Tensor] | None = None) -> Tensor:
    """``masks`` are ``(B, K)`` indices of patches to keep; by default random in training and all in evaluation."""
    grid = tuple(s // k for s, k in zip(x.shape[2:], self.patch_embed.proj.kernel_size))
    x = self.patch_embed(x)
    B, N, _ = x.shape
    pos = grid_coords(grid).to(x.device).expand(B, -1, -1)
    if masks is None and self.training and self.token_drop > 0:
        keep = max(1, round(N * (1 - self.token_drop)))
        masks = [torch.rand(B, N, device=x.device).argsort(dim=1)[:, :keep]]
    if masks is not None:
        x, pos = apply_masks(x, masks), apply_masks(pos, masks)
    attn_mask = block_causal_mask(pos[..., 0]) if self.block_causal and len(grid) == 3 else None
    x = torch.cat([self.cls_token.expand(x.size(0), -1, -1), x], dim=1)
    pos = torch.cat([pos.new_zeros(pos.size(0), 1, pos.size(-1)), pos], dim=1)
    return self.transformer(x, attn_mask=attn_mask, pos=pos)

class VLJEPA ​

torch_world.models.VLJEPA GitHub

python
VLJEPA(
    x_encoder: nn.Module,
    predictor: nn.Module,
    query_embed: nn.Embedding,
    y_encoder: nn.Module,
    vision_dim: int,
    predictor_dim: int,
    text_dim: int,
    embed_dim: int = 1536,
    temperature: float = 0.07,
    y_lr_mult: float = 0.05,
)

VL-JEPA: predict the embedding of a target text from visual tokens and an optional text query.

A frozen X-encoder turns images or videos into visual tokens. The predictor attends bidirectionally over the projected visual tokens followed by the query tokens, and the non-padding outputs are average-pooled into a predicted embedding. The Y-encoder embeds the target text. Linear heads map both into a shared space, and the predictor and Y-encoder are trained jointly with bidirectional InfoNCE. The Y-encoder trains at y_lr_mult times the base learning rate (see param_groups). Text is produced only on demand by a separate decoder; segment picks the decoding points of an embedding stream (selective decoding).

The paper does not report the InfoNCE temperature, so it is learnable here, initialized at 0.07 as in CLIP.

Chen et al., "VL-JEPA: Joint Embedding Predictive Architecture for Vision-language", ICLR 2026. Paper: https://arxiv.org/abs/2512.10942 Code: not released; this follows the paper.

Parameters

NameTypeDescriptionDefault
x_encodernn.Modulefrozen module mapping visual input to tokens (B, N, vision_dim) (V-JEPA 2 ViT-L in the paper).required
predictornn.Modulemodule mapping (tokens, attn_mask=...) to tokens of the same shape (last 8 Llama-3.2-1B layers).required
query_embednn.Embeddingtoken embedding of the predictor's language model.required
y_encodernn.Modulemodule mapping (ids, mask) to pooled text embeddings (B, text_dim) (EmbeddingGemma-300M).required

Members

MemberDescription
predictPredicted target embedding (B, embed_dim); query_mask is True on non-padding query tokens.
retrieveIndex (B,) of the closest row of bank (candidate text embeddings from embed_text) by cosine.
param_groupsOptimizer groups with the Y-encoder at y_lr_mult * lr; the frozen X-encoder is excluded.
segmentSelective decoding points: midpoints of num_segments contiguous segments of a (T, D) stream.
Source code in torch_world/models/jepa/_vljepa.py
python
class VLJEPA(JEPA):
    """VL-JEPA: predict the embedding of a target text from visual tokens and an optional text query.

    A frozen X-encoder turns images or videos into visual tokens. The predictor attends bidirectionally over the
    projected visual tokens followed by the query tokens, and the non-padding outputs are average-pooled into a
    predicted embedding. The Y-encoder embeds the target text. Linear heads map both into a shared space, and the
    predictor and Y-encoder are trained jointly with bidirectional InfoNCE. The Y-encoder trains at
    ``y_lr_mult`` times the base learning rate (see ``param_groups``). Text is produced only on demand by a
    separate decoder; ``segment`` picks the decoding points of an embedding stream (selective decoding).

    The paper does not report the InfoNCE temperature, so it is learnable here, initialized at 0.07 as in CLIP.

    Chen et al., "VL-JEPA: Joint Embedding Predictive Architecture for Vision-language", ICLR 2026.
    Paper: https://arxiv.org/abs/2512.10942
    Code: not released; this follows the paper.

    Args:
        x_encoder: frozen module mapping visual input to tokens ``(B, N, vision_dim)`` (V-JEPA 2 ViT-L in the paper).
        predictor: module mapping ``(tokens, attn_mask=...)`` to tokens of the same shape (last 8 Llama-3.2-1B layers).
        query_embed: token embedding of the predictor's language model.
        y_encoder: module mapping ``(ids, mask)`` to pooled text embeddings ``(B, text_dim)`` (EmbeddingGemma-300M).
    """

    def __init__(
        self,
        x_encoder: nn.Module,
        predictor: nn.Module,
        query_embed: nn.Embedding,
        y_encoder: nn.Module,
        vision_dim: int,
        predictor_dim: int,
        text_dim: int,
        embed_dim: int = 1536,
        temperature: float = 0.07,
        y_lr_mult: float = 0.05,
    ):
        super().__init__()
        self.x_encoder = x_encoder.requires_grad_(False).eval()
        self.vision_proj = nn.Linear(vision_dim, predictor_dim)
        self.query_embed = query_embed
        self.predictor = predictor
        self.pred_head = nn.Linear(predictor_dim, embed_dim)
        self.y_encoder = y_encoder
        self.y_head = nn.Linear(text_dim, embed_dim)
        self.log_scale = nn.Parameter(torch.tensor(math.log(1 / temperature)))
        self.y_lr_mult = y_lr_mult

    def train(self, mode: bool = True):
        super().train(mode)
        self.x_encoder.eval()
        return self

    def predict(self, x: Tensor, query_ids: Tensor | None = None, query_mask: Tensor | None = None) -> Tensor:
        """Predicted target embedding ``(B, embed_dim)``; ``query_mask`` is ``True`` on non-padding query tokens."""
        with torch.no_grad():
            v = self.x_encoder(x)
        tokens = self.vision_proj(v)
        mask = torch.ones(tokens.shape[:2], dtype=torch.bool, device=tokens.device)
        if query_ids is not None:
            tokens = torch.cat([tokens, self.query_embed(query_ids)], dim=1)
            mask = torch.cat(
                [mask, query_mask if query_mask is not None else torch.ones_like(query_ids, dtype=torch.bool)], dim=1
            )
        h = self.predictor(tokens, attn_mask=mask[:, None, None, :])
        pooled = (h * mask[..., None]).sum(1) / mask.sum(1, keepdim=True)
        return self.pred_head(pooled)

    def embed_text(self, ids: Tensor, mask: Tensor | None = None) -> Tensor:
        return self.y_head(self.y_encoder(ids, mask))

    @torch.no_grad()
    def retrieve(
        self, x: Tensor, bank: Tensor, query_ids: Tensor | None = None, query_mask: Tensor | None = None
    ) -> Tensor:
        """Index ``(B,)`` of the closest row of ``bank`` (candidate text embeddings from ``embed_text``) by cosine."""
        pred = F.normalize(self.predict(x, query_ids, query_mask), dim=-1)
        return (pred @ F.normalize(bank, dim=-1).T).argmax(1)

    def forward(
        self,
        x: Tensor,
        target_ids: Tensor,
        target_mask: Tensor | None = None,
        query_ids: Tensor | None = None,
        query_mask: Tensor | None = None,
    ) -> dict[str, Tensor]:
        pred = self.predict(x, query_ids, query_mask)
        target = self.embed_text(target_ids, target_mask)
        return {"loss": info_nce(pred, target, 1 / self.log_scale.exp())}

    def param_groups(self, lr: float, **kwargs) -> list[dict]:
        """Optimizer groups with the Y-encoder at ``y_lr_mult * lr``; the frozen X-encoder is excluded."""
        y = {id(p) for p in self.y_encoder.parameters()}
        rest = [p for p in self.parameters() if p.requires_grad and id(p) not in y]
        return [
            {"params": rest, "lr": lr, **kwargs},
            {"params": list(self.y_encoder.parameters()), "lr": lr * self.y_lr_mult, **kwargs},
        ]

    @staticmethod
    def segment(stream: Tensor, num_segments: int) -> Tensor:
        """Selective decoding points: midpoints of ``num_segments`` contiguous segments of a ``(T, D)`` stream.

        Segments come from agglomerative clustering with temporal connectivity and Ward linkage.
        """
        starts, sizes, means = list(range(len(stream))), [1] * len(stream), list(stream.float())
        while len(starts) > num_segments:
            costs = [
                sizes[i] * sizes[i + 1] / (sizes[i] + sizes[i + 1]) * (means[i] - means[i + 1]).square().sum()
                for i in range(len(starts) - 1)
            ]
            i = int(torch.stack(costs).argmin())
            n = sizes[i] + sizes[i + 1]
            means[i] = (sizes[i] * means[i] + sizes[i + 1] * means[i + 1]) / n
            sizes[i] = n
            del starts[i + 1], sizes[i + 1], means[i + 1]
        return torch.tensor([s + (n - 1) // 2 for s, n in zip(starts, sizes)])

method predict ​

torch_world.models.VLJEPA.predict GitHub

python
predict(
    x: Tensor, query_ids: Tensor | None = None, query_mask: Tensor | None = None
) -> Tensor

Predicted target embedding (B, embed_dim); query_mask is True on non-padding query tokens.

Source code in torch_world/models/jepa/_vljepa.py
python
def predict(self, x: Tensor, query_ids: Tensor | None = None, query_mask: Tensor | None = None) -> Tensor:
    """Predicted target embedding ``(B, embed_dim)``; ``query_mask`` is ``True`` on non-padding query tokens."""
    with torch.no_grad():
        v = self.x_encoder(x)
    tokens = self.vision_proj(v)
    mask = torch.ones(tokens.shape[:2], dtype=torch.bool, device=tokens.device)
    if query_ids is not None:
        tokens = torch.cat([tokens, self.query_embed(query_ids)], dim=1)
        mask = torch.cat(
            [mask, query_mask if query_mask is not None else torch.ones_like(query_ids, dtype=torch.bool)], dim=1
        )
    h = self.predictor(tokens, attn_mask=mask[:, None, None, :])
    pooled = (h * mask[..., None]).sum(1) / mask.sum(1, keepdim=True)
    return self.pred_head(pooled)

method retrieve ​

torch_world.models.VLJEPA.retrieve GitHub

python
retrieve(
    x: Tensor,
    bank: Tensor,
    query_ids: Tensor | None = None,
    query_mask: Tensor | None = None,
) -> Tensor

Index (B,) of the closest row of bank (candidate text embeddings from embed_text) by cosine.

Source code in torch_world/models/jepa/_vljepa.py
python
@torch.no_grad()
def retrieve(
    self, x: Tensor, bank: Tensor, query_ids: Tensor | None = None, query_mask: Tensor | None = None
) -> Tensor:
    """Index ``(B,)`` of the closest row of ``bank`` (candidate text embeddings from ``embed_text``) by cosine."""
    pred = F.normalize(self.predict(x, query_ids, query_mask), dim=-1)
    return (pred @ F.normalize(bank, dim=-1).T).argmax(1)

method param_groups ​

torch_world.models.VLJEPA.param_groups GitHub

python
param_groups(lr: float, **kwargs) -> list[dict]

Optimizer groups with the Y-encoder at y_lr_mult * lr; the frozen X-encoder is excluded.

Source code in torch_world/models/jepa/_vljepa.py
python
def param_groups(self, lr: float, **kwargs) -> list[dict]:
    """Optimizer groups with the Y-encoder at ``y_lr_mult * lr``; the frozen X-encoder is excluded."""
    y = {id(p) for p in self.y_encoder.parameters()}
    rest = [p for p in self.parameters() if p.requires_grad and id(p) not in y]
    return [
        {"params": rest, "lr": lr, **kwargs},
        {"params": list(self.y_encoder.parameters()), "lr": lr * self.y_lr_mult, **kwargs},
    ]

method segment ​

torch_world.models.VLJEPA.segment GitHub

python
segment(stream: Tensor, num_segments: int) -> Tensor

Selective decoding points: midpoints of num_segments contiguous segments of a (T, D) stream.

Segments come from agglomerative clustering with temporal connectivity and Ward linkage.

Source code in torch_world/models/jepa/_vljepa.py
python
@staticmethod
def segment(stream: Tensor, num_segments: int) -> Tensor:
    """Selective decoding points: midpoints of ``num_segments`` contiguous segments of a ``(T, D)`` stream.

    Segments come from agglomerative clustering with temporal connectivity and Ward linkage.
    """
    starts, sizes, means = list(range(len(stream))), [1] * len(stream), list(stream.float())
    while len(starts) > num_segments:
        costs = [
            sizes[i] * sizes[i + 1] / (sizes[i] + sizes[i + 1]) * (means[i] - means[i + 1]).square().sum()
            for i in range(len(starts) - 1)
        ]
        i = int(torch.stack(costs).argmin())
        n = sizes[i] + sizes[i + 1]
        means[i] = (sizes[i] * means[i] + sizes[i + 1] * means[i + 1]) / n
        sizes[i] = n
        del starts[i + 1], sizes[i + 1], means[i + 1]
    return torch.tensor([s + (n - 1) // 2 for s, n in zip(starts, sizes)])

class LeWAM ​

torch_world.models.LeWAM GitHub

python
LeWAM(
    encoder: nn.Module,
    action_dim: int,
    embed_dim: int = 192,
    *,
    history: int = 3,
    chunk_size: int = 8,
    dim: int = 192,
    depth: int = 4,
    num_heads: int = 4,
    mlp_dim: int = 768,
    dropout: float = 0.0,
    flow_steps: int = 8,
    goal_conditioned: bool = True,
    goal_type: str | None = None,
    state_dim: int = 0,
    action_scale=None,
    action_mean=None,
    action_std=None,
    frameskip: int = 1,
    num_states: int | None = None,
    feature_dim: int | None = None,
    projector_norm: str | None = None,
    lamb: float = 0.04,
    action_weight: float = 1.0,
    state_weight: float = 1.0,
    sigreg: SIGReg | None = None,
)

Joint latent dynamics and flow-matching action chunks (Fu et al., 2026).

A mixture of transformers predicts future latent states from clean actions, and an action velocity field from noisy actions. Its grouped attention mask prevents clean-action and future-state leakage into the policy branch. Training jointly minimizes dynamics MSE, action flow matching and SIGReg.

encoder maps (N,C,H,W) to (N,feature_dim or embed_dim). Inputs to forward contain history + chunk_size frames and at least one fewer actions. Goals are separate images from the same episode. goal_conditioned=False trains task-only behavior cloning. Optional remaining is a normalized remaining horizon, seen only by the action branch.

state_dim optionally appends externally normalized measured state. That extension predicts state residuals, initialized to zero, and excludes state coordinates from SIGReg. action_scale sets per-coordinate physical action units; without statistics, flow matching divides actions by these scales. Supply training-only action_mean/action_std to use z-scored actions. Sampling clips physical controls after denormalization.

frameskip spaces dynamics targets, num_states sets their count, and chunk_size sets the number of consecutive predicted actions. Use forward_windows when these lengths differ. projector_norm="batch" selects the reference BatchNorm projector and positional initialization; legacy defaults retain their parameter keys and inference behavior.

Paper: https://arxiv.org/abs/2610.12818 Reference: https://github.com/MinghaoFu/lewam

Members

MemberDescription
encodeEncode (B,T,C,H,W) images, optionally appending (B,T,state_dim).
attention_maskBoolean SDPA mask: history | future queries | goal | clean | noisy.
joint_predictionReturn future latents and action velocities; actions here use normalized units.
normalize_actionsPhysical controls to training coordinates (z-score when statistics exist).
denormalize_actionsTraining coordinates to physical controls; bounds apply after conversion.
predict_futurePredict a chunk of future latents from physical-unit actions, differentiably.
predictWorldModel-compatible next-state predictions for each history prefix.
sample_actionsEuler-integrate noise → action flow; return bounded physical-unit chunks.
forwardTrain on aligned windows; action_valid masks failed demonstrations (B,K).
forward_windowsReference-aligned single-view MSE-state/flow-action training.
Source code in torch_world/models/jepa/_lewam.py
python
class LeWAM(WorldActionModel):
    """Joint latent dynamics and flow-matching action chunks (Fu et al., 2026).

    A mixture of transformers predicts future latent states from clean actions,
    and an action velocity field from noisy actions. Its grouped attention mask
    prevents clean-action and future-state leakage into the policy branch.
    Training jointly minimizes dynamics MSE, action flow matching and SIGReg.

    ``encoder`` maps ``(N,C,H,W)`` to ``(N,feature_dim or embed_dim)``. Inputs to ``forward``
    contain ``history + chunk_size`` frames and at least one fewer actions.
    Goals are separate images from the same episode. ``goal_conditioned=False``
    trains task-only behavior cloning. Optional ``remaining`` is a normalized
    remaining horizon, seen only by the action branch.

    ``state_dim`` optionally appends externally normalized measured state. That
    extension predicts state residuals, initialized to zero, and excludes state
    coordinates from SIGReg. ``action_scale`` sets per-coordinate physical action
    units; without statistics, flow matching divides actions by these scales.
    Supply training-only ``action_mean``/``action_std`` to use z-scored actions.
    Sampling clips physical controls after denormalization.

    ``frameskip`` spaces dynamics targets, ``num_states`` sets their count,
    and ``chunk_size`` sets the number of consecutive predicted actions. Use
    ``forward_windows`` when these lengths differ. ``projector_norm="batch"``
    selects the reference BatchNorm projector and positional initialization;
    legacy defaults retain their parameter keys and inference behavior.

    Paper: https://arxiv.org/abs/2610.12818
    Reference: https://github.com/MinghaoFu/lewam
    """

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        embed_dim: int = 192,
        *,
        history: int = 3,
        chunk_size: int = 8,
        dim: int = 192,
        depth: int = 4,
        num_heads: int = 4,
        mlp_dim: int = 768,
        dropout: float = 0.0,
        flow_steps: int = 8,
        goal_conditioned: bool = True,
        goal_type: str | None = None,
        state_dim: int = 0,
        action_scale=None,
        action_mean=None,
        action_std=None,
        frameskip: int = 1,
        num_states: int | None = None,
        feature_dim: int | None = None,
        projector_norm: str | None = None,
        lamb: float = 0.04,
        action_weight: float = 1.0,
        state_weight: float = 1.0,
        sigreg: SIGReg | None = None,
    ):
        super().__init__()
        if min(action_dim, embed_dim, history, chunk_size, dim, depth, num_heads, mlp_dim, flow_steps) < 1:
            raise ValueError("Model dimensions and flow_steps must be positive")
        if dim % num_heads or dim % 2 or state_dim < 0 or min(lamb, action_weight, state_weight) < 0:
            raise ValueError("Invalid attention dimensions, state_dim or loss weights")
        if not 0 <= dropout < 1:
            raise ValueError("dropout must be in [0, 1)")
        num_states = chunk_size if num_states is None else num_states
        if frameskip < 1 or num_states < 1 or num_states * frameskip > chunk_size:
            raise ValueError("chunk_size must cover num_states * frameskip")
        if projector_norm not in (None, "batch"):
            raise ValueError("projector_norm must be None or 'batch'")
        goal_type = ("terminal" if goal_conditioned else "none") if goal_type is None else goal_type
        if goal_type not in ("none", "terminal", "sampled") or (goal_type != "none") != goal_conditioned:
            raise ValueError("goal_type must agree with goal_conditioned")
        self.goal_type = goal_type
        self.frameskip, self.num_states = frameskip, num_states
        self.num_clean_actions = num_states * frameskip
        self.encoder = encoder
        self.history, self.chunk_size, self.action_dim = history, chunk_size, action_dim
        self.embed_dim, self.state_dim, self.dim = embed_dim, state_dim, dim
        self.flow_steps, self.goal_conditioned = flow_steps, goal_conditioned
        self.lamb, self.action_weight, self.state_weight = lamb, action_weight, state_weight
        latent_dim = embed_dim + state_dim
        scale = torch.ones(action_dim) if action_scale is None else torch.as_tensor(action_scale, dtype=torch.float32)
        if scale.shape != (action_dim,) or not torch.isfinite(scale).all() or (scale <= 0).any():
            raise ValueError("action_scale must contain one finite positive scale per action coordinate")
        self.register_buffer("action_scale", scale.clone())
        if (action_mean is None) != (action_std is None):
            raise ValueError("Supply both action_mean and action_std")
        for name, value in (("action_mean", action_mean), ("action_std", action_std)):
            value = None if value is None else torch.as_tensor(value, dtype=torch.float32).clone()
            if value is not None and (value.shape != (action_dim,) or not torch.isfinite(value).all()):
                raise ValueError(f"{name} must contain one finite value per action coordinate")
            if name == "action_std" and value is not None and (value <= 0).any():
                raise ValueError("action_std must be positive")
            self.register_buffer(name, value)
        layers = [nn.Linear(feature_dim or embed_dim, 2 * embed_dim)]
        if projector_norm == "batch":
            layers.append(nn.BatchNorm1d(2 * embed_dim))
        self.projector = nn.Sequential(*layers, nn.GELU(), nn.Linear(2 * embed_dim, embed_dim))
        self.history_projection, self.goal_projection = nn.Linear(latent_dim, dim), nn.Linear(latent_dim, dim)
        self.action_projection = nn.Linear(action_dim, dim)
        self.history_position = nn.Parameter(torch.randn(1, history, dim) * 0.02)
        self.state_queries = nn.Parameter(torch.randn(1, num_states, dim) * 0.02)
        self.action_position = nn.Parameter(torch.randn(1, chunk_size, dim) * 0.02)
        # Reference initialization; legacy defaults retain their checkpoint layout.
        if projector_norm == "batch":
            nn.init.zeros_(self.history_position)
            nn.init.zeros_(self.action_position)
        self.register_parameter(
            "state_position", nn.Parameter(torch.zeros(1, num_states, dim)) if projector_norm == "batch" else None
        )
        self.token_type = nn.Embedding(5, dim)
        self.time_projection, self.horizon_projection = nn.Linear(dim, dim), nn.Linear(dim, dim)
        self.blocks = nn.ModuleList([_MixtureBlock(dim, num_heads, mlp_dim, dropout) for _ in range(depth)])
        self.state_output = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, latent_dim))
        self.action_output = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, action_dim))
        if state_dim:
            with torch.no_grad():
                self.state_output[-1].weight[embed_dim:].zero_()
                self.state_output[-1].bias[embed_dim:].zero_()
        self.sigreg = sigreg or SIGReg()

    def encode(self, pixels: Tensor, states: Tensor | None = None) -> Tensor:
        """Encode ``(B,T,C,H,W)`` images, optionally appending ``(B,T,state_dim)``."""
        if pixels.ndim != 5:
            raise ValueError("pixels must have shape (B,T,C,H,W)")
        z = self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])
        if self.state_dim:
            if states is None or states.shape != (*pixels.shape[:2], self.state_dim):
                raise ValueError("Measured states must match batch, time and state_dim")
            z = torch.cat((z, states), dim=-1)
        return z

    def attention_mask(self, history: int, *, device=None) -> Tensor:
        """Boolean SDPA mask: history | future queries | goal | clean | noisy."""
        if not 1 <= history <= self.history:
            raise ValueError("Invalid history length")
        h, s, c, k, g = history, self.num_states, self.num_clean_actions, self.chunk_size, int(self.goal_conditioned)
        clean, noisy = h + s + g, h + s + g + c
        mask = torch.zeros(noisy + k, noisy + k, dtype=torch.bool, device=device)
        mask[:, :h] = True
        mask[h : h + s, h : h + s] = torch.ones(s, s, dtype=torch.bool, device=device).tril()
        for step in range(s):
            mask[h + step, clean : clean + (step + 1) * self.frameskip] = True
        if g:
            mask[h + s, h + s] = True
            mask[noisy:, h + s] = True
        mask[clean:noisy, clean:noisy] = torch.ones(c, c, dtype=torch.bool, device=device).tril()
        mask[noisy:, noisy:] = torch.ones(k, k, dtype=torch.bool, device=device).tril()
        return mask

    def joint_prediction(
        self,
        z: Tensor,
        clean_actions: Tensor,
        noisy_actions: Tensor,
        time: Tensor,
        goal: Tensor | None = None,
        remaining: Tensor | None = None,
        history_pad: Tensor | None = None,
    ) -> tuple[Tensor, Tensor]:
        """Return future latents and action velocities; actions here use normalized units.

        Exposed for leakage tests and advanced training. Clean actions never
        influence action velocities; goal/time/noisy actions never influence dynamics.
        """
        b, h, _ = z.shape
        k = self.chunk_size
        if not 1 <= h <= self.history or z.shape[-1] != self.embed_dim + self.state_dim:
            raise ValueError("Invalid latent history shape")
        if clean_actions.shape != (b, k, self.action_dim) or noisy_actions.shape != clean_actions.shape:
            raise ValueError("Expected full clean and noisy action chunks")
        if time.shape != (b,) or (remaining is not None and remaining.shape != (b,)):
            raise ValueError("time and remaining must have shape (B,)")
        history = self.history_projection(z) + self.history_position[:, -h:] + self.token_type.weight[0]
        future = self.state_queries.expand(b, -1, -1) + self.token_type.weight[1]
        if self.state_position is not None:
            future = future + self.state_position
        tokens = [history, future]
        if self.goal_conditioned:
            # Dynamics-only calls may omit the goal; its token is unreachable
            # from history, clean actions and future queries in every layer.
            goal = torch.zeros_like(z[:, -1]) if goal is None else goal
            if goal.shape != z[:, -1].shape:
                raise ValueError("Goal latent must have shape (B, latent_dim)")
            tokens.append(self.goal_projection(goal)[:, None] + self.token_type.weight[2])
        elif goal is not None:
            raise ValueError("This model is not goal-conditioned")
        clean = (
            self.action_projection(clean_actions[:, : self.num_clean_actions])
            + self.action_position[:, : self.num_clean_actions]
            + self.token_type.weight[3]
        )
        noisy = self.action_projection(noisy_actions) + self.action_position + self.token_type.weight[4]
        state_count = h + self.num_states + int(self.goal_conditioned)
        x = torch.cat((*tokens, clean, noisy), dim=1)
        condition = self.time_projection(_time_embedding(time, self.dim).to(z.dtype))
        if remaining is not None:
            condition = condition + self.horizon_projection(_time_embedding(remaining, self.dim).to(z.dtype))
        mask = self.attention_mask(h, device=z.device)
        if history_pad is not None:
            if history_pad.shape != (b, h) or history_pad.dtype != torch.bool or history_pad[:, -1].any():
                raise ValueError("history_pad must be boolean (B,H), with the current frame unpadded")
            mask = mask[None, None].expand(b, 1, -1, -1).clone()
            mask[:, :, :, :h] &= ~history_pad[:, None, None, :]
        for block in self.blocks:
            x = block(x, mask, state_count, state_count + self.num_clean_actions, condition)
        predicted = self.state_output(x[:, h : h + self.num_states])
        if self.state_dim:
            predicted = torch.cat(
                (predicted[..., : self.embed_dim], z[:, -1:, self.embed_dim :] + predicted[..., self.embed_dim :]),
                dim=-1,
            )
        return predicted, self.action_output(x[:, -k:])

    def normalize_actions(self, actions: Tensor) -> Tensor:
        """Physical controls to training coordinates (z-score when statistics exist)."""
        if self.action_mean is not None:
            return (actions - self.action_mean) / self.action_std
        return actions / self.action_scale

    def denormalize_actions(self, actions: Tensor, *, clamp: bool = False) -> Tensor:
        """Training coordinates to physical controls; bounds apply after conversion."""
        raw = actions * self.action_scale if self.action_mean is None else actions * self.action_std + self.action_mean
        return raw.maximum(-self.action_scale).minimum(self.action_scale) if clamp else raw

    def predict_future(
        self, z: Tensor, actions: Tensor, goal: Tensor | None = None, *, history_pad: Tensor | None = None
    ) -> Tensor:
        """Predict a chunk of future latents from physical-unit actions, differentiably.

        ``goal`` is accepted for the ``WorldActionModel`` interface and ignored: LeWAM's dynamics never see the goal.
        """
        if actions.shape != (z.size(0), self.chunk_size, self.action_dim):
            raise ValueError("predict_future requires a complete action chunk")
        return self.joint_prediction(
            z,
            self.normalize_actions(actions),
            torch.zeros_like(actions),
            z.new_zeros(z.size(0)),
            history_pad=history_pad,
        )[0]

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        """WorldModel-compatible next-state predictions for each history prefix."""
        if self.frameskip != 1:
            raise ValueError("predict is a one-step API; use predict_future for frameskip dynamics")
        if actions.shape != (*z.shape[:2], self.action_dim):
            raise ValueError("Actions must align with latent history")
        predictions = []
        for t in range(z.size(1)):
            chunk = F.pad(actions[:, t : t + 1], (0, 0, 0, self.chunk_size - 1))
            predictions.append(self.predict_future(z[:, max(0, t + 1 - self.history) : t + 1], chunk)[:, :1])
        return torch.cat(predictions, dim=1)

    def sample_actions(
        self,
        z: Tensor,
        goal: Tensor | None = None,
        *,
        remaining: Tensor | None = None,
        generator: torch.Generator | None = None,
        noise: Tensor | None = None,
        steps: int | None = None,
        clamp: bool = True,
        history_pad: Tensor | None = None,
    ) -> Tensor:
        """Euler-integrate noise → action flow; return bounded physical-unit chunks."""
        if self.goal_conditioned and goal is None:
            raise ValueError("Goal-conditioned action sampling requires a goal latent")
        steps = self.flow_steps if steps is None else steps
        if steps < 1:
            raise ValueError("steps must be positive")
        shape = (z.size(0), self.chunk_size, self.action_dim)
        actions = torch.randn(shape, device=z.device, dtype=z.dtype, generator=generator) if noise is None else noise
        if actions.shape != shape:
            raise ValueError("Noise must have shape (B, chunk_size, action_dim)")
        clean = torch.zeros_like(actions)
        actions = euler_sample(
            lambda x, time: self.joint_prediction(z, clean, x, time, goal, remaining, history_pad)[1], actions, steps
        )
        return self.denormalize_actions(actions, clamp=clamp)

    def _distance(self, predicted, target):
        error = (predicted - target).square()
        distance = error[..., : self.embed_dim].mean(-1)
        if self.state_dim:
            distance = distance + self.state_weight * error[..., self.embed_dim :].mean(-1)
        return distance

    def cost(self, z: Tensor, goal: Tensor) -> Tensor:
        return self._distance(z[:, -1], goal)

    def forward(
        self,
        pixels: Tensor,
        actions: Tensor,
        states: Tensor | None = None,
        *,
        goal_pixels: Tensor | None = None,
        goal_states: Tensor | None = None,
        action_valid: Tensor | None = None,
        remaining: Tensor | None = None,
        generator: torch.Generator | None = None,
    ) -> dict[str, Tensor]:
        """Train on aligned windows; action_valid masks failed demonstrations (B,K).

        Targets stay attached to the jointly trained encoder. All valid windows
        train dynamics; only action_valid entries supervise the action branch.
        An optional final padded action is ignored. Goals must be supplied
        explicitly, avoiding an implicit short-horizon/final-goal mismatch.
        """
        if self.frameskip != 1 or self.num_states != self.chunk_size:
            raise ValueError("Use forward_windows for spaced dynamics targets")
        h, k = self.history, self.chunk_size
        if pixels.size(1) != h + k or actions.shape[:2] not in ((pixels.size(0), h + k - 1), (pixels.size(0), h + k)):
            raise ValueError("Expected history + chunk_size frames and aligned actions")
        z = self.encode(pixels, states)
        goal = None
        if self.goal_conditioned:
            if goal_pixels is None:
                raise ValueError("Training requires explicit goal_pixels")
            goal = self.encode(goal_pixels[:, None], None if goal_states is None else goal_states[:, None])[:, 0]
        target = self.normalize_actions(actions[:, h - 1 : h + k - 1])
        noise = torch.randn(target.shape, device=target.device, dtype=target.dtype, generator=generator)
        time = torch.rand(z.size(0), device=z.device, dtype=z.dtype, generator=generator)
        noisy = interpolate(noise, target, time)
        predicted, velocity = self.joint_prediction(z[:, :h], target, noisy, time, goal, remaining)
        dynamics = self._distance(predicted, z[:, h:]).mean()
        error = (velocity - velocity_target(noise, target)).square().mean(-1)
        if action_valid is None:
            action_valid = torch.ones_like(error)
        if action_valid.shape != error.shape or not torch.isfinite(action_valid).all() or (action_valid < 0).any():
            raise ValueError("action_valid must be finite nonnegative weights with shape (B,K)")
        action_loss = ((error * action_valid).sum(-1) / action_valid.sum(-1).clamp_min(1)).mean()
        visual = z[..., : self.embed_dim]
        if goal is not None:
            visual = torch.cat((visual, goal[:, None, : self.embed_dim]), dim=1)
        regularizer = self.sigreg(visual.transpose(0, 1), generator=generator)
        return {
            "loss": dynamics + self.action_weight * action_loss + self.lamb * regularizer,
            "pred_loss": dynamics,
            "action_loss": action_loss,
            "sigreg_loss": regularizer,
        }

    def forward_windows(
        self,
        history_pixels: Tensor,
        future_pixels: Tensor,
        actions: Tensor,
        *,
        goal_pixels: Tensor | None = None,
        history_pad: Tensor | None = None,
        action_valid: Tensor | None = None,
        state_valid: Tensor | None = None,
        remaining: Tensor | None = None,
        generator: torch.Generator | None = None,
    ) -> dict[str, Tensor]:
        """Reference-aligned single-view MSE-state/flow-action training.

        History contains H strided frames, future contains S frames at offsets
        K,2K,...,S*K, and actions contains C consecutive physical controls from
        the current observation. True history_pad keys are excluded. Invalid
        actions are zero in normalized coordinates. Losses average valid tokens
        within each example before averaging examples, as in the reference.
        All images share one encoder/projector call; targets are not detached.
        """
        if self.state_dim:
            raise ValueError("forward_windows is the visual-only reference path")
        b = history_pixels.size(0)
        if history_pixels.shape[:2] != (b, self.history) or future_pixels.shape[:2] != (b, self.num_states):
            raise ValueError("Expected H history frames and S future frames")
        if actions.shape != (b, self.chunk_size, self.action_dim):
            raise ValueError("Expected C consecutive physical actions")
        images = [history_pixels, future_pixels]
        if self.goal_conditioned:
            if goal_pixels is None:
                raise ValueError("Training requires explicit goal_pixels")
            images.append(goal_pixels[:, None])
        elif goal_pixels is not None:
            raise ValueError("This model is not goal-conditioned")
        z = self.encode(torch.cat(images, 1))
        goal = z[:, -1] if self.goal_conditioned else None
        target = self.normalize_actions(actions)
        if action_valid is not None:
            target = target.masked_fill(~action_valid.bool()[..., None], 0)
        noise = torch.randn(target.shape, device=target.device, dtype=target.dtype, generator=generator)
        time = torch.rand(b, device=z.device, dtype=z.dtype, generator=generator)
        predicted, velocity = self.joint_prediction(
            z[:, : self.history],
            target,
            interpolate(noise, target, time),
            time,
            goal,
            remaining,
            history_pad,
        )

        def masked_mean(error, valid):
            if valid is None:
                return error.mean()
            if valid.shape != error.shape or not torch.isfinite(valid).all() or (valid < 0).any():
                raise ValueError("Validity weights must be finite, nonnegative and match token errors")
            return ((error * valid).sum(-1) / valid.sum(-1).clamp_min(1)).mean()

        dynamics = masked_mean(
            self._distance(predicted, z[:, self.history : self.history + self.num_states]), state_valid
        )
        action_loss = masked_mean((velocity - velocity_target(noise, target)).square().mean(-1), action_valid)
        # Independent projection draws for each time/goal group, matching upstream.
        regularizer = torch.stack([self.sigreg(group[None], generator=generator) for group in z.unbind(1)]).mean()
        return {
            "loss": dynamics + self.action_weight * action_loss + self.lamb * regularizer,
            "pred_loss": dynamics,
            "action_loss": action_loss,
            "sigreg_loss": regularizer,
        }

method encode ​

torch_world.models.LeWAM.encode GitHub

python
encode(pixels: Tensor, states: Tensor | None = None) -> Tensor

Encode (B,T,C,H,W) images, optionally appending (B,T,state_dim).

Source code in torch_world/models/jepa/_lewam.py
python
def encode(self, pixels: Tensor, states: Tensor | None = None) -> Tensor:
    """Encode ``(B,T,C,H,W)`` images, optionally appending ``(B,T,state_dim)``."""
    if pixels.ndim != 5:
        raise ValueError("pixels must have shape (B,T,C,H,W)")
    z = self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])
    if self.state_dim:
        if states is None or states.shape != (*pixels.shape[:2], self.state_dim):
            raise ValueError("Measured states must match batch, time and state_dim")
        z = torch.cat((z, states), dim=-1)
    return z

method attention_mask ​

torch_world.models.LeWAM.attention_mask GitHub

python
attention_mask(history: int, *, device=None) -> Tensor

Boolean SDPA mask: history | future queries | goal | clean | noisy.

Source code in torch_world/models/jepa/_lewam.py
python
def attention_mask(self, history: int, *, device=None) -> Tensor:
    """Boolean SDPA mask: history | future queries | goal | clean | noisy."""
    if not 1 <= history <= self.history:
        raise ValueError("Invalid history length")
    h, s, c, k, g = history, self.num_states, self.num_clean_actions, self.chunk_size, int(self.goal_conditioned)
    clean, noisy = h + s + g, h + s + g + c
    mask = torch.zeros(noisy + k, noisy + k, dtype=torch.bool, device=device)
    mask[:, :h] = True
    mask[h : h + s, h : h + s] = torch.ones(s, s, dtype=torch.bool, device=device).tril()
    for step in range(s):
        mask[h + step, clean : clean + (step + 1) * self.frameskip] = True
    if g:
        mask[h + s, h + s] = True
        mask[noisy:, h + s] = True
    mask[clean:noisy, clean:noisy] = torch.ones(c, c, dtype=torch.bool, device=device).tril()
    mask[noisy:, noisy:] = torch.ones(k, k, dtype=torch.bool, device=device).tril()
    return mask

method joint_prediction ​

torch_world.models.LeWAM.joint_prediction GitHub

python
joint_prediction(
    z: Tensor,
    clean_actions: Tensor,
    noisy_actions: Tensor,
    time: Tensor,
    goal: Tensor | None = None,
    remaining: Tensor | None = None,
    history_pad: Tensor | None = None,
) -> tuple[Tensor, Tensor]

Return future latents and action velocities; actions here use normalized units.

Exposed for leakage tests and advanced training. Clean actions never influence action velocities; goal/time/noisy actions never influence dynamics.

Source code in torch_world/models/jepa/_lewam.py
python
def joint_prediction(
    self,
    z: Tensor,
    clean_actions: Tensor,
    noisy_actions: Tensor,
    time: Tensor,
    goal: Tensor | None = None,
    remaining: Tensor | None = None,
    history_pad: Tensor | None = None,
) -> tuple[Tensor, Tensor]:
    """Return future latents and action velocities; actions here use normalized units.

    Exposed for leakage tests and advanced training. Clean actions never
    influence action velocities; goal/time/noisy actions never influence dynamics.
    """
    b, h, _ = z.shape
    k = self.chunk_size
    if not 1 <= h <= self.history or z.shape[-1] != self.embed_dim + self.state_dim:
        raise ValueError("Invalid latent history shape")
    if clean_actions.shape != (b, k, self.action_dim) or noisy_actions.shape != clean_actions.shape:
        raise ValueError("Expected full clean and noisy action chunks")
    if time.shape != (b,) or (remaining is not None and remaining.shape != (b,)):
        raise ValueError("time and remaining must have shape (B,)")
    history = self.history_projection(z) + self.history_position[:, -h:] + self.token_type.weight[0]
    future = self.state_queries.expand(b, -1, -1) + self.token_type.weight[1]
    if self.state_position is not None:
        future = future + self.state_position
    tokens = [history, future]
    if self.goal_conditioned:
        # Dynamics-only calls may omit the goal; its token is unreachable
        # from history, clean actions and future queries in every layer.
        goal = torch.zeros_like(z[:, -1]) if goal is None else goal
        if goal.shape != z[:, -1].shape:
            raise ValueError("Goal latent must have shape (B, latent_dim)")
        tokens.append(self.goal_projection(goal)[:, None] + self.token_type.weight[2])
    elif goal is not None:
        raise ValueError("This model is not goal-conditioned")
    clean = (
        self.action_projection(clean_actions[:, : self.num_clean_actions])
        + self.action_position[:, : self.num_clean_actions]
        + self.token_type.weight[3]
    )
    noisy = self.action_projection(noisy_actions) + self.action_position + self.token_type.weight[4]
    state_count = h + self.num_states + int(self.goal_conditioned)
    x = torch.cat((*tokens, clean, noisy), dim=1)
    condition = self.time_projection(_time_embedding(time, self.dim).to(z.dtype))
    if remaining is not None:
        condition = condition + self.horizon_projection(_time_embedding(remaining, self.dim).to(z.dtype))
    mask = self.attention_mask(h, device=z.device)
    if history_pad is not None:
        if history_pad.shape != (b, h) or history_pad.dtype != torch.bool or history_pad[:, -1].any():
            raise ValueError("history_pad must be boolean (B,H), with the current frame unpadded")
        mask = mask[None, None].expand(b, 1, -1, -1).clone()
        mask[:, :, :, :h] &= ~history_pad[:, None, None, :]
    for block in self.blocks:
        x = block(x, mask, state_count, state_count + self.num_clean_actions, condition)
    predicted = self.state_output(x[:, h : h + self.num_states])
    if self.state_dim:
        predicted = torch.cat(
            (predicted[..., : self.embed_dim], z[:, -1:, self.embed_dim :] + predicted[..., self.embed_dim :]),
            dim=-1,
        )
    return predicted, self.action_output(x[:, -k:])

method normalize_actions ​

torch_world.models.LeWAM.normalize_actions GitHub

python
normalize_actions(actions: Tensor) -> Tensor

Physical controls to training coordinates (z-score when statistics exist).

Source code in torch_world/models/jepa/_lewam.py
python
def normalize_actions(self, actions: Tensor) -> Tensor:
    """Physical controls to training coordinates (z-score when statistics exist)."""
    if self.action_mean is not None:
        return (actions - self.action_mean) / self.action_std
    return actions / self.action_scale

method denormalize_actions ​

torch_world.models.LeWAM.denormalize_actions GitHub

python
denormalize_actions(actions: Tensor, *, clamp: bool = False) -> Tensor

Training coordinates to physical controls; bounds apply after conversion.

Source code in torch_world/models/jepa/_lewam.py
python
def denormalize_actions(self, actions: Tensor, *, clamp: bool = False) -> Tensor:
    """Training coordinates to physical controls; bounds apply after conversion."""
    raw = actions * self.action_scale if self.action_mean is None else actions * self.action_std + self.action_mean
    return raw.maximum(-self.action_scale).minimum(self.action_scale) if clamp else raw

method predict_future ​

torch_world.models.LeWAM.predict_future GitHub

python
predict_future(
    z: Tensor,
    actions: Tensor,
    goal: Tensor | None = None,
    *,
    history_pad: Tensor | None = None,
) -> Tensor

Predict a chunk of future latents from physical-unit actions, differentiably.

goal is accepted for the WorldActionModel interface and ignored: LeWAM's dynamics never see the goal.

Source code in torch_world/models/jepa/_lewam.py
python
def predict_future(
    self, z: Tensor, actions: Tensor, goal: Tensor | None = None, *, history_pad: Tensor | None = None
) -> Tensor:
    """Predict a chunk of future latents from physical-unit actions, differentiably.

    ``goal`` is accepted for the ``WorldActionModel`` interface and ignored: LeWAM's dynamics never see the goal.
    """
    if actions.shape != (z.size(0), self.chunk_size, self.action_dim):
        raise ValueError("predict_future requires a complete action chunk")
    return self.joint_prediction(
        z,
        self.normalize_actions(actions),
        torch.zeros_like(actions),
        z.new_zeros(z.size(0)),
        history_pad=history_pad,
    )[0]

method predict ​

torch_world.models.LeWAM.predict GitHub

python
predict(z: Tensor, actions: Tensor) -> Tensor

WorldModel-compatible next-state predictions for each history prefix.

Source code in torch_world/models/jepa/_lewam.py
python
def predict(self, z: Tensor, actions: Tensor) -> Tensor:
    """WorldModel-compatible next-state predictions for each history prefix."""
    if self.frameskip != 1:
        raise ValueError("predict is a one-step API; use predict_future for frameskip dynamics")
    if actions.shape != (*z.shape[:2], self.action_dim):
        raise ValueError("Actions must align with latent history")
    predictions = []
    for t in range(z.size(1)):
        chunk = F.pad(actions[:, t : t + 1], (0, 0, 0, self.chunk_size - 1))
        predictions.append(self.predict_future(z[:, max(0, t + 1 - self.history) : t + 1], chunk)[:, :1])
    return torch.cat(predictions, dim=1)

method sample_actions ​

torch_world.models.LeWAM.sample_actions GitHub

python
sample_actions(
    z: Tensor,
    goal: Tensor | None = None,
    *,
    remaining: Tensor | None = None,
    generator: torch.Generator | None = None,
    noise: Tensor | None = None,
    steps: int | None = None,
    clamp: bool = True,
    history_pad: Tensor | None = None,
) -> Tensor

Euler-integrate noise → action flow; return bounded physical-unit chunks.

Source code in torch_world/models/jepa/_lewam.py
python
def sample_actions(
    self,
    z: Tensor,
    goal: Tensor | None = None,
    *,
    remaining: Tensor | None = None,
    generator: torch.Generator | None = None,
    noise: Tensor | None = None,
    steps: int | None = None,
    clamp: bool = True,
    history_pad: Tensor | None = None,
) -> Tensor:
    """Euler-integrate noise → action flow; return bounded physical-unit chunks."""
    if self.goal_conditioned and goal is None:
        raise ValueError("Goal-conditioned action sampling requires a goal latent")
    steps = self.flow_steps if steps is None else steps
    if steps < 1:
        raise ValueError("steps must be positive")
    shape = (z.size(0), self.chunk_size, self.action_dim)
    actions = torch.randn(shape, device=z.device, dtype=z.dtype, generator=generator) if noise is None else noise
    if actions.shape != shape:
        raise ValueError("Noise must have shape (B, chunk_size, action_dim)")
    clean = torch.zeros_like(actions)
    actions = euler_sample(
        lambda x, time: self.joint_prediction(z, clean, x, time, goal, remaining, history_pad)[1], actions, steps
    )
    return self.denormalize_actions(actions, clamp=clamp)

method forward ​

torch_world.models.LeWAM.forward GitHub

python
forward(
    pixels: Tensor,
    actions: Tensor,
    states: Tensor | None = None,
    *,
    goal_pixels: Tensor | None = None,
    goal_states: Tensor | None = None,
    action_valid: Tensor | None = None,
    remaining: Tensor | None = None,
    generator: torch.Generator | None = None,
) -> dict[str, Tensor]

Train on aligned windows; action_valid masks failed demonstrations (B,K).

Targets stay attached to the jointly trained encoder. All valid windows train dynamics; only action_valid entries supervise the action branch. An optional final padded action is ignored. Goals must be supplied explicitly, avoiding an implicit short-horizon/final-goal mismatch.

Source code in torch_world/models/jepa/_lewam.py
python
def forward(
    self,
    pixels: Tensor,
    actions: Tensor,
    states: Tensor | None = None,
    *,
    goal_pixels: Tensor | None = None,
    goal_states: Tensor | None = None,
    action_valid: Tensor | None = None,
    remaining: Tensor | None = None,
    generator: torch.Generator | None = None,
) -> dict[str, Tensor]:
    """Train on aligned windows; action_valid masks failed demonstrations (B,K).

    Targets stay attached to the jointly trained encoder. All valid windows
    train dynamics; only action_valid entries supervise the action branch.
    An optional final padded action is ignored. Goals must be supplied
    explicitly, avoiding an implicit short-horizon/final-goal mismatch.
    """
    if self.frameskip != 1 or self.num_states != self.chunk_size:
        raise ValueError("Use forward_windows for spaced dynamics targets")
    h, k = self.history, self.chunk_size
    if pixels.size(1) != h + k or actions.shape[:2] not in ((pixels.size(0), h + k - 1), (pixels.size(0), h + k)):
        raise ValueError("Expected history + chunk_size frames and aligned actions")
    z = self.encode(pixels, states)
    goal = None
    if self.goal_conditioned:
        if goal_pixels is None:
            raise ValueError("Training requires explicit goal_pixels")
        goal = self.encode(goal_pixels[:, None], None if goal_states is None else goal_states[:, None])[:, 0]
    target = self.normalize_actions(actions[:, h - 1 : h + k - 1])
    noise = torch.randn(target.shape, device=target.device, dtype=target.dtype, generator=generator)
    time = torch.rand(z.size(0), device=z.device, dtype=z.dtype, generator=generator)
    noisy = interpolate(noise, target, time)
    predicted, velocity = self.joint_prediction(z[:, :h], target, noisy, time, goal, remaining)
    dynamics = self._distance(predicted, z[:, h:]).mean()
    error = (velocity - velocity_target(noise, target)).square().mean(-1)
    if action_valid is None:
        action_valid = torch.ones_like(error)
    if action_valid.shape != error.shape or not torch.isfinite(action_valid).all() or (action_valid < 0).any():
        raise ValueError("action_valid must be finite nonnegative weights with shape (B,K)")
    action_loss = ((error * action_valid).sum(-1) / action_valid.sum(-1).clamp_min(1)).mean()
    visual = z[..., : self.embed_dim]
    if goal is not None:
        visual = torch.cat((visual, goal[:, None, : self.embed_dim]), dim=1)
    regularizer = self.sigreg(visual.transpose(0, 1), generator=generator)
    return {
        "loss": dynamics + self.action_weight * action_loss + self.lamb * regularizer,
        "pred_loss": dynamics,
        "action_loss": action_loss,
        "sigreg_loss": regularizer,
    }

method forward_windows ​

torch_world.models.LeWAM.forward_windows GitHub

python
forward_windows(
    history_pixels: Tensor,
    future_pixels: Tensor,
    actions: Tensor,
    *,
    goal_pixels: Tensor | None = None,
    history_pad: Tensor | None = None,
    action_valid: Tensor | None = None,
    state_valid: Tensor | None = None,
    remaining: Tensor | None = None,
    generator: torch.Generator | None = None,
) -> dict[str, Tensor]

Reference-aligned single-view MSE-state/flow-action training.

History contains H strided frames, future contains S frames at offsets K,2K,...,S*K, and actions contains C consecutive physical controls from the current observation. True history_pad keys are excluded. Invalid actions are zero in normalized coordinates. Losses average valid tokens within each example before averaging examples, as in the reference. All images share one encoder/projector call; targets are not detached.

Source code in torch_world/models/jepa/_lewam.py
python
def forward_windows(
    self,
    history_pixels: Tensor,
    future_pixels: Tensor,
    actions: Tensor,
    *,
    goal_pixels: Tensor | None = None,
    history_pad: Tensor | None = None,
    action_valid: Tensor | None = None,
    state_valid: Tensor | None = None,
    remaining: Tensor | None = None,
    generator: torch.Generator | None = None,
) -> dict[str, Tensor]:
    """Reference-aligned single-view MSE-state/flow-action training.

    History contains H strided frames, future contains S frames at offsets
    K,2K,...,S*K, and actions contains C consecutive physical controls from
    the current observation. True history_pad keys are excluded. Invalid
    actions are zero in normalized coordinates. Losses average valid tokens
    within each example before averaging examples, as in the reference.
    All images share one encoder/projector call; targets are not detached.
    """
    if self.state_dim:
        raise ValueError("forward_windows is the visual-only reference path")
    b = history_pixels.size(0)
    if history_pixels.shape[:2] != (b, self.history) or future_pixels.shape[:2] != (b, self.num_states):
        raise ValueError("Expected H history frames and S future frames")
    if actions.shape != (b, self.chunk_size, self.action_dim):
        raise ValueError("Expected C consecutive physical actions")
    images = [history_pixels, future_pixels]
    if self.goal_conditioned:
        if goal_pixels is None:
            raise ValueError("Training requires explicit goal_pixels")
        images.append(goal_pixels[:, None])
    elif goal_pixels is not None:
        raise ValueError("This model is not goal-conditioned")
    z = self.encode(torch.cat(images, 1))
    goal = z[:, -1] if self.goal_conditioned else None
    target = self.normalize_actions(actions)
    if action_valid is not None:
        target = target.masked_fill(~action_valid.bool()[..., None], 0)
    noise = torch.randn(target.shape, device=target.device, dtype=target.dtype, generator=generator)
    time = torch.rand(b, device=z.device, dtype=z.dtype, generator=generator)
    predicted, velocity = self.joint_prediction(
        z[:, : self.history],
        target,
        interpolate(noise, target, time),
        time,
        goal,
        remaining,
        history_pad,
    )

    def masked_mean(error, valid):
        if valid is None:
            return error.mean()
        if valid.shape != error.shape or not torch.isfinite(valid).all() or (valid < 0).any():
            raise ValueError("Validity weights must be finite, nonnegative and match token errors")
        return ((error * valid).sum(-1) / valid.sum(-1).clamp_min(1)).mean()

    dynamics = masked_mean(
        self._distance(predicted, z[:, self.history : self.history + self.num_states]), state_valid
    )
    action_loss = masked_mean((velocity - velocity_target(noise, target)).square().mean(-1), action_valid)
    # Independent projection draws for each time/goal group, matching upstream.
    regularizer = torch.stack([self.sigreg(group[None], generator=generator) for group in z.unbind(1)]).mean()
    return {
        "loss": dynamics + self.action_weight * action_loss + self.lamb * regularizer,
        "pred_loss": dynamics,
        "action_loss": action_loss,
        "sigreg_loss": regularizer,
    }

class LeWM ​

torch_world.models.LeWM GitHub

python
LeWM(
    encoder: nn.Module,
    action_dim: int,
    embed_dim: int = 192,
    history: int = 3,
    depth: int = 6,
    num_heads: int = 16,
    head_dim: int = 64,
    mlp_dim: int = 2048,
    proj_dim: int = 2048,
    dropout: float = 0.1,
    lamb: float = 0.09,
    sigreg: SIGReg | None = None,
)

LeWorldModel: an end-to-end JEPA world model trained from pixels with two terms, next-embedding MSE and SIGReg.

Each frame is encoded to one embedding (the encoder's CLS token) and projected. A causal transformer, conditioned on action embeddings through adaLN-zero, predicts the next embedding from the last history frames. There is no EMA target and no stop-gradient: loss = mse + lamb * sigreg.

Maes et al., "LeWorldModel: Stable End-to-End Joint-Embedding Predictive Architecture from Pixels", 2026. Paper: https://arxiv.org/abs/2603.19312 Code: https://github.com/lucas-maes/le-wm

Parameters

NameTypeDescriptionDefault
encodernn.Modulemodule mapping images (N, C, H, W) to embeddings (N, embed_dim) (ViT-tiny CLS in the paper).required
action_dimintdimension of one action, times the frameskip when actions are stacked.required

Members

MemberDescription
encode(B, T, C, H, W) to (B, T, embed_dim).
forwardpixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim).
Source code in torch_world/models/jepa/_lewm.py
python
class LeWM(WorldModel):
    """LeWorldModel: an end-to-end JEPA world model trained from pixels with two terms, next-embedding MSE and SIGReg.

    Each frame is encoded to one embedding (the encoder's CLS token) and projected. A causal transformer, conditioned
    on action embeddings through adaLN-zero, predicts the next embedding from the last ``history`` frames. There is no
    EMA target and no stop-gradient: ``loss = mse + lamb * sigreg``.

    Maes et al., "LeWorldModel: Stable End-to-End Joint-Embedding Predictive Architecture from Pixels", 2026.
    Paper: https://arxiv.org/abs/2603.19312
    Code: https://github.com/lucas-maes/le-wm

    Args:
        encoder: module mapping images ``(N, C, H, W)`` to embeddings ``(N, embed_dim)`` (ViT-tiny CLS in the paper).
        action_dim: dimension of one action, times the frameskip when actions are stacked.
    """

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        embed_dim: int = 192,
        history: int = 3,
        depth: int = 6,
        num_heads: int = 16,
        head_dim: int = 64,
        mlp_dim: int = 2048,
        proj_dim: int = 2048,
        dropout: float = 0.1,
        lamb: float = 0.09,
        sigreg: SIGReg | None = None,
    ):
        super().__init__()
        self.history = history
        self.lamb = lamb
        self.encoder = encoder
        self.projector = MLP([embed_dim, proj_dim, embed_dim], norm=nn.BatchNorm1d)
        self.action_encoder = nn.Sequential(
            nn.Linear(action_dim, action_dim), MLP([action_dim, 4 * embed_dim, embed_dim], act=nn.SiLU)
        )
        self.pos_embed = nn.Parameter(torch.randn(1, history, embed_dim))
        self.predictor = Transformer(
            embed_dim, depth, num_heads, conditional=True, mlp_dim=mlp_dim, head_dim=head_dim, dropout=dropout
        )
        self.pred_proj = MLP([embed_dim, proj_dim, embed_dim], norm=nn.BatchNorm1d)
        self.sigreg = sigreg or SIGReg()

    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
        return self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        T = z.size(1)
        h = self.predictor(z + self.pos_embed[:, :T], self.action_encoder(actions), is_causal=True)
        return self.pred_proj(h.flatten(0, 1)).unflatten(0, (z.size(0), T))

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``."""
        z = self.encode(pixels)
        pred = self.predict(z[:, : self.history], actions[:, : self.history])
        mse = (pred - z[:, 1 : self.history + 1]).square().mean()
        sigreg = self.sigreg(z.transpose(0, 1))
        return {"loss": mse + self.lamb * sigreg, "pred_loss": mse, "sigreg_loss": sigreg}

method encode ​

torch_world.models.LeWM.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to (B, T, embed_dim).

Source code in torch_world/models/jepa/_lewm.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
    return self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

method forward ​

torch_world.models.LeWM.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim).

Source code in torch_world/models/jepa/_lewm.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``."""
    z = self.encode(pixels)
    pred = self.predict(z[:, : self.history], actions[:, : self.history])
    mse = (pred - z[:, 1 : self.history + 1]).square().mean()
    sigreg = self.sigreg(z.transpose(0, 1))
    return {"loss": mse + self.lamb * sigreg, "pred_loss": mse, "sigreg_loss": sigreg}

class PLDM ​

torch_world.models.PLDM GitHub

python
PLDM(
    encoder: nn.Module,
    action_dim: int,
    latent_dim: int = 128,
    idm_dim: int = 512,
    var_coeff: float = 4.0,
    cov_coeff: float = 6.9,
    smooth_coeff: float = 0.75,
    idm_coeff: float = 1.0,
    std_margin: float = 1.0,
)

PLDM: a JEPA latent dynamics model trained reward-free, then used to plan toward goal images.

Each frame is encoded to one latent, normalized by a LayerNorm. A GRU whose hidden state is the latent predicts the next latent from the current one and the action, through the same LayerNorm. During training it is unrolled open loop from the first frame over the whole window, and five terms keep the latents informative:

loss = pred + var_coeff * var + cov_coeff * cov + smooth_coeff * smooth + idm_coeff * idm

pred is the MSE of the multi-step predictions, var and cov are VICReg's variance hinge and covariance penalty over the batch at every step, smooth pulls consecutive latents together and idm is an inverse dynamics MLP regressing a_t from (z_t, z_{t+1}). Planning minimizes the latent distance to the goal along the imagined path.

Sobal et al., "Learning from Reward-Free Offline Data: A Case for Planning with Latent Dynamics Models", 2025. Paper: https://arxiv.org/abs/2502.14819 Code: https://github.com/vladisai/PLDM

Parameters

NameTypeDescriptionDefault
encodernn.Modulemodule mapping images (N, C, H, W) to latents (N, latent_dim), such as PLDMEncoder.required
action_dimintdimension of one action.required
var_coeff, cov_coeff, smooth_coeff, idm_coeffloss weights; the defaults are the reference's Two-Rooms ones.required

Members

MemberDescription
encode(B, T, C, H, W) to (B, T, latent_dim).
stepOne step of the dynamics: (N, latent_dim) and (N, action_dim) to the next latent.
rolloutUnroll from the last context latent z[:, -1] with actions[:, T0 - 1:]; returns T + 1 latents.
forwardpixels (B, T + 1, C, H, W) and actions (B, T + 1, action_dim); the last action is unused.
Source code in torch_world/models/jepa/_pldm.py
python
class PLDM(WorldModel):
    """PLDM: a JEPA latent dynamics model trained reward-free, then used to plan toward goal images.

    Each frame is encoded to one latent, normalized by a LayerNorm. A GRU whose hidden state is the latent predicts
    the next latent from the current one and the action, through the same LayerNorm. During training it is unrolled
    open loop from the first frame over the whole window, and five terms keep the latents informative:

    ``loss = pred + var_coeff * var + cov_coeff * cov + smooth_coeff * smooth + idm_coeff * idm``

    ``pred`` is the MSE of the multi-step predictions, ``var`` and ``cov`` are VICReg's variance hinge and covariance
    penalty over the batch at every step, ``smooth`` pulls consecutive latents together and ``idm`` is an inverse
    dynamics MLP regressing ``a_t`` from ``(z_t, z_{t+1})``. Planning minimizes the latent distance to the goal along
    the imagined path.

    Sobal et al., "Learning from Reward-Free Offline Data: A Case for Planning with Latent Dynamics Models", 2025.
    Paper: https://arxiv.org/abs/2502.14819
    Code: https://github.com/vladisai/PLDM

    Args:
        encoder: module mapping images ``(N, C, H, W)`` to latents ``(N, latent_dim)``, such as ``PLDMEncoder``.
        action_dim: dimension of one action.
        var_coeff, cov_coeff, smooth_coeff, idm_coeff: loss weights; the defaults are the reference's Two-Rooms ones.
    """

    history = 1

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        latent_dim: int = 128,
        idm_dim: int = 512,
        var_coeff: float = 4.0,
        cov_coeff: float = 6.9,
        smooth_coeff: float = 0.75,
        idm_coeff: float = 1.0,
        std_margin: float = 1.0,
    ):
        super().__init__()
        self.encoder = encoder
        self.norm = nn.LayerNorm(latent_dim)
        self.predictor = nn.GRUCell(action_dim, latent_dim)
        self.idm = MLP([2 * latent_dim, idm_dim, action_dim], act=nn.ReLU)
        self.var_coeff, self.cov_coeff, self.std_margin = var_coeff, cov_coeff, std_margin
        self.smooth_coeff, self.idm_coeff = smooth_coeff, idm_coeff

    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to ``(B, T, latent_dim)``."""
        return self.norm(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

    def step(self, z: Tensor, action: Tensor) -> Tensor:
        """One step of the dynamics: ``(N, latent_dim)`` and ``(N, action_dim)`` to the next latent."""
        return self.norm(self.predictor(action, z))

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        return self.step(z.flatten(0, 1), actions.flatten(0, 1)).unflatten(0, z.shape[:2])

    def rollout(self, z: Tensor, actions: Tensor) -> Tensor:
        """Unroll from the last context latent ``z[:, -1]`` with ``actions[:, T0 - 1:]``; returns ``T + 1`` latents."""
        out = list(z.unbind(1))
        for t in range(z.size(1) - 1, actions.size(1)):
            out.append(self.step(out[-1], actions[:, t]))
        return torch.stack(out, 1)

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, T + 1, C, H, W)`` and ``actions`` ``(B, T + 1, action_dim)``; the last action is unused."""
        z = self.encode(pixels)
        T, D = z.size(1) - 1, z.size(2)
        pred = self.rollout(z[:, :1], actions[:, :T])
        pred_loss = (pred[:, 1:] - z[:, 1:]).square().mean()

        zt = z.transpose(0, 1)
        zt = zt - zt.mean(1, keepdim=True)
        var_loss = (self.std_margin - (zt.var(1) + 1e-4).sqrt()).relu().mean()
        cov = zt.transpose(1, 2) @ zt / (zt.size(1) - 1)
        off_diagonal = cov.square().sum((1, 2)) - cov.diagonal(dim1=1, dim2=2).square().sum(1)
        cov_loss = (off_diagonal / (D * (D - 1))).mean()

        smooth_loss = (z[:, 1:] - z[:, :-1]).square().mean()
        idm_loss = (self.idm(torch.cat([z[:, :-1], z[:, 1:]], -1)) - actions[:, :T]).square().mean()

        loss = (
            pred_loss
            + self.var_coeff * var_loss
            + self.cov_coeff * cov_loss
            + self.smooth_coeff * smooth_loss
            + self.idm_coeff * idm_loss
        )
        return {
            "loss": loss,
            "pred_loss": pred_loss,
            "var_loss": var_loss,
            "cov_loss": cov_loss,
            "smooth_loss": smooth_loss,
            "idm_loss": idm_loss,
        }

method encode ​

torch_world.models.PLDM.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to (B, T, latent_dim).

Source code in torch_world/models/jepa/_pldm.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to ``(B, T, latent_dim)``."""
    return self.norm(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

method step ​

torch_world.models.PLDM.step GitHub

python
step(z: Tensor, action: Tensor) -> Tensor

One step of the dynamics: (N, latent_dim) and (N, action_dim) to the next latent.

Source code in torch_world/models/jepa/_pldm.py
python
def step(self, z: Tensor, action: Tensor) -> Tensor:
    """One step of the dynamics: ``(N, latent_dim)`` and ``(N, action_dim)`` to the next latent."""
    return self.norm(self.predictor(action, z))

method rollout ​

torch_world.models.PLDM.rollout GitHub

python
rollout(z: Tensor, actions: Tensor) -> Tensor

Unroll from the last context latent z[:, -1] with actions[:, T0 - 1:]; returns T + 1 latents.

Source code in torch_world/models/jepa/_pldm.py
python
def rollout(self, z: Tensor, actions: Tensor) -> Tensor:
    """Unroll from the last context latent ``z[:, -1]`` with ``actions[:, T0 - 1:]``; returns ``T + 1`` latents."""
    out = list(z.unbind(1))
    for t in range(z.size(1) - 1, actions.size(1)):
        out.append(self.step(out[-1], actions[:, t]))
    return torch.stack(out, 1)

method forward ​

torch_world.models.PLDM.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, T + 1, C, H, W) and actions (B, T + 1, action_dim); the last action is unused.

Source code in torch_world/models/jepa/_pldm.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, T + 1, C, H, W)`` and ``actions`` ``(B, T + 1, action_dim)``; the last action is unused."""
    z = self.encode(pixels)
    T, D = z.size(1) - 1, z.size(2)
    pred = self.rollout(z[:, :1], actions[:, :T])
    pred_loss = (pred[:, 1:] - z[:, 1:]).square().mean()

    zt = z.transpose(0, 1)
    zt = zt - zt.mean(1, keepdim=True)
    var_loss = (self.std_margin - (zt.var(1) + 1e-4).sqrt()).relu().mean()
    cov = zt.transpose(1, 2) @ zt / (zt.size(1) - 1)
    off_diagonal = cov.square().sum((1, 2)) - cov.diagonal(dim1=1, dim2=2).square().sum(1)
    cov_loss = (off_diagonal / (D * (D - 1))).mean()

    smooth_loss = (z[:, 1:] - z[:, :-1]).square().mean()
    idm_loss = (self.idm(torch.cat([z[:, :-1], z[:, 1:]], -1)) - actions[:, :T]).square().mean()

    loss = (
        pred_loss
        + self.var_coeff * var_loss
        + self.cov_coeff * cov_loss
        + self.smooth_coeff * smooth_loss
        + self.idm_coeff * idm_loss
    )
    return {
        "loss": loss,
        "pred_loss": pred_loss,
        "var_loss": var_loss,
        "cov_loss": cov_loss,
        "smooth_loss": smooth_loss,
        "idm_loss": idm_loss,
    }

class PLDMEncoder ​

torch_world.models.PLDMEncoder GitHub

python
PLDMEncoder(
    img_size: int,
    latent_dim: int = 128,
    in_channels: int = 3,
    channels: tuple[int, ...] = (16, 32, 32),
)

A small IMPALA-style encoder: (N, C, H, W) to (N, latent_dim).

Each stage is a convolution, a stride-2 max pool and two residual blocks, as in the IMPALA encoder that PLDM takes from OGBench, followed by a linear layer to latent_dim.

Source code in torch_world/models/jepa/_pldm.py
python
class PLDMEncoder(nn.Sequential):
    """A small IMPALA-style encoder: ``(N, C, H, W)`` to ``(N, latent_dim)``.

    Each stage is a convolution, a stride-2 max pool and two residual blocks, as in the IMPALA encoder that PLDM
    takes from OGBench, followed by a linear layer to ``latent_dim``.
    """

    def __init__(
        self, img_size: int, latent_dim: int = 128, in_channels: int = 3, channels: tuple[int, ...] = (16, 32, 32)
    ):
        layers, c = [], in_channels
        for out in channels:
            layers += [nn.Conv2d(c, out, 3, padding=1), nn.MaxPool2d(3, 2, 1), ResidualBlock(out), ResidualBlock(out)]
            c, img_size = out, (img_size + 1) // 2
        super().__init__(*layers, nn.ReLU(), nn.Flatten(), nn.Linear(c * img_size**2, latent_dim))

class LpWM ​

torch_world.models.LpWM GitHub

python
LpWM(
    encoder: nn.Module,
    action_dim: int,
    embed_dim: int = 192,
    history: int = 3,
    depth: int = 6,
    num_heads: int = 16,
    head_dim: int = 64,
    mlp_dim: int = 2048,
    proj_dim: int = 2048,
    dropout: float = 0.1,
    lamb: float = 10.0,
    rdmreg: RDMReg | None = None,
)

LpWM: a LeWM-style JEPA world model whose latents are non-negative and sparse, predicted under actions.

Each frame is encoded to one embedding (the encoder's CLS token), projected and passed through a RepReLU link, so codes are exactly zero on most units. A causal transformer, conditioned on action embeddings through adaLN-zero, predicts the next code from the last history frames, through the same link. RDMReg pulls the codes of each timestep toward a rectified Laplace, which prevents collapse and sets the sparsity: loss = mse + lamb * rdmreg. Which units are active encodes the discrete regime (for example the room), their magnitudes the continuous state within it. Planning minimizes the distance to the goal code (CEM).

Kuang et al., "LpWM: A Case for Sparse Representations in World Models", 2026. Paper: https://arxiv.org/abs/2608.22764 Code: https://github.com/YilunKuang/lpworldmodel

Parameters

NameTypeDescriptionDefault
encodernn.Modulemodule mapping images (N, C, H, W) to embeddings (N, embed_dim) (ViT-tiny CLS in the paper).required
action_dimintdimension of one action, times the frameskip when actions are stacked.required

Members

MemberDescription
encode(B, T, C, H, W) to non-negative sparse codes (B, T, embed_dim).
forwardpixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim).
Source code in torch_world/models/jepa/_lpwm.py
python
class LpWM(WorldModel):
    """LpWM: a LeWM-style JEPA world model whose latents are non-negative and sparse, predicted under actions.

    Each frame is encoded to one embedding (the encoder's CLS token), projected and passed through a RepReLU link, so
    codes are exactly zero on most units. A causal transformer, conditioned on action embeddings through adaLN-zero,
    predicts the next code from the last ``history`` frames, through the same link. RDMReg pulls the codes of each
    timestep toward a rectified Laplace, which prevents collapse and sets the sparsity:
    ``loss = mse + lamb * rdmreg``. Which units are active encodes the discrete regime (for example the room), their
    magnitudes the continuous state within it. Planning minimizes the distance to the goal code (CEM).

    Kuang et al., "LpWM: A Case for Sparse Representations in World Models", 2026.
    Paper: https://arxiv.org/abs/2608.22764
    Code: https://github.com/YilunKuang/lpworldmodel

    Args:
        encoder: module mapping images ``(N, C, H, W)`` to embeddings ``(N, embed_dim)`` (ViT-tiny CLS in the paper).
        action_dim: dimension of one action, times the frameskip when actions are stacked.
    """

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        embed_dim: int = 192,
        history: int = 3,
        depth: int = 6,
        num_heads: int = 16,
        head_dim: int = 64,
        mlp_dim: int = 2048,
        proj_dim: int = 2048,
        dropout: float = 0.1,
        lamb: float = 10.0,
        rdmreg: RDMReg | None = None,
    ):
        super().__init__()
        self.history = history
        self.lamb = lamb
        self.encoder = encoder
        self.projector = nn.Sequential(MLP([embed_dim, proj_dim, embed_dim], norm=nn.BatchNorm1d), RepReLU())
        self.action_encoder = nn.Sequential(
            nn.Linear(action_dim, action_dim), MLP([action_dim, 4 * embed_dim, embed_dim], act=nn.SiLU)
        )
        self.pos_embed = nn.Parameter(torch.randn(1, history, embed_dim))
        self.predictor = Transformer(
            embed_dim, depth, num_heads, conditional=True, mlp_dim=mlp_dim, head_dim=head_dim, dropout=dropout
        )
        self.pred_proj = nn.Sequential(MLP([embed_dim, proj_dim, embed_dim], norm=nn.BatchNorm1d), RepReLU())
        self.rdmreg = rdmreg or RDMReg()

    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to non-negative sparse codes ``(B, T, embed_dim)``."""
        return self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        T = z.size(1)
        h = self.predictor(z + self.pos_embed[:, :T], self.action_encoder(actions), is_causal=True)
        return self.pred_proj(h.flatten(0, 1)).unflatten(0, (z.size(0), T))

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``."""
        z = self.encode(pixels)
        pred = self.predict(z[:, : self.history], actions[:, : self.history])
        mse = (pred - z[:, 1 : self.history + 1]).square().mean()
        rdmreg = self.rdmreg(z)
        return {"loss": mse + self.lamb * rdmreg, "pred_loss": mse, "rdmreg_loss": rdmreg}

method encode ​

torch_world.models.LpWM.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to non-negative sparse codes (B, T, embed_dim).

Source code in torch_world/models/jepa/_lpwm.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to non-negative sparse codes ``(B, T, embed_dim)``."""
    return self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

method forward ​

torch_world.models.LpWM.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim).

Source code in torch_world/models/jepa/_lpwm.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``."""
    z = self.encode(pixels)
    pred = self.predict(z[:, : self.history], actions[:, : self.history])
    mse = (pred - z[:, 1 : self.history + 1]).square().mean()
    rdmreg = self.rdmreg(z)
    return {"loss": mse + self.lamb * rdmreg, "pred_loss": mse, "rdmreg_loss": rdmreg}

class FlowJEPA ​

torch_world.models.FlowJEPA GitHub

python
FlowJEPA(
    encoder: nn.Module,
    action_dim: int,
    embed_dim: int = 192,
    num_preds: int = 5,
    depth: int = 6,
    num_heads: int = 16,
    head_dim: int = 64,
    mlp_dim: int = 2048,
    proj_dim: int = 2048,
    dropout: float = 0.1,
    lamb: float = 0.1,
    steps: int = 8,
    source: str = "noise",
    source_std: float = 1.0,
    causal: bool = False,
    sigreg: SIGReg | None = None,
)

Flow-JEPA (F-JEPA): a LeWM-style JEPA world model whose predictor samples whole future trajectories by flow matching.

Each frame is encoded to one embedding (the encoder's CLS token) and projected, as in LeWM. From the current embedding z_t and num_preds actions, a transformer predicts the velocity that transports Gaussian source latents Z_0 to the future embeddings Z = [z_{t+1}, ..., z_{t+num_preds}], all at once. The flow time tau conditions every block through adaLN-zero; future token i sees z_t, the actions up to a_{t+i} and the other future tokens (all of them, or the earlier ones when causal). Training regresses the straight path's velocity, end to end with SIGReg on the embeddings:

loss = || v(Z_tau, tau, z_t, a) - (Z - Z_0) ||^2 + lamb * sigreg, with Z_tau = (1 - tau) Z_0 + tau Z.

Z_0 is source_std * N(0, I), centered on z_t when source="current". A prediction integrates the flow from fresh noise in steps Euler steps, so predict and rollout draw one sample of the future, and sample draws several. Planning scores each candidate by one sampled rollout, as the reference does.

Huo, Luo and Song, "Flow-JEPA: Robust Latent Dynamics for JEPA World Models via Flow Matching", 2026. Paper: https://arxiv.org/abs/2608.29029 Code: https://github.com/HuoYanchen/Flow-JEPA

Parameters

NameTypeDescriptionDefault
encodernn.Modulemodule mapping images (N, C, H, W) to embeddings (N, embed_dim) (ViT-tiny CLS in the paper).required
action_dimintdimension of one action, times the frameskip when actions are stacked.required
num_predsintfuture embeddings predicted jointly in training (h = 5 in the paper).5

Members

MemberDescription
encode(B, T, C, H, W) to (B, T, embed_dim).
maskBoolean attention mask over ``[z_t, a_t ..
velocityVelocity (B, P, D) at noisy futures x and flow times tau (B,), from z (B, 1, D) and encoded actions (B, P, D).
predictOne sample of the T embeddings that actions (B, T, action_dim) lead to from z[:, 0].
rolloutSample the future of the last context embedding jointly; returns T + 1 embeddings like WorldModel.
samplenum_samples rollouts per batch element: (B, num_samples, T + 1, D).
forwardpixels (B, num_preds + 1, C, H, W) and actions (B, num_preds + 1, action_dim).
Source code in torch_world/models/jepa/_flowjepa.py
python
class FlowJEPA(WorldModel):
    """Flow-JEPA (F-JEPA): a LeWM-style JEPA world model whose predictor samples whole future trajectories by flow
    matching.

    Each frame is encoded to one embedding (the encoder's CLS token) and projected, as in LeWM. From the current
    embedding ``z_t`` and ``num_preds`` actions, a transformer predicts the velocity that transports Gaussian source
    latents ``Z_0`` to the future embeddings ``Z = [z_{t+1}, ..., z_{t+num_preds}]``, all at once. The flow time
    ``tau`` conditions every block through adaLN-zero; future token ``i`` sees ``z_t``, the actions up to ``a_{t+i}``
    and the other future tokens (all of them, or the earlier ones when ``causal``). Training regresses the straight
    path's velocity, end to end with SIGReg on the embeddings:

    ``loss = || v(Z_tau, tau, z_t, a) - (Z - Z_0) ||^2 + lamb * sigreg``, with ``Z_tau = (1 - tau) Z_0 + tau Z``.

    ``Z_0`` is ``source_std * N(0, I)``, centered on ``z_t`` when ``source="current"``. A prediction integrates the flow
    from fresh noise in ``steps`` Euler steps, so ``predict`` and ``rollout`` draw one sample of the future, and
    ``sample`` draws several. Planning scores each candidate by one sampled rollout, as the reference does.

    Huo, Luo and Song, "Flow-JEPA: Robust Latent Dynamics for JEPA World Models via Flow Matching", 2026.
    Paper: https://arxiv.org/abs/2608.29029
    Code: https://github.com/HuoYanchen/Flow-JEPA

    Args:
        encoder: module mapping images ``(N, C, H, W)`` to embeddings ``(N, embed_dim)`` (ViT-tiny CLS in the paper).
        action_dim: dimension of one action, times the frameskip when actions are stacked.
        num_preds: future embeddings predicted jointly in training (``h = 5`` in the paper).
    """

    history = 1

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        embed_dim: int = 192,
        num_preds: int = 5,
        depth: int = 6,
        num_heads: int = 16,
        head_dim: int = 64,
        mlp_dim: int = 2048,
        proj_dim: int = 2048,
        dropout: float = 0.1,
        lamb: float = 0.1,
        steps: int = 8,
        source: str = "noise",
        source_std: float = 1.0,
        causal: bool = False,
        sigreg: SIGReg | None = None,
    ):
        super().__init__()
        if source not in ("noise", "current"):
            raise ValueError(f"source must be 'noise' or 'current', not {source!r}")
        self.embed_dim, self.num_preds, self.steps, self.lamb = embed_dim, num_preds, steps, lamb
        self.source, self.source_std, self.causal = source, source_std, causal
        self.encoder = encoder
        self.projector = MLP([embed_dim, proj_dim, embed_dim], norm=nn.BatchNorm1d)
        self.action_encoder = nn.Sequential(
            nn.Linear(action_dim, action_dim), MLP([action_dim, 4 * embed_dim, embed_dim], act=nn.SiLU)
        )
        self.time_mlp = MLP([embed_dim, embed_dim, embed_dim], act=nn.SiLU)
        self.predictor = Transformer(
            embed_dim, depth, num_heads, conditional=True, mlp_dim=mlp_dim, head_dim=head_dim, dropout=dropout
        )
        self.out_proj = MLP([embed_dim, 4 * embed_dim, embed_dim], norm=nn.RMSNorm)
        self.sigreg = sigreg or SIGReg()

    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
        return self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

    def mask(self, P: int, device) -> Tensor:
        """Boolean attention mask over ``[z_t, a_t .. a_{t+P-1}, x_1 .. x_P]``; ``True`` attends."""
        i = torch.arange(1 + 2 * P, device=device)
        step = torch.where(i <= P, i, i - P)  # z_t is step 0; a_{t+k} and x_{k+1} are step k + 1
        future = i > P
        mask = step[None, :] <= step[:, None]
        return torch.where(future[None, :], future[:, None] & (mask if self.causal else True), mask)

    def velocity(self, x: Tensor, tau: Tensor, z: Tensor, actions: Tensor) -> Tensor:
        """Velocity ``(B, P, D)`` at noisy futures ``x`` and flow times ``tau`` ``(B,)``, from ``z`` ``(B, 1, D)`` and
        encoded actions ``(B, P, D)``."""
        P = x.size(1)
        pos = time_embedding(torch.arange(1, P + 1, device=x.device, dtype=x.dtype), self.embed_dim).to(x.dtype)
        tokens = torch.cat([z, actions + pos, x + pos], dim=1)
        c = self.time_mlp(time_embedding(tau, self.embed_dim).to(x.dtype))[:, None]
        return self.out_proj(self.predictor(tokens, c, attn_mask=self.mask(P, x.device))[:, -P:])

    def source_latents(self, z: Tensor, noise: Tensor) -> Tensor:
        return self.source_std * noise + (z if self.source == "current" else 0)

    def predict(
        self,
        z: Tensor,
        actions: Tensor,
        noise: Tensor | None = None,
        steps: int | None = None,
        generator: torch.Generator | None = None,
    ) -> Tensor:
        """One sample of the ``T`` embeddings that ``actions`` ``(B, T, action_dim)`` lead to from ``z[:, 0]``.

        Later context embeddings are not used (``history = 1``); ``noise`` ``(B, T, D)`` fixes the source sample.
        """
        z0, a = z[:, :1], self.action_encoder(actions)
        if noise is None:
            shape = (z.size(0), actions.size(1), z.size(-1))
            noise = torch.randn(shape, device=z.device, dtype=z.dtype, generator=generator)
        return euler_sample(
            lambda x, t: self.velocity(x, t, z0, a), self.source_latents(z0, noise), steps or self.steps
        )

    def rollout(self, z: Tensor, actions: Tensor, **kwargs) -> Tensor:
        """Sample the future of the last context embedding jointly; returns ``T + 1`` embeddings like ``WorldModel``."""
        return torch.cat([z, self.predict(z[:, -1:], actions[:, z.size(1) - 1 :], **kwargs)], dim=1)

    def sample(
        self, z: Tensor, actions: Tensor, num_samples: int, generator: torch.Generator | None = None, **kwargs
    ) -> Tensor:
        """``num_samples`` rollouts per batch element: ``(B, num_samples, T + 1, D)``."""
        z, actions = z.repeat_interleave(num_samples, 0), actions.repeat_interleave(num_samples, 0)
        return self.rollout(z, actions, generator=generator, **kwargs).unflatten(0, (-1, num_samples))

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, num_preds + 1, C, H, W)`` and ``actions`` ``(B, num_preds + 1, action_dim)``."""
        z, P = self.encode(pixels), self.num_preds
        target = z[:, 1 : P + 1]
        source = self.source_latents(z[:, :1], torch.randn_like(target))
        tau = sample_time(z.size(0), device=z.device, dtype=z.dtype)
        v = self.velocity(interpolate(source, target, tau), tau, z[:, :1], self.action_encoder(actions[:, :P]))
        flow = (v - velocity_target(source, target)).square().mean()
        sigreg = self.sigreg(z.transpose(0, 1))
        return {"loss": flow + self.lamb * sigreg, "flow_loss": flow, "sigreg_loss": sigreg}

method encode ​

torch_world.models.FlowJEPA.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to (B, T, embed_dim).

Source code in torch_world/models/jepa/_flowjepa.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
    return self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

method mask ​

torch_world.models.FlowJEPA.mask GitHub

python
mask(P: int, device) -> Tensor

Boolean attention mask over [z_t, a_t .. a_{t+P-1}, x_1 .. x_P]; True attends.

Source code in torch_world/models/jepa/_flowjepa.py
python
def mask(self, P: int, device) -> Tensor:
    """Boolean attention mask over ``[z_t, a_t .. a_{t+P-1}, x_1 .. x_P]``; ``True`` attends."""
    i = torch.arange(1 + 2 * P, device=device)
    step = torch.where(i <= P, i, i - P)  # z_t is step 0; a_{t+k} and x_{k+1} are step k + 1
    future = i > P
    mask = step[None, :] <= step[:, None]
    return torch.where(future[None, :], future[:, None] & (mask if self.causal else True), mask)

method velocity ​

torch_world.models.FlowJEPA.velocity GitHub

python
velocity(x: Tensor, tau: Tensor, z: Tensor, actions: Tensor) -> Tensor

Velocity (B, P, D) at noisy futures x and flow times tau (B,), from z (B, 1, D) and encoded actions (B, P, D).

Source code in torch_world/models/jepa/_flowjepa.py
python
def velocity(self, x: Tensor, tau: Tensor, z: Tensor, actions: Tensor) -> Tensor:
    """Velocity ``(B, P, D)`` at noisy futures ``x`` and flow times ``tau`` ``(B,)``, from ``z`` ``(B, 1, D)`` and
    encoded actions ``(B, P, D)``."""
    P = x.size(1)
    pos = time_embedding(torch.arange(1, P + 1, device=x.device, dtype=x.dtype), self.embed_dim).to(x.dtype)
    tokens = torch.cat([z, actions + pos, x + pos], dim=1)
    c = self.time_mlp(time_embedding(tau, self.embed_dim).to(x.dtype))[:, None]
    return self.out_proj(self.predictor(tokens, c, attn_mask=self.mask(P, x.device))[:, -P:])

method predict ​

torch_world.models.FlowJEPA.predict GitHub

python
predict(
    z: Tensor,
    actions: Tensor,
    noise: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
) -> Tensor

One sample of the T embeddings that actions (B, T, action_dim) lead to from z[:, 0].

Later context embeddings are not used (history = 1); noise (B, T, D) fixes the source sample.

Source code in torch_world/models/jepa/_flowjepa.py
python
def predict(
    self,
    z: Tensor,
    actions: Tensor,
    noise: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
) -> Tensor:
    """One sample of the ``T`` embeddings that ``actions`` ``(B, T, action_dim)`` lead to from ``z[:, 0]``.

    Later context embeddings are not used (``history = 1``); ``noise`` ``(B, T, D)`` fixes the source sample.
    """
    z0, a = z[:, :1], self.action_encoder(actions)
    if noise is None:
        shape = (z.size(0), actions.size(1), z.size(-1))
        noise = torch.randn(shape, device=z.device, dtype=z.dtype, generator=generator)
    return euler_sample(
        lambda x, t: self.velocity(x, t, z0, a), self.source_latents(z0, noise), steps or self.steps
    )

method rollout ​

torch_world.models.FlowJEPA.rollout GitHub

python
rollout(z: Tensor, actions: Tensor, **kwargs) -> Tensor

Sample the future of the last context embedding jointly; returns T + 1 embeddings like WorldModel.

Source code in torch_world/models/jepa/_flowjepa.py
python
def rollout(self, z: Tensor, actions: Tensor, **kwargs) -> Tensor:
    """Sample the future of the last context embedding jointly; returns ``T + 1`` embeddings like ``WorldModel``."""
    return torch.cat([z, self.predict(z[:, -1:], actions[:, z.size(1) - 1 :], **kwargs)], dim=1)

method sample ​

torch_world.models.FlowJEPA.sample GitHub

python
sample(
    z: Tensor,
    actions: Tensor,
    num_samples: int,
    generator: torch.Generator | None = None,
    **kwargs,
) -> Tensor

num_samples rollouts per batch element: (B, num_samples, T + 1, D).

Source code in torch_world/models/jepa/_flowjepa.py
python
def sample(
    self, z: Tensor, actions: Tensor, num_samples: int, generator: torch.Generator | None = None, **kwargs
) -> Tensor:
    """``num_samples`` rollouts per batch element: ``(B, num_samples, T + 1, D)``."""
    z, actions = z.repeat_interleave(num_samples, 0), actions.repeat_interleave(num_samples, 0)
    return self.rollout(z, actions, generator=generator, **kwargs).unflatten(0, (-1, num_samples))

method forward ​

torch_world.models.FlowJEPA.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, num_preds + 1, C, H, W) and actions (B, num_preds + 1, action_dim).

Source code in torch_world/models/jepa/_flowjepa.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, num_preds + 1, C, H, W)`` and ``actions`` ``(B, num_preds + 1, action_dim)``."""
    z, P = self.encode(pixels), self.num_preds
    target = z[:, 1 : P + 1]
    source = self.source_latents(z[:, :1], torch.randn_like(target))
    tau = sample_time(z.size(0), device=z.device, dtype=z.dtype)
    v = self.velocity(interpolate(source, target, tau), tau, z[:, :1], self.action_encoder(actions[:, :P]))
    flow = (v - velocity_target(source, target)).square().mean()
    sigreg = self.sigreg(z.transpose(0, 1))
    return {"loss": flow + self.lamb * sigreg, "flow_loss": flow, "sigreg_loss": sigreg}

class VariationalJEPA ​

torch_world.models.VariationalJEPA GitHub

python
VariationalJEPA(
    encoder: nn.Module,
    action_dim: int,
    embed_dim: int = 192,
    history: int = 3,
    depth: int = 6,
    num_heads: int = 16,
    head_dim: int = 64,
    mlp_dim: int = 2048,
    proj_dim: int = 2048,
    dropout: float = 0.1,
    beta: float = 0.01,
    lamb: float = 0.09,
    logvar_range: tuple[float, float] = (-10.0, 10.0),
    sigreg: SIGReg | None = None,
)

Variational JEPA (VJEPA): a JEPA world model whose predictor outputs a Gaussian over the next embedding.

The encoder and action-conditioned causal transformer follow LeWM. The predictor head returns the mean and log-variance of p(z_{t+1} | z_{<=t}, a_{<=t}) = N(mu, diag(sigma^2)). Targets come from q(z | x), a diagonal Gaussian whose mean is the embedding of an EMA target encoder and whose log-variance is a learned head on it; a reparameterized sample of q is scored under the predictor's Gaussian:

loss = nll + beta * KL(q || N(0, I)) + lamb * sigreg, with nll = (log sigma^2 + (z - mu)^2 / sigma^2) / 2

averaged over dimensions. SIGReg keeps the online embeddings from collapsing, the role VICReg plays in the reference control experiments. predict returns the mean, the MAP plan the paper shows is optimal for quadratic costs and action-independent noise; predict(..., sample=True) draws from the Gaussian, so CEM can plan on sampled rollouts, and sample draws several rollouts.

Huang, "VJEPA: Variational Joint Embedding Predictive Architectures as Probabilistic World Models", 2026. Paper: https://arxiv.org/abs/2601.14354 Code: https://github.com/YongchaoHuang/VJEPA

Parameters

NameTypeDescriptionDefault
encodernn.Modulemodule mapping images (N, C, H, W) to embeddings (N, embed_dim).required
action_dimintdimension of one action, times the frameskip when actions are stacked.required
betafloatweight of the KL between the target distribution and the standard normal prior.0.01
logvar_rangetuple[float, float]clamp of the predicted log-variances, as the reference does.(-10.0, 10.0)

Members

MemberDescription
encode(B, T, C, H, W) to (B, T, embed_dim).
distributionMean and log-variance (B, T, D) of each next embedding, with teacher forcing.
predictThe predictive mean, or a sample of the Gaussian when sample.
samplenum_samples sampled rollouts per batch element: (B, num_samples, T + 1, D).
forwardpixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim).
Source code in torch_world/models/jepa/_varjepa.py
python
class VariationalJEPA(JEPA, WorldModel):
    """Variational JEPA (VJEPA): a JEPA world model whose predictor outputs a Gaussian over the next embedding.

    The encoder and action-conditioned causal transformer follow LeWM. The predictor head returns the mean and
    log-variance of ``p(z_{t+1} | z_{<=t}, a_{<=t}) = N(mu, diag(sigma^2))``. Targets come from ``q(z | x)``, a diagonal
    Gaussian whose mean is the embedding of an EMA target encoder and whose log-variance is a learned head on it; a
    reparameterized sample of ``q`` is scored under the predictor's Gaussian:

    ``loss = nll + beta * KL(q || N(0, I)) + lamb * sigreg``, with ``nll = (log sigma^2 + (z - mu)^2 / sigma^2) / 2``

    averaged over dimensions. SIGReg keeps the online embeddings from collapsing, the role VICReg plays in the
    reference control experiments. ``predict`` returns the mean, the MAP plan the paper shows is optimal for quadratic
    costs and action-independent noise; ``predict(..., sample=True)`` draws from the Gaussian, so CEM can plan on
    sampled rollouts, and ``sample`` draws several rollouts.

    Huang, "VJEPA: Variational Joint Embedding Predictive Architectures as Probabilistic World Models", 2026.
    Paper: https://arxiv.org/abs/2601.14354
    Code: https://github.com/YongchaoHuang/VJEPA

    Args:
        encoder: module mapping images ``(N, C, H, W)`` to embeddings ``(N, embed_dim)``.
        action_dim: dimension of one action, times the frameskip when actions are stacked.
        beta: weight of the KL between the target distribution and the standard normal prior.
        logvar_range: clamp of the predicted log-variances, as the reference does.
    """

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        embed_dim: int = 192,
        history: int = 3,
        depth: int = 6,
        num_heads: int = 16,
        head_dim: int = 64,
        mlp_dim: int = 2048,
        proj_dim: int = 2048,
        dropout: float = 0.1,
        beta: float = 0.01,
        lamb: float = 0.09,
        logvar_range: tuple[float, float] = (-10.0, 10.0),
        sigreg: SIGReg | None = None,
    ):
        super().__init__()
        self.history, self.beta, self.lamb, self.logvar_range = history, beta, lamb, logvar_range
        self.encoder = nn.Sequential(encoder, MLP([embed_dim, proj_dim, embed_dim], norm=nn.BatchNorm1d))
        self.target_encoder = self.make_target_encoder(self.encoder)
        self.target_logvar = nn.Linear(embed_dim, embed_dim)
        self.action_encoder = nn.Sequential(
            nn.Linear(action_dim, action_dim), MLP([action_dim, 4 * embed_dim, embed_dim], act=nn.SiLU)
        )
        self.pos_embed = nn.Parameter(torch.randn(1, history, embed_dim))
        self.predictor = Transformer(
            embed_dim, depth, num_heads, conditional=True, mlp_dim=mlp_dim, head_dim=head_dim, dropout=dropout
        )
        self.head = MLP([embed_dim, proj_dim, 2 * embed_dim], norm=nn.BatchNorm1d)
        self.sigreg = sigreg or SIGReg()

    def encode(self, pixels: Tensor, encoder: nn.Module | None = None) -> Tensor:
        """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
        return (encoder or self.encoder)(pixels.flatten(0, 1)).unflatten(0, pixels.shape[:2])

    def distribution(self, z: Tensor, actions: Tensor) -> tuple[Tensor, Tensor]:
        """Mean and log-variance ``(B, T, D)`` of each next embedding, with teacher forcing."""
        B, T = z.shape[:2]
        h = self.predictor(z + self.pos_embed[:, :T], self.action_encoder(actions), is_causal=True)
        mean, logvar = self.head(h.flatten(0, 1)).unflatten(0, (B, T)).chunk(2, dim=-1)
        return mean, logvar.clamp(*self.logvar_range)

    def predict(
        self, z: Tensor, actions: Tensor, sample: bool = False, generator: torch.Generator | None = None
    ) -> Tensor:
        """The predictive mean, or a sample of the Gaussian when ``sample``."""
        mean, logvar = self.distribution(z, actions)
        if not sample:
            return mean
        noise = torch.randn(mean.shape, device=mean.device, dtype=mean.dtype, generator=generator)
        return mean + (0.5 * logvar).exp() * noise

    def sample(self, z: Tensor, actions: Tensor, num_samples: int, generator: torch.Generator | None = None) -> Tensor:
        """``num_samples`` sampled rollouts per batch element: ``(B, num_samples, T + 1, D)``."""
        z, actions = z.repeat_interleave(num_samples, 0), actions.repeat_interleave(num_samples, 0)
        return self.rollout(z, actions, sample=True, generator=generator).unflatten(0, (-1, num_samples))

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``.

        Call ``update_target(momentum)`` after each optimizer step.
        """
        H = self.history
        z = self.encode(pixels)
        with torch.no_grad():
            target_mean = self.encode(pixels[:, 1 : H + 1], self.target_encoder)
        target_logvar = self.target_logvar(target_mean).clamp(*self.logvar_range)
        target = target_mean + (0.5 * target_logvar).exp() * torch.randn_like(target_mean)
        mean, logvar = self.distribution(z[:, :H], actions[:, :H])
        nll = 0.5 * (logvar + (target - mean).square() / logvar.exp()).mean()
        kl = 0.5 * (target_logvar.exp() + target_mean.square() - 1 - target_logvar).mean()
        sigreg = self.sigreg(z.transpose(0, 1))
        loss = nll + self.beta * kl + self.lamb * sigreg
        return {
            "loss": loss,
            "nll_loss": nll,
            "kl_loss": kl,
            "sigreg_loss": sigreg,
            "variance": logvar.detach().exp().mean(),
        }

method encode ​

torch_world.models.VariationalJEPA.encode GitHub

python
encode(pixels: Tensor, encoder: nn.Module | None = None) -> Tensor

(B, T, C, H, W) to (B, T, embed_dim).

Source code in torch_world/models/jepa/_varjepa.py
python
def encode(self, pixels: Tensor, encoder: nn.Module | None = None) -> Tensor:
    """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
    return (encoder or self.encoder)(pixels.flatten(0, 1)).unflatten(0, pixels.shape[:2])

method distribution ​

torch_world.models.VariationalJEPA.distribution GitHub

python
distribution(z: Tensor, actions: Tensor) -> tuple[Tensor, Tensor]

Mean and log-variance (B, T, D) of each next embedding, with teacher forcing.

Source code in torch_world/models/jepa/_varjepa.py
python
def distribution(self, z: Tensor, actions: Tensor) -> tuple[Tensor, Tensor]:
    """Mean and log-variance ``(B, T, D)`` of each next embedding, with teacher forcing."""
    B, T = z.shape[:2]
    h = self.predictor(z + self.pos_embed[:, :T], self.action_encoder(actions), is_causal=True)
    mean, logvar = self.head(h.flatten(0, 1)).unflatten(0, (B, T)).chunk(2, dim=-1)
    return mean, logvar.clamp(*self.logvar_range)

method predict ​

torch_world.models.VariationalJEPA.predict GitHub

python
predict(
    z: Tensor,
    actions: Tensor,
    sample: bool = False,
    generator: torch.Generator | None = None,
) -> Tensor

The predictive mean, or a sample of the Gaussian when sample.

Source code in torch_world/models/jepa/_varjepa.py
python
def predict(
    self, z: Tensor, actions: Tensor, sample: bool = False, generator: torch.Generator | None = None
) -> Tensor:
    """The predictive mean, or a sample of the Gaussian when ``sample``."""
    mean, logvar = self.distribution(z, actions)
    if not sample:
        return mean
    noise = torch.randn(mean.shape, device=mean.device, dtype=mean.dtype, generator=generator)
    return mean + (0.5 * logvar).exp() * noise

method sample ​

torch_world.models.VariationalJEPA.sample GitHub

python
sample(
    z: Tensor,
    actions: Tensor,
    num_samples: int,
    generator: torch.Generator | None = None,
) -> Tensor

num_samples sampled rollouts per batch element: (B, num_samples, T + 1, D).

Source code in torch_world/models/jepa/_varjepa.py
python
def sample(self, z: Tensor, actions: Tensor, num_samples: int, generator: torch.Generator | None = None) -> Tensor:
    """``num_samples`` sampled rollouts per batch element: ``(B, num_samples, T + 1, D)``."""
    z, actions = z.repeat_interleave(num_samples, 0), actions.repeat_interleave(num_samples, 0)
    return self.rollout(z, actions, sample=True, generator=generator).unflatten(0, (-1, num_samples))

method forward ​

torch_world.models.VariationalJEPA.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim).

Call update_target(momentum) after each optimizer step.

Source code in torch_world/models/jepa/_varjepa.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``.

    Call ``update_target(momentum)`` after each optimizer step.
    """
    H = self.history
    z = self.encode(pixels)
    with torch.no_grad():
        target_mean = self.encode(pixels[:, 1 : H + 1], self.target_encoder)
    target_logvar = self.target_logvar(target_mean).clamp(*self.logvar_range)
    target = target_mean + (0.5 * target_logvar).exp() * torch.randn_like(target_mean)
    mean, logvar = self.distribution(z[:, :H], actions[:, :H])
    nll = 0.5 * (logvar + (target - mean).square() / logvar.exp()).mean()
    kl = 0.5 * (target_logvar.exp() + target_mean.square() - 1 - target_logvar).mean()
    sigreg = self.sigreg(z.transpose(0, 1))
    loss = nll + self.beta * kl + self.lamb * sigreg
    return {
        "loss": loss,
        "nll_loss": nll,
        "kl_loss": kl,
        "sigreg_loss": sigreg,
        "variance": logvar.detach().exp().mean(),
    }

class HWM ​

torch_world.models.HWM GitHub

python
HWM(
    low: LeWM,
    action_dim: int,
    stride: int = 4,
    macro_dim: int = 8,
    embed_dim: int = 192,
    history: int = 3,
    depth: int = 4,
    num_heads: int = 8,
    head_dim: int = 24,
    mlp_dim: int = 1024,
    dropout: float = 0.1,
    gamma_roll: float = 1.0,
    gamma_tf_high: float = 1.0,
    gamma_roll_high: float = 0.0,
)

Hierarchical world model (HWM): two action-conditioned predictors in one latent space, on two time scales.

The low level is a LeWM that predicts the next latent from primitive actions. The high level predicts the latent stride steps later, the next waypoint, from a latent macro-action: an MLP encodes the stride actions between two waypoints. Both levels share the low level's latents; the high level sees them through a stop-gradient, as HWM trains it on a frozen encoder. Planning is top-down: a planner searches macro-actions that reach the goal latent, the first predicted waypoint becomes the subgoal of a low-level planner, and the plan is redone after each executed step (planning.HierarchicalPlanner).

Windows hold high.history + 1 waypoints, T = high.history * stride + 1 frames. Each level is trained with the ℓ1 teacher-forcing loss, the low level also with the ℓ1 multi-step rollout loss on a random crop of low.history + 1 frames, and SIGReg keeps the latents from collapsing as the encoder learns from pixels::

loss = tf_low + gamma_roll * roll_low + lamb * sigreg + gamma_tf_high * tf_high + gamma_roll_high * roll_high

roll_high is the high level's ℓ1 loss on its own autoregressive rollout from the first waypoint, the objective the paper uses for the high level on Diverse Maze (gamma_tf_high=0, gamma_roll_high=1); the defaults keep its teacher-forcing recipe for Franka and Push-T. Planning rolls the high level out over several macro-actions, which the rollout loss trains for.

Zhang et al., "Hierarchical Planning with Latent World Models", 2026. Paper: https://arxiv.org/abs/2604.03208 Code: https://github.com/kevinghst/HWM_PLDM

Parameters

NameTypeDescriptionDefault
lowLeWMthe low-level world model; its lamb and sigreg weight SIGReg.required
action_dimintdimension of one primitive action.required
strideintprimitive steps between waypoints.4
macro_dimintdimension of a macro-action (8 in the paper's maze).8
gamma_tf_highfloatweight of the high level's teacher-forcing loss.1.0
gamma_roll_highfloatweight of the high level's rollout loss; 0 skips computing it.0.0

Members

MemberDescription
encode(B, T, C, H, W) to (B, T, embed_dim).
liftLow-level latents to high-level latents: the identity, as both levels share one latent space.
encode_macroPrimitive actions (B, K * stride, A) to macro-actions (B, K, macro_dim).
forwardpixels (B, T, C, H, W) and actions (B, T, A) with T = high.history * stride + 1.
Source code in torch_world/models/jepa/_hwm.py
python
class HWM(WorldModel):
    """Hierarchical world model (HWM): two action-conditioned predictors in one latent space, on two time scales.

    The low level is a ``LeWM`` that predicts the next latent from primitive actions. The high level predicts the
    latent ``stride`` steps later, the next waypoint, from a latent macro-action: an MLP encodes the ``stride``
    actions between two waypoints. Both levels share the low level's latents; the high level sees them through a
    stop-gradient, as HWM trains it on a frozen encoder. Planning is top-down: a planner searches macro-actions that
    reach the goal latent, the first predicted waypoint becomes the subgoal of a low-level planner, and the plan is
    redone after each executed step (``planning.HierarchicalPlanner``).

    Windows hold ``high.history + 1`` waypoints, ``T = high.history * stride + 1`` frames. Each level is trained with
    the ℓ1 teacher-forcing loss, the low level also with the ℓ1 multi-step rollout loss on a random crop of
    ``low.history + 1`` frames, and SIGReg keeps the latents from collapsing as the encoder learns from pixels::

        loss = tf_low + gamma_roll * roll_low + lamb * sigreg + gamma_tf_high * tf_high + gamma_roll_high * roll_high

    ``roll_high`` is the high level's ℓ1 loss on its own autoregressive rollout from the first waypoint, the objective
    the paper uses for the high level on Diverse Maze (``gamma_tf_high=0, gamma_roll_high=1``); the defaults keep its
    teacher-forcing recipe for Franka and Push-T. Planning rolls the high level out over several macro-actions, which
    the rollout loss trains for.

    Zhang et al., "Hierarchical Planning with Latent World Models", 2026.
    Paper: https://arxiv.org/abs/2604.03208
    Code: https://github.com/kevinghst/HWM_PLDM

    Args:
        low: the low-level world model; its ``lamb`` and ``sigreg`` weight SIGReg.
        action_dim: dimension of one primitive action.
        stride: primitive steps between waypoints.
        macro_dim: dimension of a macro-action (8 in the paper's maze).
        gamma_tf_high: weight of the high level's teacher-forcing loss.
        gamma_roll_high: weight of the high level's rollout loss; 0 skips computing it.
    """

    def __init__(
        self,
        low: LeWM,
        action_dim: int,
        stride: int = 4,
        macro_dim: int = 8,
        embed_dim: int = 192,
        history: int = 3,
        depth: int = 4,
        num_heads: int = 8,
        head_dim: int = 24,
        mlp_dim: int = 1024,
        dropout: float = 0.1,
        gamma_roll: float = 1.0,
        gamma_tf_high: float = 1.0,
        gamma_roll_high: float = 0.0,
    ):
        super().__init__()
        self.low, self.stride, self.gamma_roll = low, stride, gamma_roll
        self.gamma_tf_high, self.gamma_roll_high = gamma_tf_high, gamma_roll_high
        self.history = low.history
        self.macro_encoder = nn.Sequential(
            MLP([stride * action_dim, 4 * embed_dim, macro_dim]), nn.BatchNorm1d(macro_dim, affine=False)
        )
        self.high = MacroLevel(embed_dim, macro_dim, history, depth, num_heads, head_dim, mlp_dim, dropout, p=1)

    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
        return self.low.encode(pixels)

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        return self.low.predict(z, actions)

    def cost(self, z: Tensor, goal: Tensor) -> Tensor:
        return self.high.cost(z, goal)

    def lift(self, z: Tensor) -> Tensor:
        """Low-level latents to high-level latents: the identity, as both levels share one latent space."""
        return z

    def encode_macro(self, actions: Tensor) -> Tensor:
        """Primitive actions ``(B, K * stride, A)`` to macro-actions ``(B, K, macro_dim)``."""
        chunks = actions.unflatten(1, (-1, self.stride)).flatten(2)
        return self.macro_encoder(chunks.flatten(0, 1)).unflatten(0, chunks.shape[:2])

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, T, C, H, W)`` and ``actions`` ``(B, T, A)`` with ``T = high.history * stride + 1``."""
        z = self.encode(pixels)
        h = self.low.history
        t = int(torch.randint(z.size(1) - h, ()))
        pred = self.low.predict(z[:, t : t + h], actions[:, t : t + h])
        tf_low = (pred - z[:, t + 1 : t + h + 1]).abs().mean()
        roll = self.low.rollout(z[:, t : t + 1], actions[:, t : t + h])[:, 1:]
        roll_low = (roll - z[:, t + 1 : t + h + 1]).abs().mean()
        sigreg = self.low.sigreg(z.transpose(0, 1))
        waypoints = z.detach()[:, :: self.stride]
        macro = self.encode_macro(actions[:, : (waypoints.size(1) - 1) * self.stride])
        out = {"low_loss": tf_low, "rollout_loss": roll_low, "sigreg_loss": sigreg}
        loss = tf_low + self.gamma_roll * roll_low + self.low.lamb * sigreg
        if self.gamma_tf_high:
            tf_high = self.high.distance(self.high.predict(waypoints[:, :-1], macro), waypoints[:, 1:]).mean()
            loss = loss + self.gamma_tf_high * tf_high
            out["high_loss"] = tf_high
        if self.gamma_roll_high:
            roll_high = self.high.distance(self.high.rollout(waypoints[:, :1], macro)[:, 1:], waypoints[:, 1:]).mean()
            loss = loss + self.gamma_roll_high * roll_high
            out["high_rollout_loss"] = roll_high
        return {"loss": loss, **out}

method encode ​

torch_world.models.HWM.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to (B, T, embed_dim).

Source code in torch_world/models/jepa/_hwm.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
    return self.low.encode(pixels)

method lift ​

torch_world.models.HWM.lift GitHub

python
lift(z: Tensor) -> Tensor

Low-level latents to high-level latents: the identity, as both levels share one latent space.

Source code in torch_world/models/jepa/_hwm.py
python
def lift(self, z: Tensor) -> Tensor:
    """Low-level latents to high-level latents: the identity, as both levels share one latent space."""
    return z

method encode_macro ​

torch_world.models.HWM.encode_macro GitHub

python
encode_macro(actions: Tensor) -> Tensor

Primitive actions (B, K * stride, A) to macro-actions (B, K, macro_dim).

Source code in torch_world/models/jepa/_hwm.py
python
def encode_macro(self, actions: Tensor) -> Tensor:
    """Primitive actions ``(B, K * stride, A)`` to macro-actions ``(B, K, macro_dim)``."""
    chunks = actions.unflatten(1, (-1, self.stride)).flatten(2)
    return self.macro_encoder(chunks.flatten(0, 1)).unflatten(0, chunks.shape[:2])

method forward ​

torch_world.models.HWM.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, T, C, H, W) and actions (B, T, A) with T = high.history * stride + 1.

Source code in torch_world/models/jepa/_hwm.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, T, C, H, W)`` and ``actions`` ``(B, T, A)`` with ``T = high.history * stride + 1``."""
    z = self.encode(pixels)
    h = self.low.history
    t = int(torch.randint(z.size(1) - h, ()))
    pred = self.low.predict(z[:, t : t + h], actions[:, t : t + h])
    tf_low = (pred - z[:, t + 1 : t + h + 1]).abs().mean()
    roll = self.low.rollout(z[:, t : t + 1], actions[:, t : t + h])[:, 1:]
    roll_low = (roll - z[:, t + 1 : t + h + 1]).abs().mean()
    sigreg = self.low.sigreg(z.transpose(0, 1))
    waypoints = z.detach()[:, :: self.stride]
    macro = self.encode_macro(actions[:, : (waypoints.size(1) - 1) * self.stride])
    out = {"low_loss": tf_low, "rollout_loss": roll_low, "sigreg_loss": sigreg}
    loss = tf_low + self.gamma_roll * roll_low + self.low.lamb * sigreg
    if self.gamma_tf_high:
        tf_high = self.high.distance(self.high.predict(waypoints[:, :-1], macro), waypoints[:, 1:]).mean()
        loss = loss + self.gamma_tf_high * tf_high
        out["high_loss"] = tf_high
    if self.gamma_roll_high:
        roll_high = self.high.distance(self.high.rollout(waypoints[:, :1], macro)[:, 1:], waypoints[:, 1:]).mean()
        loss = loss + self.gamma_roll_high * roll_high
        out["high_rollout_loss"] = roll_high
    return {"loss": loss, **out}

class MacroLevel ​

torch_world.models.MacroLevel GitHub

python
MacroLevel(
    embed_dim: int,
    macro_dim: int,
    history: int = 3,
    depth: int = 4,
    num_heads: int = 8,
    head_dim: int = 24,
    mlp_dim: int = 1024,
    dropout: float = 0.1,
    p: int = 2,
)

Upper level of a hierarchical world model: predicts the next waypoint latent from past waypoint latents and latent macro-actions, with a causal transformer conditioned on the macro-actions through adaLN-zero.

Macro-actions are standardized: the encoders that produce them end with a BatchNorm without affine parameters, so each dimension of a training macro-action has zero mean and unit variance. Planners search them in N(0, I) clipped to about ±2, as the papers initialize from and clip to the statistics of training macro-actions. p is the norm of the training loss and the planning cost: 1 in HWM, 2 in H-JEPA.

Members

MemberDescription
predictWaypoint latents (B, T, embed_dim) and macro-actions (B, T, macro_dim) to next waypoint latents.
distanceMean p-distance over the last dim: absolute error for p = 1, squared error for p = 2.
Source code in torch_world/models/jepa/_hwm.py
python
class MacroLevel(WorldModel):
    """Upper level of a hierarchical world model: predicts the next waypoint latent from past waypoint latents and
    latent macro-actions, with a causal transformer conditioned on the macro-actions through adaLN-zero.

    Macro-actions are standardized: the encoders that produce them end with a BatchNorm without affine parameters, so
    each dimension of a training macro-action has zero mean and unit variance. Planners search them in ``N(0, I)``
    clipped to about ``±2``, as the papers initialize from and clip to the statistics of training macro-actions.
    ``p`` is the norm of the training loss and the planning cost: 1 in HWM, 2 in H-JEPA.
    """

    def __init__(
        self,
        embed_dim: int,
        macro_dim: int,
        history: int = 3,
        depth: int = 4,
        num_heads: int = 8,
        head_dim: int = 24,
        mlp_dim: int = 1024,
        dropout: float = 0.1,
        p: int = 2,
    ):
        super().__init__()
        self.history, self.macro_dim, self.p = history, macro_dim, p
        self.macro_embed = MLP([macro_dim, 4 * embed_dim, embed_dim], act=nn.SiLU)
        self.pos_embed = nn.Parameter(torch.randn(1, history, embed_dim))
        self.predictor = Transformer(
            embed_dim, depth, num_heads, conditional=True, mlp_dim=mlp_dim, head_dim=head_dim, dropout=dropout
        )
        self.proj = nn.Linear(embed_dim, embed_dim)

    def predict(self, z: Tensor, macro: Tensor) -> Tensor:
        """Waypoint latents ``(B, T, embed_dim)`` and macro-actions ``(B, T, macro_dim)`` to next waypoint latents."""
        h = self.predictor(z + self.pos_embed[:, : z.size(1)], self.macro_embed(macro), is_causal=True)
        return self.proj(h)

    def distance(self, pred: Tensor, target: Tensor) -> Tensor:
        """Mean ``p``-distance over the last dim: absolute error for ``p = 1``, squared error for ``p = 2``."""
        return (pred - target).abs().pow(self.p).mean(-1)

    def cost(self, z: Tensor, goal: Tensor) -> Tensor:
        return self.distance(z[:, -1], goal)

method predict ​

torch_world.models.MacroLevel.predict GitHub

python
predict(z: Tensor, macro: Tensor) -> Tensor

Waypoint latents (B, T, embed_dim) and macro-actions (B, T, macro_dim) to next waypoint latents.

Source code in torch_world/models/jepa/_hwm.py
python
def predict(self, z: Tensor, macro: Tensor) -> Tensor:
    """Waypoint latents ``(B, T, embed_dim)`` and macro-actions ``(B, T, macro_dim)`` to next waypoint latents."""
    h = self.predictor(z + self.pos_embed[:, : z.size(1)], self.macro_embed(macro), is_causal=True)
    return self.proj(h)

method distance ​

torch_world.models.MacroLevel.distance GitHub

python
distance(pred: Tensor, target: Tensor) -> Tensor

Mean p-distance over the last dim: absolute error for p = 1, squared error for p = 2.

Source code in torch_world/models/jepa/_hwm.py
python
def distance(self, pred: Tensor, target: Tensor) -> Tensor:
    """Mean ``p``-distance over the last dim: absolute error for ``p = 1``, squared error for ``p = 2``."""
    return (pred - target).abs().pow(self.p).mean(-1)

class HJEPA ​

torch_world.models.HJEPA GitHub

python
HJEPA(
    low: LeWM,
    stride: int = 4,
    macro_dim: int = 4,
    embed_dim: int = 192,
    encoder_dim: int = 384,
    history: int = 3,
    depth: int = 4,
    num_heads: int = 8,
    head_dim: int = 24,
    mlp_dim: int = 1024,
    dropout: float = 0.1,
    sigreg: SIGReg | None = None,
)

H-JEPA: a two-level hierarchy of JEPA world models trained end-to-end from pixels.

Level 1 is a LeWM: next-embedding prediction from primitive actions. Level 2 has its own state encoder, an MLP over every stride-th level-1 latent, z2_k = E2(z1_{k * stride}), and its own macro-actions: a one-layer transformer pools the stride level-1 action embeddings between two of its states. Its predictor (MacroLevel) predicts the next level-2 latent. Each level is a JEPA with teacher-forced MSE and SIGReg on its own latents, and the level-2 loss flows into the level-1 encoder and action encoder::

loss = mse_1 + lamb * sigreg(z1) + mse_2 + lamb * sigreg(z2)

Planning is top-down (planning.HierarchicalPlanner): level 2 plans macro-actions toward E2(goal), and level 1 plans the next stride actions so that E2 of its last predicted latent matches the first level-2 prediction, the subgoal, in level-2 space. The paper plans every level by gradient descent (planning.GradientPlanner).

Windows hold high.history + 1 level-2 states, T = high.history * stride + 1 frames; level 1 is trained on a random crop of low.history + 1 frames, as the reference crops each level to its context.

Zhang et al., "H-JEPA: End-to-End Learning of Hierarchical World Models for Visual Planning", 2026. Paper: https://arxiv.org/abs/2610.06805 Code: https://github.com/kevinghst/H-JEPA

Parameters

NameTypeDescriptionDefault
lowLeWMlevel 1; its lamb weights SIGReg at both levels, uniform across levels as in the paper.required
strideintlevel-1 steps per level-2 step (2 in the paper, 4 here by default).4
macro_dimintdimension of a level-2 macro-action (4 in the paper).4
embed_dimintdimension of level-1 latents and of level-2 latents.192

Members

MemberDescription
encode(B, T, C, H, W) to level-1 latents (B, T, embed_dim).
liftLevel-1 latents (B, T, D) to level-2 latents (B, T, D), step by step (H-JEPA's window of 1).
encode_macroPrimitive actions (B, K * stride, A) to macro-actions (B, K, macro_dim).
forwardpixels (B, T, C, H, W) and actions (B, T, A) with T = high.history * stride + 1.
Source code in torch_world/models/jepa/_hjepa.py
python
class HJEPA(WorldModel):
    """H-JEPA: a two-level hierarchy of JEPA world models trained end-to-end from pixels.

    Level 1 is a ``LeWM``: next-embedding prediction from primitive actions. Level 2 has its own state encoder, an
    MLP over every ``stride``-th level-1 latent, ``z2_k = E2(z1_{k * stride})``, and its own macro-actions: a
    one-layer transformer pools the ``stride`` level-1 action embeddings between two of its states. Its predictor
    (``MacroLevel``) predicts the next level-2 latent. Each level is a JEPA with teacher-forced MSE and SIGReg on its
    own latents, and the level-2 loss flows into the level-1 encoder and action encoder::

        loss = mse_1 + lamb * sigreg(z1) + mse_2 + lamb * sigreg(z2)

    Planning is top-down (``planning.HierarchicalPlanner``): level 2 plans macro-actions toward ``E2(goal)``, and
    level 1 plans the next ``stride`` actions so that ``E2`` of its last predicted latent matches the first level-2
    prediction, the subgoal, in level-2 space. The paper plans every level by gradient descent
    (``planning.GradientPlanner``).

    Windows hold ``high.history + 1`` level-2 states, ``T = high.history * stride + 1`` frames; level 1 is trained on
    a random crop of ``low.history + 1`` frames, as the reference crops each level to its context.

    Zhang et al., "H-JEPA: End-to-End Learning of Hierarchical World Models for Visual Planning", 2026.
    Paper: https://arxiv.org/abs/2610.06805
    Code: https://github.com/kevinghst/H-JEPA

    Args:
        low: level 1; its ``lamb`` weights SIGReg at both levels, uniform across levels as in the paper.
        stride: level-1 steps per level-2 step (2 in the paper, 4 here by default).
        macro_dim: dimension of a level-2 macro-action (4 in the paper).
        embed_dim: dimension of level-1 latents and of level-2 latents.
    """

    def __init__(
        self,
        low: LeWM,
        stride: int = 4,
        macro_dim: int = 4,
        embed_dim: int = 192,
        encoder_dim: int = 384,
        history: int = 3,
        depth: int = 4,
        num_heads: int = 8,
        head_dim: int = 24,
        mlp_dim: int = 1024,
        dropout: float = 0.1,
        sigreg: SIGReg | None = None,
    ):
        super().__init__()
        self.low, self.stride = low, stride
        self.history = low.history
        self.state_encoder = MLP([embed_dim, encoder_dim, embed_dim], act=nn.ReLU)
        self.macro_encoder = MacroPool(embed_dim, macro_dim, stride)
        self.high = MacroLevel(embed_dim, macro_dim, history, depth, num_heads, head_dim, mlp_dim, dropout, p=2)
        self.sigreg = sigreg or SIGReg()

    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to level-1 latents ``(B, T, embed_dim)``."""
        return self.low.encode(pixels)

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        return self.low.predict(z, actions)

    def lift(self, z: Tensor) -> Tensor:
        """Level-1 latents ``(B, T, D)`` to level-2 latents ``(B, T, D)``, step by step (H-JEPA's window of 1)."""
        return self.state_encoder(z)

    def encode_macro(self, actions: Tensor) -> Tensor:
        """Primitive actions ``(B, K * stride, A)`` to macro-actions ``(B, K, macro_dim)``."""
        chunks = self.low.action_encoder(actions).unflatten(1, (-1, self.stride))
        return self.macro_encoder(chunks.flatten(0, 1)).unflatten(0, chunks.shape[:2])

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, T, C, H, W)`` and ``actions`` ``(B, T, A)`` with ``T = high.history * stride + 1``."""
        z = self.encode(pixels)
        h = self.low.history
        t = int(torch.randint(z.size(1) - h, ()))
        pred = self.low.predict(z[:, t : t + h], actions[:, t : t + h])
        mse_1 = (pred - z[:, t + 1 : t + h + 1]).square().mean()
        sigreg_1 = self.low.sigreg(z[:, t : t + h + 1].transpose(0, 1))
        z2 = self.lift(z[:, :: self.stride])
        macro = self.encode_macro(actions[:, : (z2.size(1) - 1) * self.stride])
        mse_2 = (self.high.predict(z2[:, :-1], macro) - z2[:, 1:]).square().mean()
        sigreg_2 = self.sigreg(z2.transpose(0, 1))
        loss = mse_1 + mse_2 + self.low.lamb * (sigreg_1 + sigreg_2)
        return {
            "loss": loss,
            "low_loss": mse_1,
            "high_loss": mse_2,
            "low_sigreg_loss": sigreg_1,
            "high_sigreg_loss": sigreg_2,
        }

method encode ​

torch_world.models.HJEPA.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to level-1 latents (B, T, embed_dim).

Source code in torch_world/models/jepa/_hjepa.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to level-1 latents ``(B, T, embed_dim)``."""
    return self.low.encode(pixels)

method lift ​

torch_world.models.HJEPA.lift GitHub

python
lift(z: Tensor) -> Tensor

Level-1 latents (B, T, D) to level-2 latents (B, T, D), step by step (H-JEPA's window of 1).

Source code in torch_world/models/jepa/_hjepa.py
python
def lift(self, z: Tensor) -> Tensor:
    """Level-1 latents ``(B, T, D)`` to level-2 latents ``(B, T, D)``, step by step (H-JEPA's window of 1)."""
    return self.state_encoder(z)

method encode_macro ​

torch_world.models.HJEPA.encode_macro GitHub

python
encode_macro(actions: Tensor) -> Tensor

Primitive actions (B, K * stride, A) to macro-actions (B, K, macro_dim).

Source code in torch_world/models/jepa/_hjepa.py
python
def encode_macro(self, actions: Tensor) -> Tensor:
    """Primitive actions ``(B, K * stride, A)`` to macro-actions ``(B, K, macro_dim)``."""
    chunks = self.low.action_encoder(actions).unflatten(1, (-1, self.stride))
    return self.macro_encoder(chunks.flatten(0, 1)).unflatten(0, chunks.shape[:2])

method forward ​

torch_world.models.HJEPA.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, T, C, H, W) and actions (B, T, A) with T = high.history * stride + 1.

Source code in torch_world/models/jepa/_hjepa.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, T, C, H, W)`` and ``actions`` ``(B, T, A)`` with ``T = high.history * stride + 1``."""
    z = self.encode(pixels)
    h = self.low.history
    t = int(torch.randint(z.size(1) - h, ()))
    pred = self.low.predict(z[:, t : t + h], actions[:, t : t + h])
    mse_1 = (pred - z[:, t + 1 : t + h + 1]).square().mean()
    sigreg_1 = self.low.sigreg(z[:, t : t + h + 1].transpose(0, 1))
    z2 = self.lift(z[:, :: self.stride])
    macro = self.encode_macro(actions[:, : (z2.size(1) - 1) * self.stride])
    mse_2 = (self.high.predict(z2[:, :-1], macro) - z2[:, 1:]).square().mean()
    sigreg_2 = self.sigreg(z2.transpose(0, 1))
    loss = mse_1 + mse_2 + self.low.lamb * (sigreg_1 + sigreg_2)
    return {
        "loss": loss,
        "low_loss": mse_1,
        "high_loss": mse_2,
        "low_sigreg_loss": sigreg_1,
        "high_sigreg_loss": sigreg_2,
    }

class MacroPool ​

torch_world.models.MacroPool GitHub

python
MacroPool(
    dim: int, macro_dim: int, stride: int, width: int = 64, num_heads: int = 2
)

Pool stride action embeddings (N, stride, dim) into a macro-action (N, macro_dim): a one-layer transformer over the chunk, read out at a CLS token, as H-JEPA's sequence encoder.

Source code in torch_world/models/jepa/_hjepa.py
python
class MacroPool(nn.Module):
    """Pool ``stride`` action embeddings ``(N, stride, dim)`` into a macro-action ``(N, macro_dim)``: a one-layer
    transformer over the chunk, read out at a CLS token, as H-JEPA's sequence encoder."""

    def __init__(self, dim: int, macro_dim: int, stride: int, width: int = 64, num_heads: int = 2):
        super().__init__()
        self.inp = nn.Linear(dim, width)
        self.pos = nn.Parameter(torch.randn(1, stride + 1, width) * 0.02)
        layer = nn.TransformerEncoderLayer(width, num_heads, 2 * width, dropout=0.0, batch_first=True, norm_first=True)
        self.encoder = nn.TransformerEncoder(layer, 1, enable_nested_tensor=False)
        self.head = nn.Sequential(nn.Linear(width, width), nn.GELU(), nn.LayerNorm(width), nn.Linear(width, macro_dim))
        self.norm = nn.BatchNorm1d(macro_dim, affine=False)

    def forward(self, x: Tensor) -> Tensor:
        x = torch.cat([self.pos[:, :1].expand(len(x), -1, -1), self.inp(x) + self.pos[:, 1:]], dim=1)
        return self.norm(self.head(self.encoder(x)[:, 0]))

class AdaJEPA ​

torch_world.models.AdaJEPA GitHub

python
AdaJEPA(
    encoder: nn.Module,
    action_dim: int,
    embed_dim: int = 128,
    action_embed_dim: int = 16,
    history: int = 3,
    depth: int = 4,
    num_heads: int = 4,
    head_dim: int = 32,
    mlp_dim: int = 512,
    dropout: float = 0.0,
    curvature_coeff: float = 0.1,
    std_coeff: float = 1.0,
    cov_coeff: float = 0.04,
)

AdaJEPA: a JEPA world model that keeps learning at test time, inside the planning loop.

Each frame is encoded to one global latent, normalized by a LayerNorm. A causal transformer reads the last history latents, each concatenated with its action embedding, and predicts the next latents; the action features of its output are dropped. Training is teacher-forced one-step prediction against stop-gradient targets, with the temporal straightening (curvature) term of the base model and VCReg variance and covariance terms on the latents:

loss = pred + curvature_coeff * curvature + std_coeff * std + cov_coeff * cov

At test time the model plans, runs the first action, and adds the observed transition (o_t, a_t, o_{t+1}) to a buffer of the most recent ones. Before planning again it takes steps gradient steps of the same stop-gradient prediction loss on that buffer, updating only the last predictor block with the final norm and the encoder's last layer; every episode starts again from the trained weights. adapt does one such update and policy builds the closed loop.

Wang, Bounou, LeCun and Ren, "AdaJEPA: An Adaptive Latent World Model", 2026. Paper: https://arxiv.org/abs/2606.32026 Code: https://github.com/agentic-learning-ai-lab/adajepa

Parameters

NameTypeDescriptionDefault
encodernn.Modulemodule mapping images (N, C, H, W) to latents (N, embed_dim), such as PLDMEncoder. Its last child module with parameters is the head adapted at test time.required
action_dimintdimension of one action.required
action_embed_dimintwidth of the action embedding concatenated to each latent (10 in the paper).16
curvature_coeff, std_coeff, cov_coeffweights of the straightening, variance and covariance terms.required

Members

MemberDescription
encode(B, T, C, H, W) to (B, T, embed_dim).
prediction_lossOne-step MSE against stop-gradient targets over every window of history steps of z (B, T + 1, D) and actions (B, T, A).
forwardpixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim); the last action is unused.
adapted_parametersThe parameters updated at test time: the last predictor block with the final norm, and the encoder head.
adaptTake steps Adam steps of the stop-gradient prediction loss on observed transitions, in place.
policyClosed-loop policy that adapts the model on the last buffer transitions of each episode before every plan; steps=0 gives the same loop with the model frozen.
Source code in torch_world/models/jepa/_adajepa.py
python
class AdaJEPA(WorldModel):
    """AdaJEPA: a JEPA world model that keeps learning at test time, inside the planning loop.

    Each frame is encoded to one global latent, normalized by a LayerNorm. A causal transformer reads the last
    ``history`` latents, each concatenated with its action embedding, and predicts the next latents; the action
    features of its output are dropped. Training is teacher-forced one-step prediction against stop-gradient targets, with the temporal
    straightening (curvature) term of the base model and VCReg variance and covariance terms on the latents:

    ``loss = pred + curvature_coeff * curvature + std_coeff * std + cov_coeff * cov``

    At test time the model plans, runs the first action, and adds the observed transition ``(o_t, a_t, o_{t+1})`` to a
    buffer of the most recent ones. Before planning again it takes ``steps`` gradient steps of the same stop-gradient
    prediction loss on that buffer, updating only the last predictor block with the final norm and the encoder's
    last layer; every episode starts again from the trained weights. ``adapt`` does one such update and ``policy``
    builds the closed loop.

    Wang, Bounou, LeCun and Ren, "AdaJEPA: An Adaptive Latent World Model", 2026.
    Paper: https://arxiv.org/abs/2606.32026
    Code: https://github.com/agentic-learning-ai-lab/adajepa

    Args:
        encoder: module mapping images ``(N, C, H, W)`` to latents ``(N, embed_dim)``, such as ``PLDMEncoder``. Its
            last child module with parameters is the head adapted at test time.
        action_dim: dimension of one action.
        action_embed_dim: width of the action embedding concatenated to each latent (10 in the paper).
        curvature_coeff, std_coeff, cov_coeff: weights of the straightening, variance and covariance terms.
    """

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        embed_dim: int = 128,
        action_embed_dim: int = 16,
        history: int = 3,
        depth: int = 4,
        num_heads: int = 4,
        head_dim: int = 32,
        mlp_dim: int = 512,
        dropout: float = 0.0,
        curvature_coeff: float = 0.1,
        std_coeff: float = 1.0,
        cov_coeff: float = 0.04,
    ):
        super().__init__()
        self.history, self.embed_dim = history, embed_dim
        self.curvature_coeff, self.std_coeff, self.cov_coeff = curvature_coeff, std_coeff, cov_coeff
        self.encoder = encoder
        self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False)
        self.action_encoder = nn.Linear(action_dim, action_embed_dim)
        dim = embed_dim + action_embed_dim
        self.pos_embed = nn.Parameter(torch.randn(1, history, dim) * 0.02)
        self.predictor = Transformer(dim, depth, num_heads, mlp_dim=mlp_dim, head_dim=head_dim, dropout=dropout)

    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
        return self.norm(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        T = z.size(1)
        x = torch.cat([z, self.action_encoder(actions)], -1) + self.pos_embed[:, :T]
        return self.predictor(x, is_causal=True)[..., : self.embed_dim]

    def prediction_loss(self, z: Tensor, actions: Tensor) -> Tensor:
        """One-step MSE against stop-gradient targets over every window of ``history`` steps of ``z`` ``(B, T + 1, D)``
        and ``actions`` ``(B, T, A)``."""
        w = min(self.history, actions.size(1))
        windows = range(actions.size(1) - w + 1)
        src = torch.cat([z[:, t : t + w] for t in windows])
        act = torch.cat([actions[:, t : t + w] for t in windows])
        tgt = torch.cat([z[:, t + 1 : t + 1 + w] for t in windows]).detach()
        return (self.predict(src, act) - tgt).square().mean()

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``; the last action
        is unused."""
        z = self.encode(pixels)
        pred = self.prediction_loss(z[:, : self.history + 1], actions[:, : self.history])
        v1, v2 = z[:, 1:-1] - z[:, :-2], z[:, 2:] - z[:, 1:-1]
        curvature = (1 - F.cosine_similarity(v1, v2, dim=-1)).mean() if z.size(1) > 2 else z.new_zeros(())
        flat = z.flatten(0, 1)
        flat = flat - flat.mean(0)
        std = (1 - (flat.var(0) + 1e-4).sqrt()).relu().mean()
        cov = flat.T @ flat / (len(flat) - 1)
        cov = (cov.square().sum() - cov.diagonal().square().sum()) / flat.size(1)
        loss = pred + self.curvature_coeff * curvature + self.std_coeff * std + self.cov_coeff * cov
        return {"loss": loss, "pred_loss": pred, "curvature_loss": curvature, "std_loss": std, "cov_loss": cov}

    def adapted_parameters(self) -> tuple[list[nn.Parameter], list[nn.Parameter]]:
        """The parameters updated at test time: the last predictor block with the final norm, and the encoder head."""
        predictor = [*self.predictor.blocks[-1].parameters(), *self.predictor.norm.parameters()]
        head = [m for m in self.encoder.children() if any(True for _ in m.parameters())]
        return predictor, list(head[-1].parameters() if head else self.encoder.parameters())

    def adapt(
        self, pixels: Tensor, actions: Tensor, steps: int = 1, lr: float = 5e-4, encoder_lr: float = 1e-5
    ) -> list[float]:
        """Take ``steps`` Adam steps of the stop-gradient prediction loss on observed transitions, in place.

        ``pixels`` ``(B, T + 1, C, H, W)`` and ``actions`` ``(B, T, action_dim)`` hold the frames of the replay buffer
        and the actions between them. A fresh optimizer is made on every call, as in the reference; ``encoder_lr=0``
        keeps the encoder frozen. Returns the loss before each step.
        """
        predictor, head = self.adapted_parameters()
        groups = [{"params": predictor, "lr": lr}] + ([{"params": head, "lr": encoder_lr}] if encoder_lr else [])
        trainable = [p for g in groups for p in g["params"]]
        saved = [p.requires_grad for p in self.parameters()]
        self.requires_grad_(False)
        for p in trainable:
            p.requires_grad_(True)
        opt, losses = torch.optim.Adam(groups), []
        with torch.enable_grad():
            if not encoder_lr:
                with torch.no_grad():
                    z = self.encode(pixels)
            for _ in range(steps):
                loss = self.prediction_loss(self.encode(pixels) if encoder_lr else z, actions)
                opt.zero_grad()
                loss.backward()
                opt.step()
                losses.append(loss.item())
        for p, r in zip(self.parameters(), saved):
            p.requires_grad_(r)
        return losses

    def policy(
        self,
        planner,
        goal_images: Tensor,
        buffer: int = 5,
        steps: int = 1,
        lr: float = 5e-4,
        encoder_lr: float = 1e-5,
    ) -> "AdaptivePolicy":
        """Closed-loop policy that adapts the model on the last ``buffer`` transitions of each episode before every
        plan; ``steps=0`` gives the same loop with the model frozen. See ``AdaptivePolicy``."""
        return AdaptivePolicy(self, planner, goal_images, buffer, steps, lr, encoder_lr)

method encode ​

torch_world.models.AdaJEPA.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to (B, T, embed_dim).

Source code in torch_world/models/jepa/_adajepa.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``."""
    return self.norm(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

method prediction_loss ​

torch_world.models.AdaJEPA.prediction_loss GitHub

python
prediction_loss(z: Tensor, actions: Tensor) -> Tensor

One-step MSE against stop-gradient targets over every window of history steps of z (B, T + 1, D) and actions (B, T, A).

Source code in torch_world/models/jepa/_adajepa.py
python
def prediction_loss(self, z: Tensor, actions: Tensor) -> Tensor:
    """One-step MSE against stop-gradient targets over every window of ``history`` steps of ``z`` ``(B, T + 1, D)``
    and ``actions`` ``(B, T, A)``."""
    w = min(self.history, actions.size(1))
    windows = range(actions.size(1) - w + 1)
    src = torch.cat([z[:, t : t + w] for t in windows])
    act = torch.cat([actions[:, t : t + w] for t in windows])
    tgt = torch.cat([z[:, t + 1 : t + 1 + w] for t in windows]).detach()
    return (self.predict(src, act) - tgt).square().mean()

method forward ​

torch_world.models.AdaJEPA.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim); the last action is unused.

Source code in torch_world/models/jepa/_adajepa.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``; the last action
    is unused."""
    z = self.encode(pixels)
    pred = self.prediction_loss(z[:, : self.history + 1], actions[:, : self.history])
    v1, v2 = z[:, 1:-1] - z[:, :-2], z[:, 2:] - z[:, 1:-1]
    curvature = (1 - F.cosine_similarity(v1, v2, dim=-1)).mean() if z.size(1) > 2 else z.new_zeros(())
    flat = z.flatten(0, 1)
    flat = flat - flat.mean(0)
    std = (1 - (flat.var(0) + 1e-4).sqrt()).relu().mean()
    cov = flat.T @ flat / (len(flat) - 1)
    cov = (cov.square().sum() - cov.diagonal().square().sum()) / flat.size(1)
    loss = pred + self.curvature_coeff * curvature + self.std_coeff * std + self.cov_coeff * cov
    return {"loss": loss, "pred_loss": pred, "curvature_loss": curvature, "std_loss": std, "cov_loss": cov}

method adapted_parameters ​

torch_world.models.AdaJEPA.adapted_parameters GitHub

python
adapted_parameters() -> tuple[list[nn.Parameter], list[nn.Parameter]]

The parameters updated at test time: the last predictor block with the final norm, and the encoder head.

Source code in torch_world/models/jepa/_adajepa.py
python
def adapted_parameters(self) -> tuple[list[nn.Parameter], list[nn.Parameter]]:
    """The parameters updated at test time: the last predictor block with the final norm, and the encoder head."""
    predictor = [*self.predictor.blocks[-1].parameters(), *self.predictor.norm.parameters()]
    head = [m for m in self.encoder.children() if any(True for _ in m.parameters())]
    return predictor, list(head[-1].parameters() if head else self.encoder.parameters())

method adapt ​

torch_world.models.AdaJEPA.adapt GitHub

python
adapt(
    pixels: Tensor,
    actions: Tensor,
    steps: int = 1,
    lr: float = 0.0005,
    encoder_lr: float = 1e-05,
) -> list[float]

Take steps Adam steps of the stop-gradient prediction loss on observed transitions, in place.

pixels (B, T + 1, C, H, W) and actions (B, T, action_dim) hold the frames of the replay buffer and the actions between them. A fresh optimizer is made on every call, as in the reference; encoder_lr=0 keeps the encoder frozen. Returns the loss before each step.

Source code in torch_world/models/jepa/_adajepa.py
python
def adapt(
    self, pixels: Tensor, actions: Tensor, steps: int = 1, lr: float = 5e-4, encoder_lr: float = 1e-5
) -> list[float]:
    """Take ``steps`` Adam steps of the stop-gradient prediction loss on observed transitions, in place.

    ``pixels`` ``(B, T + 1, C, H, W)`` and ``actions`` ``(B, T, action_dim)`` hold the frames of the replay buffer
    and the actions between them. A fresh optimizer is made on every call, as in the reference; ``encoder_lr=0``
    keeps the encoder frozen. Returns the loss before each step.
    """
    predictor, head = self.adapted_parameters()
    groups = [{"params": predictor, "lr": lr}] + ([{"params": head, "lr": encoder_lr}] if encoder_lr else [])
    trainable = [p for g in groups for p in g["params"]]
    saved = [p.requires_grad for p in self.parameters()]
    self.requires_grad_(False)
    for p in trainable:
        p.requires_grad_(True)
    opt, losses = torch.optim.Adam(groups), []
    with torch.enable_grad():
        if not encoder_lr:
            with torch.no_grad():
                z = self.encode(pixels)
        for _ in range(steps):
            loss = self.prediction_loss(self.encode(pixels) if encoder_lr else z, actions)
            opt.zero_grad()
            loss.backward()
            opt.step()
            losses.append(loss.item())
    for p, r in zip(self.parameters(), saved):
        p.requires_grad_(r)
    return losses

method policy ​

torch_world.models.AdaJEPA.policy GitHub

python
policy(
    planner,
    goal_images: Tensor,
    buffer: int = 5,
    steps: int = 1,
    lr: float = 0.0005,
    encoder_lr: float = 1e-05,
) -> AdaptivePolicy

Closed-loop policy that adapts the model on the last buffer transitions of each episode before every plan; steps=0 gives the same loop with the model frozen. See AdaptivePolicy.

Source code in torch_world/models/jepa/_adajepa.py
python
def policy(
    self,
    planner,
    goal_images: Tensor,
    buffer: int = 5,
    steps: int = 1,
    lr: float = 5e-4,
    encoder_lr: float = 1e-5,
) -> "AdaptivePolicy":
    """Closed-loop policy that adapts the model on the last ``buffer`` transitions of each episode before every
    plan; ``steps=0`` gives the same loop with the model frozen. See ``AdaptivePolicy``."""
    return AdaptivePolicy(self, planner, goal_images, buffer, steps, lr, encoder_lr)

class TDJEPA ​

torch_world.models.TDJEPA GitHub

python
TDJEPA(
    phi_encoder: nn.Module,
    psi_encoder: nn.Module,
    action_dim: int,
    phi_dim: int = 256,
    task_dim: int = 50,
    hidden_dim: int = 1024,
    hidden_layers: int = 1,
    actor_dim: int = 256,
    actor_layers: int = 1,
    num_twins: int = 2,
    discount: float = 0.98,
    lamb: float = 1.0,
    p_goal: float = 0.5,
    actor_std: float = 0.2,
    actor_clip: float = 0.3,
    normalize: bool = True,
)

TD-JEPA: latent-predictive representations for zero-shot RL, learned from reward-free transitions with temporal-difference latent prediction.

A state encoder phi and a task encoder psi embed observations. A predictor T_phi(phi(s), a, z) predicts the discounted sum of future psi embeddings (the successor features of psi) under the policy pi_z, and T_psi(psi(s), a, z) symmetrically those of phi. Both are trained by TD against EMA target networks, with the next action drawn from the policy, plus an orthonormality regularizer on each encoder:

``L = 1/2 || T_phi(phi(s), a, z) - psi-(s') - gamma T_phi-(phi-(s'), a', z) ||^2 + (same with phi, psi swapped)

  • lamb * (reg(phi) + reg(psi)), with a' ~ pi(phi-(s'), z)andreg(phi) = mean_{i != j} (phi_i . phi_j)^2 / 2 - mean_i phi_i . phi_i``.

Since T_phi(phi(s), a, z) . z is then the Q-value of pi_z for the reward r(s) = psi(s) . z, the actor maximizes it for every z (through the predictor, which it cannot update). Task embeddings z are drawn on the sphere of radius sqrt(task_dim), or with probability p_goal are psi of random dataset states. At test time, no training is needed: infer_task regresses a reward onto psi, goal_task embeds goal observations, and policy acts for the inferred z.

forward returns the encoder/predictor losses plus the actor loss; their gradients reach disjoint parameters, so one backward pass matches Algorithm 1's three updates. Call update_target after every optimizer step.

Bagatella, Pirotta, Touati, Lazaric and Tirinzoni, "TD-JEPA: Latent-predictive Representations for Zero-Shot Reinforcement Learning", ICLR 2026. Paper: https://arxiv.org/abs/2510.00739 Code: not released; this follows the paper.

Parameters

NameTypeDescriptionDefault
phi_encodernn.Modulemodule mapping observations (N, ...) to (N, phi_dim), such as drq_encoder.required
psi_encodernn.Modulemodule mapping observations (N, ...) to (N, task_dim).required
hidden_dim, hidden_layerswidth and ReLU layers after the two embedding layers of the predictors.required
actor_dim, actor_layersthe same for the actor.required
num_twinsintpredictor heads; targets and values use their mean.2
lambfloatweight of the orthonormality regularizer (lambda).1.0
p_goalfloatprobability that a training z is psi of a random dataset state.0.5
actor_std, actor_clipfixed std of the actor's Gaussian and the clip of its noise.required
normalizeboolproject encoder outputs onto the sphere of radius sqrt(dim) (Touati et al.'s L2 normalization).True

Members

MemberDescription
param_groupsAdam groups: everything at lr, the task encoder psi at task_lr (the paper sweeps 1e-4, 1e-5).
update_targetEMA of phi, psi, T_phi and T_psi; the paper's EMA coefficient is 1 - momentum.
phiState embeddings (N, phi_dim) of observations (N, ...).
psiTask embeddings (N, task_dim) of observations (N, ...).
encode(B, T, ...) to state embeddings (B, T, phi_dim).
encode_task(B, T, ...) to task embeddings (B, T, task_dim).
sample_tasksn task embeddings (n, task_dim): uniform on the sphere of radius sqrt(task_dim), or with probability p_goal the projected psi of goals (n, ...).
policyActions (..., action_dim) in [-1, 1] for state embeddings z and tasks task: the actor's mean, or with explore a sample with clipped Gaussian noise.
predictT_phi: successor features of psi (..., task_dim) under pi_task from (z, actions), the mean of the twin heads.
valueQ-values (...) of pi_task for the reward ``psi(s) .
infer_taskZero-shot task embedding (task_dim,) for the reward rewards (N,) observed at obs (N, ...): the least-squares z = E[psi psi^T]^-1 E[psi r], projected onto the sphere the policies were trained on unless project=False.
goal_taskTask embeddings (B, task_dim) for reaching goal observations (B, ...): psi(goal), whitened by E[psi psi^T]^-1 over obs (N, ...) when given (the regression of a reward that is one at the goal), and projected onto the sphere.
controllerClosed-loop policy observation (B, ...) -> action (B, action_dim) for tasks (B, task_dim) or one task (task_dim,) shared by the batch; it runs the actor's mean on the model's device.
orthonormality``mean_{i != j} (x_i .
forwardTransitions pixels (B, 2, ...) (s and s') and actions (B, 2, action_dim) (only actions[:, 0], taken at s, is used), as windows of 2 from TrajectoryDataset.
Source code in torch_world/models/jepa/_tdjepa.py
python
class TDJEPA(JEPA):
    """TD-JEPA: latent-predictive representations for zero-shot RL, learned from reward-free transitions with
    temporal-difference latent prediction.

    A state encoder ``phi`` and a task encoder ``psi`` embed observations. A predictor ``T_phi(phi(s), a, z)``
    predicts the discounted sum of future ``psi`` embeddings (the successor features of ``psi``) under the policy
    ``pi_z``, and ``T_psi(psi(s), a, z)`` symmetrically those of ``phi``. Both are trained by TD against EMA target
    networks, with the next action drawn from the policy, plus an orthonormality regularizer on each encoder:

    ``L = 1/2 || T_phi(phi(s), a, z) - psi-(s') - gamma T_phi-(phi-(s'), a', z) ||^2 + (same with phi, psi swapped)
    + lamb * (reg(phi) + reg(psi))``, with ``a' ~ pi(phi-(s'), z)`` and
    ``reg(phi) = mean_{i != j} (phi_i . phi_j)^2 / 2 - mean_i phi_i . phi_i``.

    Since ``T_phi(phi(s), a, z) . z`` is then the Q-value of ``pi_z`` for the reward ``r(s) = psi(s) . z``, the actor
    maximizes it for every ``z`` (through the predictor, which it cannot update). Task embeddings ``z`` are drawn on
    the sphere of radius ``sqrt(task_dim)``, or with probability ``p_goal`` are ``psi`` of random dataset states. At
    test time, no training is needed: ``infer_task`` regresses a reward onto ``psi``, ``goal_task`` embeds goal
    observations, and ``policy`` acts for the inferred ``z``.

    ``forward`` returns the encoder/predictor losses plus the actor loss; their gradients reach disjoint parameters,
    so one backward pass matches Algorithm 1's three updates. Call ``update_target`` after every optimizer step.

    Bagatella, Pirotta, Touati, Lazaric and Tirinzoni, "TD-JEPA: Latent-predictive Representations for Zero-Shot
    Reinforcement Learning", ICLR 2026.
    Paper: https://arxiv.org/abs/2510.00739
    Code: not released; this follows the paper.

    Args:
        phi_encoder: module mapping observations ``(N, ...)`` to ``(N, phi_dim)``, such as ``drq_encoder``.
        psi_encoder: module mapping observations ``(N, ...)`` to ``(N, task_dim)``.
        hidden_dim, hidden_layers: width and ReLU layers after the two embedding layers of the predictors.
        actor_dim, actor_layers: the same for the actor.
        num_twins: predictor heads; targets and values use their mean.
        lamb: weight of the orthonormality regularizer (``lambda``).
        p_goal: probability that a training ``z`` is ``psi`` of a random dataset state.
        actor_std, actor_clip: fixed std of the actor's Gaussian and the clip of its noise.
        normalize: project encoder outputs onto the sphere of radius ``sqrt(dim)`` (Touati et al.'s L2 normalization).
    """

    def __init__(
        self,
        phi_encoder: nn.Module,
        psi_encoder: nn.Module,
        action_dim: int,
        phi_dim: int = 256,
        task_dim: int = 50,
        hidden_dim: int = 1024,
        hidden_layers: int = 1,
        actor_dim: int = 256,
        actor_layers: int = 1,
        num_twins: int = 2,
        discount: float = 0.98,
        lamb: float = 1.0,
        p_goal: float = 0.5,
        actor_std: float = 0.2,
        actor_clip: float = 0.3,
        normalize: bool = True,
    ):
        super().__init__()
        self.action_dim, self.phi_dim, self.task_dim = action_dim, phi_dim, task_dim
        self.discount, self.lamb, self.p_goal = discount, lamb, p_goal
        self.actor_std, self.actor_clip, self.normalize = actor_std, actor_clip, normalize
        self.phi_encoder, self.psi_encoder = phi_encoder, psi_encoder
        self.phi_predictor = TDPredictor(phi_dim, action_dim, task_dim, task_dim, hidden_dim, hidden_layers, num_twins)
        self.psi_predictor = TDPredictor(task_dim, action_dim, task_dim, phi_dim, hidden_dim, hidden_layers, num_twins)
        self.actor = TDActor(phi_dim, action_dim, task_dim, actor_dim, actor_layers)
        self.targets = nn.ModuleDict(
            {
                name: self.make_target_encoder(getattr(self, name))
                for name in ("phi_encoder", "psi_encoder", "phi_predictor", "psi_predictor")
            }
        )

    def param_groups(self, lr: float = 1e-4, task_lr: float | None = None) -> list[dict]:
        """Adam groups: everything at ``lr``, the task encoder ``psi`` at ``task_lr`` (the paper sweeps 1e-4, 1e-5)."""
        psi = list(self.psi_encoder.parameters())
        skip = {id(p) for p in psi}
        rest = [p for p in self.parameters() if p.requires_grad and id(p) not in skip]
        return [{"params": rest, "lr": lr}, {"params": psi, "lr": task_lr or lr}]

    def update_target(self, momentum: float = 0.995):
        """EMA of ``phi``, ``psi``, ``T_phi`` and ``T_psi``; the paper's EMA coefficient is ``1 - momentum``."""
        for name, target in self.targets.items():
            ema_update(target, getattr(self, name), momentum)

    def _embed(self, net: nn.Module, x: Tensor) -> Tensor:
        x = net(x)
        return sphere(x) if self.normalize else x

    def phi(self, obs: Tensor, target: bool = False) -> Tensor:
        """State embeddings ``(N, phi_dim)`` of observations ``(N, ...)``."""
        return self._embed(self.targets["phi_encoder"] if target else self.phi_encoder, obs)

    def psi(self, obs: Tensor, target: bool = False) -> Tensor:
        """Task embeddings ``(N, task_dim)`` of observations ``(N, ...)``."""
        return self._embed(self.targets["psi_encoder"] if target else self.psi_encoder, obs)

    def encode(self, obs: Tensor) -> Tensor:
        """``(B, T, ...)`` to state embeddings ``(B, T, phi_dim)``."""
        return self.phi(obs.flatten(0, 1)).unflatten(0, obs.shape[:2])

    def encode_task(self, obs: Tensor) -> Tensor:
        """``(B, T, ...)`` to task embeddings ``(B, T, task_dim)``."""
        return self.psi(obs.flatten(0, 1)).unflatten(0, obs.shape[:2])

    def sample_tasks(self, n: int, goals: Tensor | None = None) -> Tensor:
        """``n`` task embeddings ``(n, task_dim)``: uniform on the sphere of radius ``sqrt(task_dim)``, or with
        probability ``p_goal`` the projected ``psi`` of ``goals`` ``(n, ...)``."""
        device = next(self.parameters()).device
        z = sphere(torch.randn(n, self.task_dim, device=device))
        if goals is not None and self.p_goal > 0:
            with torch.no_grad():
                goal_z = sphere(self.psi(goals))
            z = torch.where(torch.rand(n, 1, device=device) < self.p_goal, goal_z, z)
        return z

    def policy(self, z: Tensor, task: Tensor, explore: bool = False) -> Tensor:
        """Actions ``(..., action_dim)`` in ``[-1, 1]`` for state embeddings ``z`` and tasks ``task``: the actor's
        mean, or with ``explore`` a sample with clipped Gaussian noise."""
        mean = self.actor(z, task)
        if not explore:
            return mean
        noise = (self.actor_std * torch.randn_like(mean)).clamp(-self.actor_clip, self.actor_clip)
        return (mean + noise).clamp(-1, 1)

    def predict(self, z: Tensor, actions: Tensor, task: Tensor, target: bool = False, detach: bool = False) -> Tensor:
        """``T_phi``: successor features of ``psi`` ``(..., task_dim)`` under ``pi_task`` from ``(z, actions)``, the
        mean of the twin heads. ``detach`` lets gradients reach the inputs but not the predictor."""
        net = self.targets["phi_predictor"] if target else self.phi_predictor
        if detach:
            return functional_call(net, {k: v.detach() for k, v in net.named_parameters()}, (z, actions, task)).mean(0)
        return net(z, actions, task).mean(0)

    def value(self, z: Tensor, actions: Tensor, task: Tensor, **kwargs) -> Tensor:
        """Q-values ``(...)`` of ``pi_task`` for the reward ``psi(s) . task``: ``T_phi(z, a, task) . task``."""
        return (self.predict(z, actions, task, **kwargs) * task).sum(-1)

    @torch.no_grad()
    def _psi_batched(self, obs: Tensor, chunk: int = 1024) -> Tensor:
        device = next(self.parameters()).device
        return torch.cat([self.psi(x.to(device)) for x in obs.split(chunk)])

    @torch.no_grad()
    def infer_task(self, obs: Tensor, rewards: Tensor, ridge: float = 1e-6, project: bool = True) -> Tensor:
        """Zero-shot task embedding ``(task_dim,)`` for the reward ``rewards`` ``(N,)`` observed at ``obs`` ``(N,
        ...)``: the least-squares ``z = E[psi psi^T]^-1 E[psi r]``, projected onto the sphere the policies were
        trained on unless ``project=False``."""
        psi = self._psi_batched(obs)
        cov = psi.T @ psi / len(psi)
        z = torch.linalg.solve(cov + ridge * torch.eye(len(cov), device=cov.device), psi.T @ rewards.to(psi) / len(psi))
        return sphere(z) if project else z

    @torch.no_grad()
    def goal_task(self, goals: Tensor, obs: Tensor | None = None, ridge: float = 1e-6) -> Tensor:
        """Task embeddings ``(B, task_dim)`` for reaching goal observations ``(B, ...)``: ``psi(goal)``, whitened by
        ``E[psi psi^T]^-1`` over ``obs`` ``(N, ...)`` when given (the regression of a reward that is one at the goal),
        and projected onto the sphere."""
        z = self._psi_batched(goals)
        if obs is not None:
            psi = self._psi_batched(obs)
            cov = psi.T @ psi / len(psi) + ridge * torch.eye(psi.size(1), device=psi.device)
            z = torch.linalg.solve(cov, z.T).T
        return sphere(z)

    def controller(self, task: Tensor) -> Callable[[Tensor], Tensor]:
        """Closed-loop policy ``observation (B, ...) -> action (B, action_dim)`` for tasks ``(B, task_dim)`` or one
        task ``(task_dim,)`` shared by the batch; it runs the actor's mean on the model's device."""
        device = next(self.parameters()).device

        @torch.no_grad()
        def act(obs: Tensor) -> Tensor:
            z = self.phi(obs.to(device))
            return self.policy(z, task.to(device).expand(len(z), -1)).to(obs.device)

        return act

    @staticmethod
    def orthonormality(x: Tensor) -> Tensor:
        """``mean_{i != j} (x_i . x_j)^2 / 2 - mean_i x_i . x_i`` over a batch ``(B, d)``: pushes ``E[x x^T]`` to
        ``I``."""
        cov = x @ x.T
        off = ~torch.eye(len(x), dtype=torch.bool, device=x.device)
        return 0.5 * cov[off].square().mean() - cov.diagonal().mean()

    def forward(self, pixels: Tensor, actions: Tensor, goals: Tensor | None = None) -> dict[str, Tensor]:
        """Transitions ``pixels`` ``(B, 2, ...)`` (``s`` and ``s'``) and ``actions`` ``(B, 2, action_dim)`` (only
        ``actions[:, 0]``, taken at ``s``, is used), as windows of 2 from ``TrajectoryDataset``. Goal tasks are
        ``psi`` of ``goals`` ``(B, ...)``, by default the batch's next observations shuffled."""
        obs, action, next_obs = pixels[:, 0], actions[:, 0], pixels[:, 1]
        with torch.no_grad():
            z = self.sample_tasks(len(obs), next_obs[torch.randperm(len(obs))] if goals is None else goals)
            next_phi, next_psi = self.phi(next_obs, target=True), self.psi(next_obs, target=True)
            next_action = self.policy(next_phi, z, explore=True)
            phi_target = next_psi + self.discount * self.targets["phi_predictor"](next_phi, next_action, z).mean(0)
            psi_target = next_phi + self.discount * self.targets["psi_predictor"](next_psi, next_action, z).mean(0)
        phi, psi = self.phi(obs), self.psi(obs)
        td_phi = 0.5 * (self.phi_predictor(phi, action, z) - phi_target).square().sum(-1).mean()
        td_psi = 0.5 * (self.psi_predictor(psi, action, z) - psi_target).square().sum(-1).mean()
        ortho = self.orthonormality(phi) + self.orthonormality(psi)

        state = phi.detach()
        actor = -self.value(state, self.policy(state, z, explore=True), z, detach=True).mean()
        loss = td_phi + td_psi + self.lamb * ortho + actor
        return {"loss": loss, "td_phi_loss": td_phi, "td_psi_loss": td_psi, "ortho_loss": ortho, "actor_loss": actor}

method param_groups ​

torch_world.models.TDJEPA.param_groups GitHub

python
param_groups(
    lr: float = 0.0001, task_lr: float | None = None
) -> list[dict]

Adam groups: everything at lr, the task encoder psi at task_lr (the paper sweeps 1e-4, 1e-5).

Source code in torch_world/models/jepa/_tdjepa.py
python
def param_groups(self, lr: float = 1e-4, task_lr: float | None = None) -> list[dict]:
    """Adam groups: everything at ``lr``, the task encoder ``psi`` at ``task_lr`` (the paper sweeps 1e-4, 1e-5)."""
    psi = list(self.psi_encoder.parameters())
    skip = {id(p) for p in psi}
    rest = [p for p in self.parameters() if p.requires_grad and id(p) not in skip]
    return [{"params": rest, "lr": lr}, {"params": psi, "lr": task_lr or lr}]

method update_target ​

torch_world.models.TDJEPA.update_target GitHub

python
update_target(momentum: float = 0.995)

EMA of phi, psi, T_phi and T_psi; the paper's EMA coefficient is 1 - momentum.

Source code in torch_world/models/jepa/_tdjepa.py
python
def update_target(self, momentum: float = 0.995):
    """EMA of ``phi``, ``psi``, ``T_phi`` and ``T_psi``; the paper's EMA coefficient is ``1 - momentum``."""
    for name, target in self.targets.items():
        ema_update(target, getattr(self, name), momentum)

method phi ​

torch_world.models.TDJEPA.phi GitHub

python
phi(obs: Tensor, target: bool = False) -> Tensor

State embeddings (N, phi_dim) of observations (N, ...).

Source code in torch_world/models/jepa/_tdjepa.py
python
def phi(self, obs: Tensor, target: bool = False) -> Tensor:
    """State embeddings ``(N, phi_dim)`` of observations ``(N, ...)``."""
    return self._embed(self.targets["phi_encoder"] if target else self.phi_encoder, obs)

method psi ​

torch_world.models.TDJEPA.psi GitHub

python
psi(obs: Tensor, target: bool = False) -> Tensor

Task embeddings (N, task_dim) of observations (N, ...).

Source code in torch_world/models/jepa/_tdjepa.py
python
def psi(self, obs: Tensor, target: bool = False) -> Tensor:
    """Task embeddings ``(N, task_dim)`` of observations ``(N, ...)``."""
    return self._embed(self.targets["psi_encoder"] if target else self.psi_encoder, obs)

method encode ​

torch_world.models.TDJEPA.encode GitHub

python
encode(obs: Tensor) -> Tensor

(B, T, ...) to state embeddings (B, T, phi_dim).

Source code in torch_world/models/jepa/_tdjepa.py
python
def encode(self, obs: Tensor) -> Tensor:
    """``(B, T, ...)`` to state embeddings ``(B, T, phi_dim)``."""
    return self.phi(obs.flatten(0, 1)).unflatten(0, obs.shape[:2])

method encode_task ​

torch_world.models.TDJEPA.encode_task GitHub

python
encode_task(obs: Tensor) -> Tensor

(B, T, ...) to task embeddings (B, T, task_dim).

Source code in torch_world/models/jepa/_tdjepa.py
python
def encode_task(self, obs: Tensor) -> Tensor:
    """``(B, T, ...)`` to task embeddings ``(B, T, task_dim)``."""
    return self.psi(obs.flatten(0, 1)).unflatten(0, obs.shape[:2])

method sample_tasks ​

torch_world.models.TDJEPA.sample_tasks GitHub

python
sample_tasks(n: int, goals: Tensor | None = None) -> Tensor

n task embeddings (n, task_dim): uniform on the sphere of radius sqrt(task_dim), or with probability p_goal the projected psi of goals (n, ...).

Source code in torch_world/models/jepa/_tdjepa.py
python
def sample_tasks(self, n: int, goals: Tensor | None = None) -> Tensor:
    """``n`` task embeddings ``(n, task_dim)``: uniform on the sphere of radius ``sqrt(task_dim)``, or with
    probability ``p_goal`` the projected ``psi`` of ``goals`` ``(n, ...)``."""
    device = next(self.parameters()).device
    z = sphere(torch.randn(n, self.task_dim, device=device))
    if goals is not None and self.p_goal > 0:
        with torch.no_grad():
            goal_z = sphere(self.psi(goals))
        z = torch.where(torch.rand(n, 1, device=device) < self.p_goal, goal_z, z)
    return z

method policy ​

torch_world.models.TDJEPA.policy GitHub

python
policy(z: Tensor, task: Tensor, explore: bool = False) -> Tensor

Actions (..., action_dim) in [-1, 1] for state embeddings z and tasks task: the actor's mean, or with explore a sample with clipped Gaussian noise.

Source code in torch_world/models/jepa/_tdjepa.py
python
def policy(self, z: Tensor, task: Tensor, explore: bool = False) -> Tensor:
    """Actions ``(..., action_dim)`` in ``[-1, 1]`` for state embeddings ``z`` and tasks ``task``: the actor's
    mean, or with ``explore`` a sample with clipped Gaussian noise."""
    mean = self.actor(z, task)
    if not explore:
        return mean
    noise = (self.actor_std * torch.randn_like(mean)).clamp(-self.actor_clip, self.actor_clip)
    return (mean + noise).clamp(-1, 1)

method predict ​

torch_world.models.TDJEPA.predict GitHub

python
predict(
    z: Tensor,
    actions: Tensor,
    task: Tensor,
    target: bool = False,
    detach: bool = False,
) -> Tensor

T_phi: successor features of psi (..., task_dim) under pi_task from (z, actions), the mean of the twin heads. detach lets gradients reach the inputs but not the predictor.

Source code in torch_world/models/jepa/_tdjepa.py
python
def predict(self, z: Tensor, actions: Tensor, task: Tensor, target: bool = False, detach: bool = False) -> Tensor:
    """``T_phi``: successor features of ``psi`` ``(..., task_dim)`` under ``pi_task`` from ``(z, actions)``, the
    mean of the twin heads. ``detach`` lets gradients reach the inputs but not the predictor."""
    net = self.targets["phi_predictor"] if target else self.phi_predictor
    if detach:
        return functional_call(net, {k: v.detach() for k, v in net.named_parameters()}, (z, actions, task)).mean(0)
    return net(z, actions, task).mean(0)

method value ​

torch_world.models.TDJEPA.value GitHub

python
value(z: Tensor, actions: Tensor, task: Tensor, **kwargs) -> Tensor

Q-values (...) of pi_task for the reward psi(s) . task: T_phi(z, a, task) . task.

Source code in torch_world/models/jepa/_tdjepa.py
python
def value(self, z: Tensor, actions: Tensor, task: Tensor, **kwargs) -> Tensor:
    """Q-values ``(...)`` of ``pi_task`` for the reward ``psi(s) . task``: ``T_phi(z, a, task) . task``."""
    return (self.predict(z, actions, task, **kwargs) * task).sum(-1)

method infer_task ​

torch_world.models.TDJEPA.infer_task GitHub

python
infer_task(
    obs: Tensor, rewards: Tensor, ridge: float = 1e-06, project: bool = True
) -> Tensor

Zero-shot task embedding (task_dim,) for the reward rewards (N,) observed at obs (N, ...): the least-squares z = E[psi psi^T]^-1 E[psi r], projected onto the sphere the policies were trained on unless project=False.

Source code in torch_world/models/jepa/_tdjepa.py
python
@torch.no_grad()
def infer_task(self, obs: Tensor, rewards: Tensor, ridge: float = 1e-6, project: bool = True) -> Tensor:
    """Zero-shot task embedding ``(task_dim,)`` for the reward ``rewards`` ``(N,)`` observed at ``obs`` ``(N,
    ...)``: the least-squares ``z = E[psi psi^T]^-1 E[psi r]``, projected onto the sphere the policies were
    trained on unless ``project=False``."""
    psi = self._psi_batched(obs)
    cov = psi.T @ psi / len(psi)
    z = torch.linalg.solve(cov + ridge * torch.eye(len(cov), device=cov.device), psi.T @ rewards.to(psi) / len(psi))
    return sphere(z) if project else z

method goal_task ​

torch_world.models.TDJEPA.goal_task GitHub

python
goal_task(
    goals: Tensor, obs: Tensor | None = None, ridge: float = 1e-06
) -> Tensor

Task embeddings (B, task_dim) for reaching goal observations (B, ...): psi(goal), whitened by E[psi psi^T]^-1 over obs (N, ...) when given (the regression of a reward that is one at the goal), and projected onto the sphere.

Source code in torch_world/models/jepa/_tdjepa.py
python
@torch.no_grad()
def goal_task(self, goals: Tensor, obs: Tensor | None = None, ridge: float = 1e-6) -> Tensor:
    """Task embeddings ``(B, task_dim)`` for reaching goal observations ``(B, ...)``: ``psi(goal)``, whitened by
    ``E[psi psi^T]^-1`` over ``obs`` ``(N, ...)`` when given (the regression of a reward that is one at the goal),
    and projected onto the sphere."""
    z = self._psi_batched(goals)
    if obs is not None:
        psi = self._psi_batched(obs)
        cov = psi.T @ psi / len(psi) + ridge * torch.eye(psi.size(1), device=psi.device)
        z = torch.linalg.solve(cov, z.T).T
    return sphere(z)

method controller ​

torch_world.models.TDJEPA.controller GitHub

python
controller(task: Tensor) -> Callable[[Tensor], Tensor]

Closed-loop policy observation (B, ...) -> action (B, action_dim) for tasks (B, task_dim) or one task (task_dim,) shared by the batch; it runs the actor's mean on the model's device.

Source code in torch_world/models/jepa/_tdjepa.py
python
def controller(self, task: Tensor) -> Callable[[Tensor], Tensor]:
    """Closed-loop policy ``observation (B, ...) -> action (B, action_dim)`` for tasks ``(B, task_dim)`` or one
    task ``(task_dim,)`` shared by the batch; it runs the actor's mean on the model's device."""
    device = next(self.parameters()).device

    @torch.no_grad()
    def act(obs: Tensor) -> Tensor:
        z = self.phi(obs.to(device))
        return self.policy(z, task.to(device).expand(len(z), -1)).to(obs.device)

    return act

method orthonormality ​

torch_world.models.TDJEPA.orthonormality GitHub

python
orthonormality(x: Tensor) -> Tensor

mean_{i != j} (x_i . x_j)^2 / 2 - mean_i x_i . x_i over a batch (B, d): pushes E[x x^T] to I.

Source code in torch_world/models/jepa/_tdjepa.py
python
@staticmethod
def orthonormality(x: Tensor) -> Tensor:
    """``mean_{i != j} (x_i . x_j)^2 / 2 - mean_i x_i . x_i`` over a batch ``(B, d)``: pushes ``E[x x^T]`` to
    ``I``."""
    cov = x @ x.T
    off = ~torch.eye(len(x), dtype=torch.bool, device=x.device)
    return 0.5 * cov[off].square().mean() - cov.diagonal().mean()

method forward ​

torch_world.models.TDJEPA.forward GitHub

python
forward(
    pixels: Tensor, actions: Tensor, goals: Tensor | None = None
) -> dict[str, Tensor]

Transitions pixels (B, 2, ...) (s and s') and actions (B, 2, action_dim) (only actions[:, 0], taken at s, is used), as windows of 2 from TrajectoryDataset. Goal tasks are psi of goals (B, ...), by default the batch's next observations shuffled.

Source code in torch_world/models/jepa/_tdjepa.py
python
def forward(self, pixels: Tensor, actions: Tensor, goals: Tensor | None = None) -> dict[str, Tensor]:
    """Transitions ``pixels`` ``(B, 2, ...)`` (``s`` and ``s'``) and ``actions`` ``(B, 2, action_dim)`` (only
    ``actions[:, 0]``, taken at ``s``, is used), as windows of 2 from ``TrajectoryDataset``. Goal tasks are
    ``psi`` of ``goals`` ``(B, ...)``, by default the batch's next observations shuffled."""
    obs, action, next_obs = pixels[:, 0], actions[:, 0], pixels[:, 1]
    with torch.no_grad():
        z = self.sample_tasks(len(obs), next_obs[torch.randperm(len(obs))] if goals is None else goals)
        next_phi, next_psi = self.phi(next_obs, target=True), self.psi(next_obs, target=True)
        next_action = self.policy(next_phi, z, explore=True)
        phi_target = next_psi + self.discount * self.targets["phi_predictor"](next_phi, next_action, z).mean(0)
        psi_target = next_phi + self.discount * self.targets["psi_predictor"](next_psi, next_action, z).mean(0)
    phi, psi = self.phi(obs), self.psi(obs)
    td_phi = 0.5 * (self.phi_predictor(phi, action, z) - phi_target).square().sum(-1).mean()
    td_psi = 0.5 * (self.psi_predictor(psi, action, z) - psi_target).square().sum(-1).mean()
    ortho = self.orthonormality(phi) + self.orthonormality(psi)

    state = phi.detach()
    actor = -self.value(state, self.policy(state, z, explore=True), z, detach=True).mean()
    loss = td_phi + td_psi + self.lamb * ortho + actor
    return {"loss": loss, "td_phi_loss": td_phi, "td_psi_loss": td_psi, "ortho_loss": ortho, "actor_loss": actor}

function drq_encoder ​

torch_world.models.jepa.drq_encoder GitHub

python
drq_encoder(
    out_dim: int,
    hidden_layers: int = 0,
    hidden_dim: int = 256,
    img_size: int = 64,
    channels: int = 3,
    pad: int = 2,
) -> nn.Sequential

TD-JEPA's pixel encoder: DrQ-v2's convolutions (one 3x3 at stride 2, three at stride 1, 32 channels, ReLU) on images (N, C, H, W) in [0, 1], random shifts of up to pad pixels in training, then an MLP with hidden_layers ReLU layers to (N, out_dim). hidden_layers=0 is the paper's pixel state encoder phi (a linear map), hidden_layers=2 its task encoder psi.

Source code in torch_world/models/jepa/_tdjepa.py
python
def drq_encoder(
    out_dim: int, hidden_layers: int = 0, hidden_dim: int = 256, img_size: int = 64, channels: int = 3, pad: int = 2
) -> nn.Sequential:
    """TD-JEPA's pixel encoder: DrQ-v2's convolutions (one 3x3 at stride 2, three at stride 1, 32 channels, ReLU) on
    images ``(N, C, H, W)`` in ``[0, 1]``, random shifts of up to ``pad`` pixels in training, then an MLP with
    ``hidden_layers`` ReLU layers to ``(N, out_dim)``. ``hidden_layers=0`` is the paper's pixel state encoder ``phi``
    (a linear map), ``hidden_layers=2`` its task encoder ``psi``."""
    side = (img_size - 3) // 2 + 1 - 6
    convs = [nn.Conv2d(channels, 32, 3, stride=2), nn.ReLU()]
    for _ in range(3):
        convs += [nn.Conv2d(32, 32, 3), nn.ReLU()]
    return nn.Sequential(
        _TrainShift(pad), _Center(), *convs, nn.Flatten(), _mlp(32 * side * side, hidden_dim, hidden_layers, out_dim)
    )

class CausalJEPA ​

torch_world.models.CausalJEPA GitHub

python
CausalJEPA(
    encoder: nn.Module,
    action_dim: int,
    slot_dim: int = 128,
    history: int = 3,
    num_preds: int = 1,
    max_masked: int = 2,
    proprio_dim: int | None = None,
    depth: int = 6,
    num_heads: int = 16,
    head_dim: int = 64,
    mlp_dim: int = 2048,
    dropout: float = 0.1,
    match: bool = True,
)

Causal-JEPA (C-JEPA): a masked object-level JEPA world model, whose predictor must recover hidden objects from the others.

A frozen object-centric encoder turns every frame into N slots. Each timestep becomes N object tokens plus an action token (and a proprioception token), and a bidirectional transformer with no positional encoding along the object axis reads history steps and predicts the next num_preds. Training masks the history of up to max_masked random objects after the first step: their tokens become queries phi(z^i_{t0}) + m + e_tau built from the first-step slot (the identity anchor), a learned mask token and the time embedding, the same queries that stand for every future token. The predictor can only recover a masked object from the other objects and the actions, a latent intervention that makes interactions necessary to learn:

loss = sum_{masked i, 0 < tau <= t} ||z^_tau^i - z_tau^i||^2 + sum_{i, tau > t} ||z^_tau^i - z_tau^i||^2.

At test time the history is fully visible. Planning minimizes the distance between the final predicted slots and the goal's slots, after matching them (Hungarian, as in the reference), with CEM.

Nam et al., "Causal-JEPA: Learning World Models through Object-Level Latent Masking", 2026. Paper: https://arxiv.org/abs/2602.11389 Code: https://github.com/galilai-group/cjepa

Parameters

NameTypeDescriptionDefault
encodernn.Modulefrozen module mapping videos (B, T, C, H, W) to slots (B, T, num_slots, slot_dim), such as a trained SlotEncoder (VideoSAUR on DINOv2 features in the paper). Its weights are frozen here.required
action_dimintdimension of one action, times the frameskip when actions are stacked.required
max_maskedinteach training sample masks a number of objects drawn uniformly from 0..max_masked.2
proprio_dim`intNone`adds a proprioception token per step, predicted for the future like the objects.
matchboolmatch predicted and goal slots by the cheapest permutation in cost.True

Members

MemberDescription
encode(B, T, C, H, W) to frozen slots (B, T, num_slots, slot_dim).
tokensSlots (B, T, S, D), actions (B, T, A) and proprioception (B, T, P) to nodes (B, T, S + 1 [+ 1], D): the objects, the proprioception, then the action.
completeRun the predictor on history nodes x (B, T, N, D) (T <= history) whose nodes masked (B, N) are hidden after the first step, plus steps future steps (num_preds by default) of queries; returns predictions for all (B, T + steps, N, D).
predictFrom slots z (B, T, S, D) and their actions (B, T, A), the slots (B, T + num_preds, S, D): the history, where objects masked (B, S) are inferred after the first step, then the future.
rolloutUnroll from T0 context slots (B, T0, S, D) with T >= T0 actions; returns (B, T + 1, S, D).
costMean squared distance between the final slots of each rollout (B, T, S, D) and the goal's slots (B, S, D), under the cheapest one-to-one matching of slots when match.
forwardobs is pixels (B, history + num_preds, C, H, W) or pre-extracted slots (B, history + num_preds, S, D), with actions (B, history + num_preds, A).
Source code in torch_world/models/jepa/_causaljepa.py
python
class CausalJEPA(WorldModel):
    """Causal-JEPA (C-JEPA): a masked object-level JEPA world model, whose predictor must recover hidden objects from
    the others.

    A frozen object-centric encoder turns every frame into ``N`` slots. Each timestep becomes ``N`` object tokens plus
    an action token (and a proprioception token), and a bidirectional transformer with no positional encoding along
    the object axis reads ``history`` steps and predicts the next ``num_preds``. Training masks the history of up to
    ``max_masked`` random objects after the first step: their tokens become queries
    ``phi(z^i_{t0}) + m + e_tau`` built from the first-step slot (the identity anchor), a learned mask token and the
    time embedding, the same queries that stand for every future token. The predictor can only recover a masked object
    from the other objects and the actions, a latent intervention that makes interactions necessary to learn:

    ``loss = sum_{masked i, 0 < tau <= t} ||z^_tau^i - z_tau^i||^2 + sum_{i, tau > t} ||z^_tau^i - z_tau^i||^2``.

    At test time the history is fully visible. Planning minimizes the distance between the final predicted slots and
    the goal's slots, after matching them (Hungarian, as in the reference), with CEM.

    Nam et al., "Causal-JEPA: Learning World Models through Object-Level Latent Masking", 2026.
    Paper: https://arxiv.org/abs/2602.11389
    Code: https://github.com/galilai-group/cjepa

    Args:
        encoder: frozen module mapping videos ``(B, T, C, H, W)`` to slots ``(B, T, num_slots, slot_dim)``, such as a
            trained ``SlotEncoder`` (VideoSAUR on DINOv2 features in the paper). Its weights are frozen here.
        action_dim: dimension of one action, times the frameskip when actions are stacked.
        max_masked: each training sample masks a number of objects drawn uniformly from ``0..max_masked``.
        proprio_dim: adds a proprioception token per step, predicted for the future like the objects.
        match: match predicted and goal slots by the cheapest permutation in ``cost``.
    """

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        slot_dim: int = 128,
        history: int = 3,
        num_preds: int = 1,
        max_masked: int = 2,
        proprio_dim: int | None = None,
        depth: int = 6,
        num_heads: int = 16,
        head_dim: int = 64,
        mlp_dim: int = 2048,
        dropout: float = 0.1,
        match: bool = True,
    ):
        super().__init__()
        self.history, self.num_preds, self.max_masked, self.match = history, num_preds, max_masked, match
        self.encoder = encoder.requires_grad_(False)
        self.action_encoder = nn.Linear(action_dim, slot_dim)
        self.proprio_encoder = nn.Linear(proprio_dim, slot_dim) if proprio_dim else None
        self.mask_token = nn.Parameter(torch.zeros(1, 1, 1, slot_dim))
        nn.init.trunc_normal_(self.mask_token, std=0.02)
        self.time_embed = nn.Parameter(torch.randn(1, history + num_preds, 1, slot_dim))
        self.anchor_proj = nn.Linear(slot_dim, slot_dim)
        self.predictor = Transformer(
            slot_dim, depth, num_heads, mlp_dim=mlp_dim, head_dim=head_dim, dropout=dropout
        )  # fmt: skip
        self.out_proj = nn.Linear(slot_dim, slot_dim)

    @torch.no_grad()
    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to frozen slots ``(B, T, num_slots, slot_dim)``."""
        return self.encoder(pixels)

    def tokens(self, z: Tensor, actions: Tensor, proprio: Tensor | None = None) -> Tensor:
        """Slots ``(B, T, S, D)``, actions ``(B, T, A)`` and proprioception ``(B, T, P)`` to nodes
        ``(B, T, S + 1 [+ 1], D)``: the objects, the proprioception, then the action."""
        extra = [] if self.proprio_encoder is None else [self.proprio_encoder(proprio)[:, :, None]]
        return torch.cat([z, *extra, self.action_encoder(actions)[:, :, None]], dim=2)

    def complete(self, x: Tensor, masked: Tensor | None = None, steps: int | None = None) -> Tensor:
        """Run the predictor on history nodes ``x`` ``(B, T, N, D)`` (``T <= history``) whose nodes ``masked``
        ``(B, N)`` are hidden after the first step, plus ``steps`` future steps (``num_preds`` by default) of queries;
        returns predictions for all ``(B, T + steps, N, D)``."""
        (B, T, N, D), P = x.shape, steps or self.num_preds
        pos = self.time_embed[:, self.history - T : self.history + P]
        query = self.mask_token + self.anchor_proj(x[:, :1])
        hist = x + pos[:, :T]
        if masked is not None:
            hidden = torch.cat([masked.new_zeros(B, 1, N), masked[:, None].expand(B, T - 1, N)], 1)
            hist = torch.where(hidden[..., None], query + pos[:, :T], hist)
        seq = torch.cat([hist, (query + pos[:, T:]).expand(B, P, N, D)], dim=1)
        return self.out_proj(self.predictor(seq.flatten(1, 2))).unflatten(1, (T + P, N))

    def predict(
        self, z: Tensor, actions: Tensor, proprio: Tensor | None = None, masked: Tensor | None = None
    ) -> Tensor:
        """From slots ``z`` ``(B, T, S, D)`` and their actions ``(B, T, A)``, the slots ``(B, T + num_preds, S, D)``:
        the history, where objects ``masked`` ``(B, S)`` are inferred after the first step, then the future."""
        proprio = None if proprio is None else proprio[:, -self.history :]
        x = self.tokens(z[:, -self.history :], actions[:, -self.history :], proprio)
        if masked is not None:
            masked = F.pad(masked, (0, x.size(2) - z.size(2)))
        return self.complete(x, masked)[:, :, : z.size(2)]

    def rollout(self, z: Tensor, actions: Tensor, proprio: Tensor | None = None) -> Tensor:
        """Unroll from ``T0`` context slots ``(B, T0, S, D)`` with ``T >= T0`` actions; returns ``(B, T + 1, S, D)``.

        Each step predicts the next frame (with its proprioception token) from the last ``history`` frames.
        ``proprio`` ``(B, T0, P)`` describes the context frames.
        """
        S, T0 = z.size(2), z.size(1)
        x = self.tokens(z, actions[:, :T0], proprio)
        for t in range(T0, actions.size(1) + 1):
            nxt = self.complete(x[:, -self.history :], steps=1)[:, -1]
            if t < actions.size(1):
                nxt = torch.cat([nxt[:, :-1], self.action_encoder(actions[:, t])[:, None]], dim=1)
            x = torch.cat([x, nxt[:, None]], dim=1)
        return torch.cat([z, x[:, T0:, :S]], dim=1)

    def cost(self, z: Tensor, goal: Tensor) -> Tensor:
        """Mean squared distance between the final slots of each rollout ``(B, T, S, D)`` and the goal's slots
        ``(B, S, D)``, under the cheapest one-to-one matching of slots when ``match``."""
        if not self.match:
            return (z[:, -1] - goal).square().flatten(1).mean(1)
        return slot_distances(z[:, -1], goal)[0]

    def forward(self, obs: Tensor, actions: Tensor, proprio: Tensor | None = None) -> dict[str, Tensor]:
        """``obs`` is pixels ``(B, history + num_preds, C, H, W)`` or pre-extracted slots ``(B, history + num_preds,
        S, D)``, with ``actions`` ``(B, history + num_preds, A)``."""
        z = obs if obs.dim() == 4 else self.encode(obs)
        (B, _, S, _), H = z.shape, self.history
        x = self.tokens(z, actions, proprio)
        count = torch.randint(0, self.max_masked + 1, (B, 1), device=z.device)
        masked = torch.rand(B, S, device=z.device).argsort(1).argsort(1) < count  # ``count`` random objects
        pred = self.complete(x[:, :H], F.pad(masked, (0, x.size(2) - S)))
        err = (pred[:, 1:H, :S] - z[:, 1:H]).square().mean(-1)  # (B, H - 1, S)
        hidden = masked[:, None].expand_as(err)
        history_loss = (err * hidden).sum() / hidden.sum().clamp(min=1)
        future_loss = (pred[:, H:, :S] - z[:, H:]).square().mean()
        out = {"history_loss": history_loss, "future_loss": future_loss}
        if self.proprio_encoder is not None:
            out["proprio_loss"] = (pred[:, H:, S] - x[:, H:, S].detach()).square().mean()
        return {"loss": sum(out.values()), **out}

method encode ​

torch_world.models.CausalJEPA.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to frozen slots (B, T, num_slots, slot_dim).

Source code in torch_world/models/jepa/_causaljepa.py
python
@torch.no_grad()
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to frozen slots ``(B, T, num_slots, slot_dim)``."""
    return self.encoder(pixels)

method tokens ​

torch_world.models.CausalJEPA.tokens GitHub

python
tokens(z: Tensor, actions: Tensor, proprio: Tensor | None = None) -> Tensor

Slots (B, T, S, D), actions (B, T, A) and proprioception (B, T, P) to nodes (B, T, S + 1 [+ 1], D): the objects, the proprioception, then the action.

Source code in torch_world/models/jepa/_causaljepa.py
python
def tokens(self, z: Tensor, actions: Tensor, proprio: Tensor | None = None) -> Tensor:
    """Slots ``(B, T, S, D)``, actions ``(B, T, A)`` and proprioception ``(B, T, P)`` to nodes
    ``(B, T, S + 1 [+ 1], D)``: the objects, the proprioception, then the action."""
    extra = [] if self.proprio_encoder is None else [self.proprio_encoder(proprio)[:, :, None]]
    return torch.cat([z, *extra, self.action_encoder(actions)[:, :, None]], dim=2)

method complete ​

torch_world.models.CausalJEPA.complete GitHub

python
complete(
    x: Tensor, masked: Tensor | None = None, steps: int | None = None
) -> Tensor

Run the predictor on history nodes x (B, T, N, D) (T <= history) whose nodes masked(B, N) are hidden after the first step, plus steps future steps (num_preds by default) of queries; returns predictions for all (B, T + steps, N, D).

Source code in torch_world/models/jepa/_causaljepa.py
python
def complete(self, x: Tensor, masked: Tensor | None = None, steps: int | None = None) -> Tensor:
    """Run the predictor on history nodes ``x`` ``(B, T, N, D)`` (``T <= history``) whose nodes ``masked``
    ``(B, N)`` are hidden after the first step, plus ``steps`` future steps (``num_preds`` by default) of queries;
    returns predictions for all ``(B, T + steps, N, D)``."""
    (B, T, N, D), P = x.shape, steps or self.num_preds
    pos = self.time_embed[:, self.history - T : self.history + P]
    query = self.mask_token + self.anchor_proj(x[:, :1])
    hist = x + pos[:, :T]
    if masked is not None:
        hidden = torch.cat([masked.new_zeros(B, 1, N), masked[:, None].expand(B, T - 1, N)], 1)
        hist = torch.where(hidden[..., None], query + pos[:, :T], hist)
    seq = torch.cat([hist, (query + pos[:, T:]).expand(B, P, N, D)], dim=1)
    return self.out_proj(self.predictor(seq.flatten(1, 2))).unflatten(1, (T + P, N))

method predict ​

torch_world.models.CausalJEPA.predict GitHub

python
predict(
    z: Tensor,
    actions: Tensor,
    proprio: Tensor | None = None,
    masked: Tensor | None = None,
) -> Tensor

From slots z (B, T, S, D) and their actions (B, T, A), the slots (B, T + num_preds, S, D): the history, where objects masked (B, S) are inferred after the first step, then the future.

Source code in torch_world/models/jepa/_causaljepa.py
python
def predict(
    self, z: Tensor, actions: Tensor, proprio: Tensor | None = None, masked: Tensor | None = None
) -> Tensor:
    """From slots ``z`` ``(B, T, S, D)`` and their actions ``(B, T, A)``, the slots ``(B, T + num_preds, S, D)``:
    the history, where objects ``masked`` ``(B, S)`` are inferred after the first step, then the future."""
    proprio = None if proprio is None else proprio[:, -self.history :]
    x = self.tokens(z[:, -self.history :], actions[:, -self.history :], proprio)
    if masked is not None:
        masked = F.pad(masked, (0, x.size(2) - z.size(2)))
    return self.complete(x, masked)[:, :, : z.size(2)]

method rollout ​

torch_world.models.CausalJEPA.rollout GitHub

python
rollout(
    z: Tensor, actions: Tensor, proprio: Tensor | None = None
) -> Tensor

Unroll from T0 context slots (B, T0, S, D) with T >= T0 actions; returns (B, T + 1, S, D).

Each step predicts the next frame (with its proprioception token) from the last history frames. proprio (B, T0, P) describes the context frames.

Source code in torch_world/models/jepa/_causaljepa.py
python
def rollout(self, z: Tensor, actions: Tensor, proprio: Tensor | None = None) -> Tensor:
    """Unroll from ``T0`` context slots ``(B, T0, S, D)`` with ``T >= T0`` actions; returns ``(B, T + 1, S, D)``.

    Each step predicts the next frame (with its proprioception token) from the last ``history`` frames.
    ``proprio`` ``(B, T0, P)`` describes the context frames.
    """
    S, T0 = z.size(2), z.size(1)
    x = self.tokens(z, actions[:, :T0], proprio)
    for t in range(T0, actions.size(1) + 1):
        nxt = self.complete(x[:, -self.history :], steps=1)[:, -1]
        if t < actions.size(1):
            nxt = torch.cat([nxt[:, :-1], self.action_encoder(actions[:, t])[:, None]], dim=1)
        x = torch.cat([x, nxt[:, None]], dim=1)
    return torch.cat([z, x[:, T0:, :S]], dim=1)

method cost ​

torch_world.models.CausalJEPA.cost GitHub

python
cost(z: Tensor, goal: Tensor) -> Tensor

Mean squared distance between the final slots of each rollout (B, T, S, D) and the goal's slots (B, S, D), under the cheapest one-to-one matching of slots when match.

Source code in torch_world/models/jepa/_causaljepa.py
python
def cost(self, z: Tensor, goal: Tensor) -> Tensor:
    """Mean squared distance between the final slots of each rollout ``(B, T, S, D)`` and the goal's slots
    ``(B, S, D)``, under the cheapest one-to-one matching of slots when ``match``."""
    if not self.match:
        return (z[:, -1] - goal).square().flatten(1).mean(1)
    return slot_distances(z[:, -1], goal)[0]

method forward ​

torch_world.models.CausalJEPA.forward GitHub

python
forward(
    obs: Tensor, actions: Tensor, proprio: Tensor | None = None
) -> dict[str, Tensor]

obs is pixels (B, history + num_preds, C, H, W) or pre-extracted slots (B, history + num_preds, S, D), with actions (B, history + num_preds, A).

Source code in torch_world/models/jepa/_causaljepa.py
python
def forward(self, obs: Tensor, actions: Tensor, proprio: Tensor | None = None) -> dict[str, Tensor]:
    """``obs`` is pixels ``(B, history + num_preds, C, H, W)`` or pre-extracted slots ``(B, history + num_preds,
    S, D)``, with ``actions`` ``(B, history + num_preds, A)``."""
    z = obs if obs.dim() == 4 else self.encode(obs)
    (B, _, S, _), H = z.shape, self.history
    x = self.tokens(z, actions, proprio)
    count = torch.randint(0, self.max_masked + 1, (B, 1), device=z.device)
    masked = torch.rand(B, S, device=z.device).argsort(1).argsort(1) < count  # ``count`` random objects
    pred = self.complete(x[:, :H], F.pad(masked, (0, x.size(2) - S)))
    err = (pred[:, 1:H, :S] - z[:, 1:H]).square().mean(-1)  # (B, H - 1, S)
    hidden = masked[:, None].expand_as(err)
    history_loss = (err * hidden).sum() / hidden.sum().clamp(min=1)
    future_loss = (pred[:, H:, :S] - z[:, H:]).square().mean()
    out = {"history_loss": history_loss, "future_loss": future_loss}
    if self.proprio_encoder is not None:
        out["proprio_loss"] = (pred[:, H:, S] - x[:, H:, S].detach()).square().mean()
    return {"loss": sum(out.values()), **out}

class SlotEncoder ​

torch_world.models.SlotEncoder GitHub

python
SlotEncoder(
    img_size: int = 64,
    num_slots: int = 5,
    slot_dim: int = 64,
    channels: int = 64,
    iters: int = 3,
    in_channels: int = 3,
    track: str | None = "match",
)

Object-centric image encoder: a CNN, slot attention from learned queries and a spatial-broadcast decoder.

forward maps images (N, C, H, W) to slots (N, num_slots, slot_dim) and videos (B, T, C, H, W) to (B, T, num_slots, slot_dim). Every frame starts from the learned queries. track keeps each object in the same slot through a video: "match" reorders the slots of frame t to best match frame t - 1, and "propagate" starts frame t from the slots of frame t - 1, as SAVi and VideoSAUR do. forward(pixels, reconstruct=True) instead returns the pixel reconstruction loss that trains it: each slot is broadcast on a grid, decoded to RGB and a mask logit, and the masks are softmaxed over slots.

Watters et al., "Spatial Broadcast Decoder", 2019. Paper: https://arxiv.org/abs/1901.07017

Parameters

NameTypeDescriptionDefault
img_sizeintside of the square input images, a multiple of 8.64
channelsintwidth of the CNN and the decoder.64

Members

MemberDescription
featuresImages (N, C, H, W) to position-aware features (N, H/2 * W/2, slot_dim).
slotsImages (N, C, H, W) to slots (N, S, D) and feature attention (N, S, P), from init or the learned queries.
decodeSlots (N, S, D) to images (N, C, H, W) and slot masks (N, S, 1, H, W) that sum to one.
Source code in torch_world/models/jepa/_causaljepa.py
python
class SlotEncoder(nn.Module):
    """Object-centric image encoder: a CNN, slot attention from learned queries and a spatial-broadcast decoder.

    ``forward`` maps images ``(N, C, H, W)`` to slots ``(N, num_slots, slot_dim)`` and videos ``(B, T, C, H, W)`` to
    ``(B, T, num_slots, slot_dim)``. Every frame starts from the learned queries. ``track`` keeps each object in the same
    slot through a video: ``"match"`` reorders the slots of frame ``t`` to best match frame ``t - 1``, and
    ``"propagate"`` starts frame ``t`` from the slots of frame ``t - 1``, as SAVi and VideoSAUR do.
    ``forward(pixels, reconstruct=True)`` instead returns the pixel reconstruction loss that trains it: each slot is
    broadcast on a grid, decoded to RGB and a mask logit, and the masks are softmaxed over slots.

    Watters et al., "Spatial Broadcast Decoder", 2019. Paper: https://arxiv.org/abs/1901.07017

    Args:
        img_size: side of the square input images, a multiple of 8.
        channels: width of the CNN and the decoder.
    """

    def __init__(
        self,
        img_size: int = 64,
        num_slots: int = 5,
        slot_dim: int = 64,
        channels: int = 64,
        iters: int = 3,
        in_channels: int = 3,
        track: str | None = "match",
    ):
        super().__init__()
        if img_size % 8:
            raise ValueError(f"img_size must be a multiple of 8, not {img_size}")
        if track not in (None, "match", "propagate"):
            raise ValueError(f"track must be None, 'match' or 'propagate', not {track!r}")
        self.img_size, self.num_slots, self.slot_dim, self.track = img_size, num_slots, slot_dim, track
        c = channels
        self.cnn = nn.Sequential(
            nn.Conv2d(in_channels, c, 5, 2, 2), nn.ReLU(),
            *(m for _ in range(3) for m in (nn.Conv2d(c, c, 5, 1, 2), nn.ReLU())),
        )  # fmt: skip
        self.enc_pos = nn.Linear(4, c)
        self.enc_mlp = nn.Sequential(nn.LayerNorm(c), MLP([c, slot_dim, slot_dim], act=nn.ReLU))
        self.queries = nn.Parameter(torch.randn(1, num_slots, slot_dim) * slot_dim**-0.5)
        self.slot_attention = SlotAttention(slot_dim, iters)
        self.dec_pos = nn.Linear(4, slot_dim)
        self.decoder = nn.Sequential(
            *(m for i in range(3) for m in (nn.ConvTranspose2d(slot_dim if i == 0 else c, c, 5, 2, 2, 1), nn.ReLU())),
            nn.Conv2d(c, c, 5, 1, 2), nn.ReLU(), nn.Conv2d(c, in_channels + 1, 3, 1, 1),
        )  # fmt: skip

    def features(self, x: Tensor) -> Tensor:
        """Images ``(N, C, H, W)`` to position-aware features ``(N, H/2 * W/2, slot_dim)``."""
        h = self.cnn(x)
        h = h.flatten(2).transpose(1, 2) + self.enc_pos(_grid(*h.shape[-2:], x.device))
        return self.enc_mlp(h)

    def slots(self, x: Tensor, init: Tensor | None = None) -> tuple[Tensor, Tensor]:
        """Images ``(N, C, H, W)`` to slots ``(N, S, D)`` and feature attention ``(N, S, P)``, from ``init`` or the
        learned queries."""
        init = self.queries.expand(x.size(0), -1, -1) if init is None else init
        return self.slot_attention(self.features(x), init)

    def decode(self, slots: Tensor) -> tuple[Tensor, Tensor]:
        """Slots ``(N, S, D)`` to images ``(N, C, H, W)`` and slot masks ``(N, S, 1, H, W)`` that sum to one."""
        g = self.img_size // 8
        h = slots.flatten(0, 1)[:, :, None, None].expand(-1, -1, g, g)
        h = h + self.dec_pos(_grid(g, g, slots.device)).T.view(1, -1, g, g)
        out = self.decoder(h).unflatten(0, slots.shape[:2])
        rgb, masks = out[:, :, :-1], out[:, :, -1:].softmax(1)
        return (rgb * masks).sum(1), masks

    def forward(self, pixels: Tensor, reconstruct: bool = False) -> Tensor | dict[str, Tensor]:
        if reconstruct:
            x = pixels.flatten(0, pixels.dim() - 4)
            recon, masks = self.decode(self.slots(x)[0])
            loss = (recon - x).square().mean()
            return {"loss": loss, "recon_loss": loss, "recon": recon, "masks": masks}
        if pixels.dim() == 4:
            return self.slots(pixels)[0]
        if self.track != "propagate":
            out = list(self.slots(pixels.flatten(0, 1))[0].unflatten(0, pixels.shape[:2]).unbind(1))
            for t in range(1, len(out) if self.track == "match" else 0):
                out[t] = slot_distances(out[t], out[t - 1])[1]
            return torch.stack(out, 1)
        out = [self.slots(pixels[:, 0])[0]]
        for t in range(1, pixels.size(1)):
            out.append(self.slots(pixels[:, t], out[-1])[0])
        return torch.stack(out, 1)

method features ​

torch_world.models.SlotEncoder.features GitHub

python
features(x: Tensor) -> Tensor

Images (N, C, H, W) to position-aware features (N, H/2 * W/2, slot_dim).

Source code in torch_world/models/jepa/_causaljepa.py
python
def features(self, x: Tensor) -> Tensor:
    """Images ``(N, C, H, W)`` to position-aware features ``(N, H/2 * W/2, slot_dim)``."""
    h = self.cnn(x)
    h = h.flatten(2).transpose(1, 2) + self.enc_pos(_grid(*h.shape[-2:], x.device))
    return self.enc_mlp(h)

method slots ​

torch_world.models.SlotEncoder.slots GitHub

python
slots(x: Tensor, init: Tensor | None = None) -> tuple[Tensor, Tensor]

Images (N, C, H, W) to slots (N, S, D) and feature attention (N, S, P), from init or the learned queries.

Source code in torch_world/models/jepa/_causaljepa.py
python
def slots(self, x: Tensor, init: Tensor | None = None) -> tuple[Tensor, Tensor]:
    """Images ``(N, C, H, W)`` to slots ``(N, S, D)`` and feature attention ``(N, S, P)``, from ``init`` or the
    learned queries."""
    init = self.queries.expand(x.size(0), -1, -1) if init is None else init
    return self.slot_attention(self.features(x), init)

method decode ​

torch_world.models.SlotEncoder.decode GitHub

python
decode(slots: Tensor) -> tuple[Tensor, Tensor]

Slots (N, S, D) to images (N, C, H, W) and slot masks (N, S, 1, H, W) that sum to one.

Source code in torch_world/models/jepa/_causaljepa.py
python
def decode(self, slots: Tensor) -> tuple[Tensor, Tensor]:
    """Slots ``(N, S, D)`` to images ``(N, C, H, W)`` and slot masks ``(N, S, 1, H, W)`` that sum to one."""
    g = self.img_size // 8
    h = slots.flatten(0, 1)[:, :, None, None].expand(-1, -1, g, g)
    h = h + self.dec_pos(_grid(g, g, slots.device)).T.view(1, -1, g, g)
    out = self.decoder(h).unflatten(0, slots.shape[:2])
    rgb, masks = out[:, :, :-1], out[:, :, -1:].softmax(1)
    return (rgb * masks).sum(1), masks

class CFJEPA ​

torch_world.models.CFJEPA GitHub

python
CFJEPA(
    encoder: nn.Module,
    action_dim: int,
    embed_dim: int = 192,
    ctrl_dim: int = 128,
    history: int = 3,
    depth: int = 6,
    unctrl_depth: int | None = None,
    num_heads: int = 16,
    head_dim: int = 64,
    mlp_dim: int = 2048,
    proj_dim: int = 2048,
    inv_dim: int = 512,
    dropout: float = 0.1,
    alpha: float = 3.0,
    beta: float = 1.0,
    lamb: float = 0.09,
    reversal: float = 1.0,
    sigreg: SIGReg | None = None,
)

CF-JEPA: a LeWM-style JEPA world model whose latent is factored into a controllable and an uncontrollable part, so that distractors which move on their own stay out of the part the planner looks at.

Each frame is encoded to one embedding (the encoder's CLS token) and projected, as in LeWM, then split into z = [z^c, z^u] (ctrl_dim and embed_dim - ctrl_dim dims). A causal transformer g, conditioned on the actions through adaLN-zero, predicts the next z^c from z^c alone; a smaller, action-free causal transformer h predicts the next z^u from z^u alone. An inverse model psi([z^c_t, z^c_{t+1}]) must recover the action, so z^c holds what the agent controls; an adversary phi([z^u_t, z^u_{t+1}]) also tries to, behind a gradient reversal layer, so the encoder strips action information from z^u. SIGReg keeps the whole latent from collapsing. Planning compares only z^c with the goal:

loss = ||[g(z^c, a), h(z^u)] - z_{t+1}||^2 + alpha ||psi - a||^2 + beta ||phi(GRL) - a||^2 + lamb * sigreg.

Byrd, Wright and Ha, "CF-JEPA: Improving Robustness of JEPA World Models via Controllability Factorization", 2026. Paper: https://arxiv.org/abs/2610.00727 Code: not released; this follows the paper.

Parameters

NameTypeDescriptionDefault
encodernn.Modulemodule mapping images (N, C, H, W) to embeddings (N, embed_dim) (ViT-tiny CLS in the paper).required
action_dimintdimension of one action, times the frameskip when actions are stacked.required
ctrl_dimintdimensions of the controllable part z^c (128 of 192 in the paper); the rest is z^u.128
unctrl_depth`intNone`depth of the action-free predictor h (half of depth by default).
alphafloatweight of the inverse-dynamics loss on z^c (3 on Two-Room, 10 on Reacher and Cube in the paper).3.0
betafloatweight of the adversarial action loss on z^u.1.0
reversalfloatscale of the reversed gradient that reaches the encoder from the adversary.1.0

Members

MemberDescription
encode(B, T, C, H, W) to (B, T, embed_dim), controllable dims first.
splitz^c and z^u of latents (..., embed_dim).
predictNext latents (B, T, embed_dim): z^c from z^c and the actions, z^u from z^u alone.
costSquared distance between the final z^c of each rollout (B, T, D) and the goal's (B, D).
forwardpixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim).
Source code in torch_world/models/jepa/_cfjepa.py
python
class CFJEPA(WorldModel):
    """CF-JEPA: a LeWM-style JEPA world model whose latent is factored into a controllable and an uncontrollable part,
    so that distractors which move on their own stay out of the part the planner looks at.

    Each frame is encoded to one embedding (the encoder's CLS token) and projected, as in LeWM, then split into
    ``z = [z^c, z^u]`` (``ctrl_dim`` and ``embed_dim - ctrl_dim`` dims). A causal transformer ``g``, conditioned on the
    actions through adaLN-zero, predicts the next ``z^c`` from ``z^c`` alone; a smaller, action-free causal transformer
    ``h`` predicts the next ``z^u`` from ``z^u`` alone. An inverse model ``psi([z^c_t, z^c_{t+1}])`` must recover the
    action, so ``z^c`` holds what the agent controls; an adversary ``phi([z^u_t, z^u_{t+1}])`` also tries to, behind a
    gradient reversal layer, so the encoder strips action information from ``z^u``. SIGReg keeps the whole latent from
    collapsing. Planning compares only ``z^c`` with the goal:

    ``loss = ||[g(z^c, a), h(z^u)] - z_{t+1}||^2 + alpha ||psi - a||^2 + beta ||phi(GRL) - a||^2 + lamb * sigreg``.

    Byrd, Wright and Ha, "CF-JEPA: Improving Robustness of JEPA World Models via Controllability Factorization", 2026.
    Paper: https://arxiv.org/abs/2610.00727
    Code: not released; this follows the paper.

    Args:
        encoder: module mapping images ``(N, C, H, W)`` to embeddings ``(N, embed_dim)`` (ViT-tiny CLS in the paper).
        action_dim: dimension of one action, times the frameskip when actions are stacked.
        ctrl_dim: dimensions of the controllable part ``z^c`` (128 of 192 in the paper); the rest is ``z^u``.
        unctrl_depth: depth of the action-free predictor ``h`` (half of ``depth`` by default).
        alpha: weight of the inverse-dynamics loss on ``z^c`` (3 on Two-Room, 10 on Reacher and Cube in the paper).
        beta: weight of the adversarial action loss on ``z^u``.
        reversal: scale of the reversed gradient that reaches the encoder from the adversary.
    """

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        embed_dim: int = 192,
        ctrl_dim: int = 128,
        history: int = 3,
        depth: int = 6,
        unctrl_depth: int | None = None,
        num_heads: int = 16,
        head_dim: int = 64,
        mlp_dim: int = 2048,
        proj_dim: int = 2048,
        inv_dim: int = 512,
        dropout: float = 0.1,
        alpha: float = 3.0,
        beta: float = 1.0,
        lamb: float = 0.09,
        reversal: float = 1.0,
        sigreg: SIGReg | None = None,
    ):
        super().__init__()
        if not 0 < ctrl_dim < embed_dim:
            raise ValueError(f"ctrl_dim must be in (0, {embed_dim}), not {ctrl_dim}")
        self.history, self.ctrl_dim = history, ctrl_dim
        self.alpha, self.beta, self.lamb, self.reversal = alpha, beta, lamb, reversal
        c, u = ctrl_dim, embed_dim - ctrl_dim
        self.encoder = encoder
        self.projector = MLP([embed_dim, proj_dim, embed_dim], norm=nn.BatchNorm1d)
        self.action_encoder = nn.Sequential(nn.Linear(action_dim, action_dim), MLP([action_dim, 4 * c, c], act=nn.SiLU))
        block = {"num_heads": num_heads, "mlp_dim": mlp_dim, "head_dim": head_dim, "dropout": dropout}
        self.ctrl_pos = nn.Parameter(torch.randn(1, history, c))
        self.ctrl_predictor = Transformer(c, depth, conditional=True, **block)
        self.ctrl_proj = MLP([c, proj_dim, c], norm=nn.BatchNorm1d)
        self.unctrl_pos = nn.Parameter(torch.randn(1, history, u))
        self.unctrl_predictor = Transformer(u, unctrl_depth or max(1, depth // 2), **block)
        self.unctrl_proj = MLP([u, proj_dim, u], norm=nn.BatchNorm1d)
        self.inverse = MLP([2 * c, inv_dim, action_dim])
        self.adversary = MLP([2 * u, inv_dim, action_dim])
        self.sigreg = sigreg or SIGReg()

    def encode(self, pixels: Tensor) -> Tensor:
        """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``, controllable dims first."""
        return self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

    def split(self, z: Tensor) -> tuple[Tensor, Tensor]:
        """``z^c`` and ``z^u`` of latents ``(..., embed_dim)``."""
        return z[..., : self.ctrl_dim], z[..., self.ctrl_dim :]

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        """Next latents ``(B, T, embed_dim)``: ``z^c`` from ``z^c`` and the actions, ``z^u`` from ``z^u`` alone."""
        (B, T), (zc, zu) = z.shape[:2], self.split(z)
        c = self.ctrl_predictor(zc + self.ctrl_pos[:, :T], self.action_encoder(actions), is_causal=True)
        u = self.unctrl_predictor(zu + self.unctrl_pos[:, :T], is_causal=True)
        return torch.cat([self.ctrl_proj(c.flatten(0, 1)), self.unctrl_proj(u.flatten(0, 1))], -1).unflatten(0, (B, T))

    def cost(self, z: Tensor, goal: Tensor) -> Tensor:
        """Squared distance between the final ``z^c`` of each rollout ``(B, T, D)`` and the goal's ``(B, D)``."""
        return (self.split(z[:, -1])[0] - self.split(goal)[0]).square().mean(1)

    def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
        """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``."""
        z, H = self.encode(pixels), self.history
        pred = self.predict(z[:, :H], actions[:, :H])
        mse = (pred - z[:, 1 : H + 1]).square().mean()
        (zc, zu), a = self.split(z[:, : H + 1]), actions[:, :H]
        inverse = (self.inverse(torch.cat([zc[:, :-1], zc[:, 1:]], -1)) - a).square().mean()
        pair = GradientReversal.apply(torch.cat([zu[:, :-1], zu[:, 1:]], -1), self.reversal)
        adversary = (self.adversary(pair) - a).square().mean()
        sigreg = self.sigreg(z.transpose(0, 1))
        loss = mse + self.alpha * inverse + self.beta * adversary + self.lamb * sigreg
        return {
            "loss": loss,
            "pred_loss": mse,
            "inverse_loss": inverse,
            "adversary_loss": adversary,
            "sigreg_loss": sigreg,
        }

method encode ​

torch_world.models.CFJEPA.encode GitHub

python
encode(pixels: Tensor) -> Tensor

(B, T, C, H, W) to (B, T, embed_dim), controllable dims first.

Source code in torch_world/models/jepa/_cfjepa.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """``(B, T, C, H, W)`` to ``(B, T, embed_dim)``, controllable dims first."""
    return self.projector(self.encoder(pixels.flatten(0, 1))).unflatten(0, pixels.shape[:2])

method split ​

torch_world.models.CFJEPA.split GitHub

python
split(z: Tensor) -> tuple[Tensor, Tensor]

z^c and z^u of latents (..., embed_dim).

Source code in torch_world/models/jepa/_cfjepa.py
python
def split(self, z: Tensor) -> tuple[Tensor, Tensor]:
    """``z^c`` and ``z^u`` of latents ``(..., embed_dim)``."""
    return z[..., : self.ctrl_dim], z[..., self.ctrl_dim :]

method predict ​

torch_world.models.CFJEPA.predict GitHub

python
predict(z: Tensor, actions: Tensor) -> Tensor

Next latents (B, T, embed_dim): z^c from z^c and the actions, z^u from z^u alone.

Source code in torch_world/models/jepa/_cfjepa.py
python
def predict(self, z: Tensor, actions: Tensor) -> Tensor:
    """Next latents ``(B, T, embed_dim)``: ``z^c`` from ``z^c`` and the actions, ``z^u`` from ``z^u`` alone."""
    (B, T), (zc, zu) = z.shape[:2], self.split(z)
    c = self.ctrl_predictor(zc + self.ctrl_pos[:, :T], self.action_encoder(actions), is_causal=True)
    u = self.unctrl_predictor(zu + self.unctrl_pos[:, :T], is_causal=True)
    return torch.cat([self.ctrl_proj(c.flatten(0, 1)), self.unctrl_proj(u.flatten(0, 1))], -1).unflatten(0, (B, T))

method cost ​

torch_world.models.CFJEPA.cost GitHub

python
cost(z: Tensor, goal: Tensor) -> Tensor

Squared distance between the final z^c of each rollout (B, T, D) and the goal's (B, D).

Source code in torch_world/models/jepa/_cfjepa.py
python
def cost(self, z: Tensor, goal: Tensor) -> Tensor:
    """Squared distance between the final ``z^c`` of each rollout ``(B, T, D)`` and the goal's ``(B, D)``."""
    return (self.split(z[:, -1])[0] - self.split(goal)[0]).square().mean(1)

method forward ​

torch_world.models.CFJEPA.forward GitHub

python
forward(pixels: Tensor, actions: Tensor) -> dict[str, Tensor]

pixels (B, history + 1, C, H, W) and actions (B, history + 1, action_dim).

Source code in torch_world/models/jepa/_cfjepa.py
python
def forward(self, pixels: Tensor, actions: Tensor) -> dict[str, Tensor]:
    """``pixels`` ``(B, history + 1, C, H, W)`` and ``actions`` ``(B, history + 1, action_dim)``."""
    z, H = self.encode(pixels), self.history
    pred = self.predict(z[:, :H], actions[:, :H])
    mse = (pred - z[:, 1 : H + 1]).square().mean()
    (zc, zu), a = self.split(z[:, : H + 1]), actions[:, :H]
    inverse = (self.inverse(torch.cat([zc[:, :-1], zc[:, 1:]], -1)) - a).square().mean()
    pair = GradientReversal.apply(torch.cat([zu[:, :-1], zu[:, 1:]], -1), self.reversal)
    adversary = (self.adversary(pair) - a).square().mean()
    sigreg = self.sigreg(z.transpose(0, 1))
    loss = mse + self.alpha * inverse + self.beta * adversary + self.lamb * sigreg
    return {
        "loss": loss,
        "pred_loss": mse,
        "inverse_loss": inverse,
        "adversary_loss": adversary,
        "sigreg_loss": sigreg,
    }

class VLAJEPA ​

torch_world.models.VLAJEPA GitHub

python
VLAJEPA(
    vision: nn.Module,
    target_encoder: nn.Module,
    vocab_size: int,
    action_dim: int,
    vision_dim: int,
    target_dim: int,
    num_patches: int = 1,
    *,
    frames: int = 8,
    chunk_size: int = 7,
    latent_tokens: int = 3,
    action_tokens: int = 32,
    state_dim: int = 0,
    dim: int = 256,
    depth: int = 4,
    num_heads: int = 4,
    predictor_dim: int = 256,
    predictor_depth: int = 4,
    predictor_heads: int = 4,
    expert_dim: int = 256,
    expert_depth: int = 4,
    expert_heads: int = 4,
    flow_steps: int = 4,
    flow_repeats: int = 8,
    time_alpha: float = 1.5,
    wm_weight: float = 0.1,
)

VLA-JEPA: a vision-language-action policy whose VLM also drives a latent world model, trained JEPA-style.

A causal VLM reads the current image, the instruction, then two groups of learnable query tokens: one latent-action token per transition (each repeated latent_tokens times) and an embodied-action token (repeated action_tokens times). A frozen target encoder embeds every frame of the clip into world states s_0 .. s_{T-1}; future frames are only regression targets and never reach the VLM. An action-conditioned predictor with frame-causal attention reads the true states s_{<T-1} with the latent-action tokens interleaved per step and predicts s_{1:T} (teacher forcing, L1). A flow-matching action expert, conditioned on the embodied-action tokens and on the flow time through adaLN-zero, denoises the next chunk_size actions:

loss = || v(a_t, t | e) - (a - eps) ||^2 + wm_weight * | P(s_{<T-1}, l) - s_{1:T} |, a_t = (1 - t) eps + t a.

Clips without actions (human video) train the world-model term alone. Inference runs only the VLM and the expert: sample_actions integrates the flow from noise in flow_steps Euler steps. imagine also unrolls the world model from the current state with the latent-action tokens, the futures the VLM expects under the instruction.

The world model is conditioned on the VLM's latent-action tokens, not on robot actions, so this is a WorldActionModel (it outputs actions and predicts their consequences) whose predict and rollout take latent-action tokens (B, T, latent_tokens, dim) in place of actions; action-space planners such as CEM do not apply. The paper's L_WM weight is not given; wm_weight = 0.1 is the released code's.

Sun et al., "VLA-JEPA: Enhancing Vision-Language-Action Model with Latent World Model", 2026. Paper: https://arxiv.org/abs/2602.10098 Code: https://github.com/ginwind/VLA-JEPA

Parameters

NameTypeDescriptionDefault
visionnn.Moduletrainable module mapping images (N, C, H, W) to tokens (N, P, vision_dim) or (N, vision_dim) (Qwen3-VL's SigLIP-2 in the paper).required
target_encodernn.Modulefrozen module mapping images to world-state tokens (N, num_patches, target_dim) or (N, target_dim) (V-JEPA 2 ViT-L in the paper).required
vocab_sizeintsize of the instruction vocabulary; id 0 is padding (WordTokenizer).required
framesintworld states per clip T, so T - 1 latent-action groups (8 in the paper).8
latent_tokensintcopies of each latent-action token (K = 24 / T = 3 in the paper, 8 in the released config).3
action_tokensintcopies of the embodied-action token that conditions the expert (32).32
flow_repeatsintnoise draws per sample in the flow-matching loss (repeated_diffusion_steps, 8).8
time_alphafloatflow times are 1 - Beta(time_alpha, 1), concentrated near noise, as GR00T's head draws them.1.5

Members

MemberDescription
encodeWorld states of frames (B, T, C, H, W) from the frozen target encoder: (B, T, P, target_dim).
contextRun the VLM on images (B, C, H, W) and instructions ids (B, L) (mask is True on words).
predictNext world states (B, T, P, D) from states z (B, T, P, D) and latent-action tokens actions (B, T, latent_tokens, dim); step t sees the tokens of steps <= t only.
predict_futureUnroll the world model from z[:, :1] with latent-action tokens (B, T, K, dim): (B, T, P, D).
velocityAction velocity (B, H, action_dim) at noisy chunks x and flow times t (B,), given the embodied-action tokens cond (B, M, dim) and optional states (B, state_dim).
sample_actionsAction chunk (B, chunk_size, action_dim) for images (B, C, H, W) and instructions (B, L).
imagineAn action chunk and the world states the VLM expects under the instruction, (B, frames, P, D).
forwardpixels (B, T, C, H, W) with T <= frames: the VLM sees pixels[:, 0] and the target encoder every frame, unless precomputed world states latents (B, T, P, D) are given (then pixels may hold the first frame only).
Source code in torch_world/models/jepa/_vlajepa.py
python
class VLAJEPA(WorldActionModel):
    """VLA-JEPA: a vision-language-action policy whose VLM also drives a latent world model, trained JEPA-style.

    A causal VLM reads the current image, the instruction, then two groups of learnable query tokens: one
    *latent-action* token per transition (each repeated ``latent_tokens`` times) and an *embodied-action* token
    (repeated ``action_tokens`` times). A frozen target encoder embeds every frame of the clip into world states
    ``s_0 .. s_{T-1}``; future frames are only regression targets and never reach the VLM. An action-conditioned
    predictor with frame-causal attention reads the true states ``s_{<T-1}`` with the latent-action tokens interleaved
    per step and predicts ``s_{1:T}`` (teacher forcing, L1). A flow-matching action expert, conditioned on the
    embodied-action tokens and on the flow time through adaLN-zero, denoises the next ``chunk_size`` actions:

    ``loss = || v(a_t, t | e) - (a - eps) ||^2 + wm_weight * | P(s_{<T-1}, l) - s_{1:T} |``, ``a_t = (1 - t) eps + t a``.

    Clips without actions (human video) train the world-model term alone. Inference runs only the VLM and the expert:
    ``sample_actions`` integrates the flow from noise in ``flow_steps`` Euler steps. ``imagine`` also unrolls the world
    model from the current state with the latent-action tokens, the futures the VLM expects under the instruction.

    The world model is conditioned on the VLM's latent-action tokens, not on robot actions, so this is a
    ``WorldActionModel`` (it outputs actions and predicts their consequences) whose ``predict`` and ``rollout`` take
    latent-action tokens ``(B, T, latent_tokens, dim)`` in place of actions; action-space planners such as ``CEM`` do
    not apply. The paper's L_WM weight is not given; ``wm_weight = 0.1`` is the released code's.

    Sun et al., "VLA-JEPA: Enhancing Vision-Language-Action Model with Latent World Model", 2026.
    Paper: https://arxiv.org/abs/2602.10098
    Code: https://github.com/ginwind/VLA-JEPA

    Args:
        vision: trainable module mapping images ``(N, C, H, W)`` to tokens ``(N, P, vision_dim)`` or ``(N, vision_dim)``
            (Qwen3-VL's SigLIP-2 in the paper).
        target_encoder: frozen module mapping images to world-state tokens ``(N, num_patches, target_dim)`` or
            ``(N, target_dim)`` (V-JEPA 2 ViT-L in the paper).
        vocab_size: size of the instruction vocabulary; id 0 is padding (``WordTokenizer``).
        frames: world states per clip ``T``, so ``T - 1`` latent-action groups (8 in the paper).
        latent_tokens: copies of each latent-action token (``K = 24 / T = 3`` in the paper, 8 in the released config).
        action_tokens: copies of the embodied-action token that conditions the expert (32).
        flow_repeats: noise draws per sample in the flow-matching loss (``repeated_diffusion_steps``, 8).
        time_alpha: flow times are ``1 - Beta(time_alpha, 1)``, concentrated near noise, as GR00T's head draws them.
    """

    def __init__(
        self,
        vision: nn.Module,
        target_encoder: nn.Module,
        vocab_size: int,
        action_dim: int,
        vision_dim: int,
        target_dim: int,
        num_patches: int = 1,
        *,
        frames: int = 8,
        chunk_size: int = 7,
        latent_tokens: int = 3,
        action_tokens: int = 32,
        state_dim: int = 0,
        dim: int = 256,
        depth: int = 4,
        num_heads: int = 4,
        predictor_dim: int = 256,
        predictor_depth: int = 4,
        predictor_heads: int = 4,
        expert_dim: int = 256,
        expert_depth: int = 4,
        expert_heads: int = 4,
        flow_steps: int = 4,
        flow_repeats: int = 8,
        time_alpha: float = 1.5,
        wm_weight: float = 0.1,
    ):
        super().__init__()
        if frames < 2:
            raise ValueError("frames must be at least 2")
        self.frames, self.chunk_size, self.action_dim, self.state_dim = frames, chunk_size, action_dim, state_dim
        self.latent_tokens, self.action_tokens, self.dim = latent_tokens, action_tokens, dim
        self.flow_steps, self.flow_repeats, self.time_alpha, self.wm_weight = (
            flow_steps,
            flow_repeats,
            time_alpha,
            wm_weight,
        )
        # VLM: vision tokens, instruction words, latent-action queries, embodied-action queries, causal attention
        self.vision, self.vision_proj = vision, nn.Linear(vision_dim, dim)
        self.word_embed = nn.Embedding(vocab_size, dim)
        self.latent_query = nn.Parameter(torch.randn(frames - 1, dim) * 0.02)
        self.action_query = nn.Parameter(torch.randn(1, dim) * 0.02)
        self.vlm = Transformer(dim, depth, num_heads)
        # world model: frozen target encoder and a frame-causal predictor over [latent-action tokens, state tokens]
        self.target_encoder = target_encoder.requires_grad_(False).eval()
        self.state_embed, self.latent_embed = nn.Linear(target_dim, predictor_dim), nn.Linear(dim, predictor_dim)
        self.patch_pos = nn.Parameter(torch.randn(1, 1, num_patches, predictor_dim) * 0.02)
        self.predictor = Transformer(predictor_dim, predictor_depth, predictor_heads)
        self.predictor_proj = nn.Linear(predictor_dim, target_dim)
        # action expert: flow matching on action chunks, conditioned on the embodied-action tokens
        self.cond_proj = nn.Linear(dim, expert_dim)
        self.action_in = MLP([action_dim, expert_dim, expert_dim], act=nn.SiLU)
        self.action_pos = nn.Parameter(torch.randn(1, chunk_size, expert_dim) * 0.02)
        self.state_in = MLP([state_dim, expert_dim, expert_dim], act=nn.SiLU) if state_dim else None
        self.time_mlp = MLP([expert_dim, expert_dim, expert_dim], act=nn.SiLU)
        self.expert = Transformer(expert_dim, expert_depth, expert_heads, conditional=True)
        self.action_out = nn.Linear(expert_dim, action_dim)

    def train(self, mode: bool = True):
        super().train(mode)
        self.target_encoder.eval()
        return self

    @torch.no_grad()
    def encode(self, pixels: Tensor) -> Tensor:
        """World states of frames ``(B, T, C, H, W)`` from the frozen target encoder: ``(B, T, P, target_dim)``."""
        z = self.target_encoder(pixels.flatten(0, 1))
        return (z if z.dim() == 3 else z[:, None]).unflatten(0, pixels.shape[:2]).float()

    def context(self, image: Tensor, ids: Tensor, mask: Tensor | None = None) -> tuple[Tensor, Tensor]:
        """Run the VLM on images ``(B, C, H, W)`` and instructions ``ids`` ``(B, L)`` (``mask`` is ``True`` on words).

        Returns the latent-action tokens ``(B, frames - 1, latent_tokens, dim)`` and the embodied-action tokens
        ``(B, action_tokens, dim)``.
        """
        v = self.vision(image)
        v = self.vision_proj(v if v.dim() == 3 else v[:, None])
        B, n = len(v), (self.frames - 1) * self.latent_tokens
        queries = torch.cat(
            [
                self.latent_query.repeat_interleave(self.latent_tokens, 0),
                self.action_query.expand(self.action_tokens, -1),
            ]
        )
        x = torch.cat([v, self.word_embed(ids), queries.expand(B, -1, -1)], dim=1)
        x = x + sincos_1d(self.dim, torch.arange(x.size(1))).to(x)
        mask = torch.ones_like(ids, dtype=torch.bool) if mask is None else mask.bool()
        valid = torch.cat([mask.new_ones(B, v.size(1)), mask, mask.new_ones(B, len(queries))], dim=1)
        causal = torch.ones(x.size(1), x.size(1), dtype=torch.bool, device=x.device).tril()
        h = self.vlm(x, attn_mask=(causal & valid[:, None, :])[:, None])
        return h[:, -n - self.action_tokens : -self.action_tokens].unflatten(1, (-1, self.latent_tokens)), h[
            :, -self.action_tokens :
        ]

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        """Next world states ``(B, T, P, D)`` from states ``z`` ``(B, T, P, D)`` and latent-action tokens ``actions``
        ``(B, T, latent_tokens, dim)``; step ``t`` sees the tokens of steps ``<= t`` only."""
        T, P, K = z.size(1), z.size(2), actions.size(2)
        x = torch.cat([self.latent_embed(actions), self.state_embed(z) + self.patch_pos[:, :, :P]], dim=2)
        x = x + sincos_1d(x.size(-1), torch.arange(T))[None, :, None].to(x)
        step = torch.arange(T, device=x.device).repeat_interleave(K + P)
        h = self.predictor(x.flatten(1, 2), attn_mask=step[None, :] <= step[:, None])
        return self.predictor_proj(h.unflatten(1, (T, K + P))[:, :, K:])

    def predict_future(self, z: Tensor, actions: Tensor, goal: Tensor | None = None) -> Tensor:
        """Unroll the world model from ``z[:, :1]`` with latent-action tokens ``(B, T, K, dim)``: ``(B, T, P, D)``."""
        return self.rollout(z[:, :1], actions)[:, 1:]

    def velocity(self, x: Tensor, t: Tensor, cond: Tensor, state: Tensor | None = None) -> Tensor:
        """Action velocity ``(B, H, action_dim)`` at noisy chunks ``x`` and flow times ``t`` ``(B,)``, given the
        embodied-action tokens ``cond`` ``(B, M, dim)`` and optional states ``(B, state_dim)``."""
        tokens = [self.cond_proj(cond)]
        if self.state_in is not None:
            tokens.append(self.state_in(state)[:, None])
        tokens.append(self.action_in(x) + self.action_pos[:, : x.size(1)])
        c = self.time_mlp(time_embedding(t, self.time_mlp[0].in_features).to(x))[:, None]
        return self.action_out(self.expert(torch.cat(tokens, dim=1), c)[:, -x.size(1) :])

    def _sample(self, cond, state, steps, generator):
        shape = (len(cond), self.chunk_size, self.action_dim)
        noise = torch.randn(shape, device=cond.device, dtype=cond.dtype, generator=generator)
        return euler_sample(lambda x, t: self.velocity(x, t, cond, state), noise, steps or self.flow_steps)

    def sample_actions(
        self,
        image: Tensor,
        ids: Tensor,
        mask: Tensor | None = None,
        state: Tensor | None = None,
        steps: int | None = None,
        generator: torch.Generator | None = None,
    ) -> Tensor:
        """Action chunk ``(B, chunk_size, action_dim)`` for images ``(B, C, H, W)`` and instructions ``(B, L)``."""
        return self._sample(self.context(image, ids, mask)[1], state, steps, generator)

    def imagine(
        self, image: Tensor, ids: Tensor, mask: Tensor | None = None, state: Tensor | None = None, **kwargs
    ) -> tuple[Tensor, Tensor]:
        """An action chunk and the world states the VLM expects under the instruction, ``(B, frames, P, D)``."""
        latent, cond = self.context(image, ids, mask)
        return self._sample(cond, state, kwargs.get("steps"), kwargs.get("generator")), self.rollout(
            self.encode(image[:, None]), latent
        )

    def forward(
        self,
        pixels: Tensor,
        ids: Tensor,
        mask: Tensor | None = None,
        actions: Tensor | None = None,
        state: Tensor | None = None,
        latents: Tensor | None = None,
    ) -> dict[str, Tensor]:
        """``pixels`` ``(B, T, C, H, W)`` with ``T <= frames``: the VLM sees ``pixels[:, 0]`` and the target encoder
        every frame, unless precomputed world states ``latents`` ``(B, T, P, D)`` are given (then ``pixels`` may hold
        the first frame only). ``actions`` ``(B, chunk_size, action_dim)`` are the chunk from the first frame; without
        them only the world-model loss is trained, as for human videos."""
        z = self.encode(pixels) if latents is None else latents.float()
        latent, cond = self.context(pixels[:, 0], ids, mask)
        wm = F.l1_loss(self.predict(z[:, :-1], latent[:, : z.size(1) - 1]), z[:, 1:])
        if actions is None:
            return {"loss": wm, "wm_loss": wm}
        r = self.flow_repeats
        a, cond = actions.repeat(r, 1, 1), cond.repeat(r, 1, 1)
        state = None if state is None else state.repeat(r, 1)
        noise = torch.randn_like(a)
        t = sample_time(len(a), device=a.device, dtype=a.dtype, alpha=self.time_alpha)
        fm = (self.velocity(interpolate(noise, a, t), t, cond, state) - velocity_target(noise, a)).square().mean()
        return {"loss": fm + self.wm_weight * wm, "action_loss": fm, "wm_loss": wm}

method encode ​

torch_world.models.VLAJEPA.encode GitHub

python
encode(pixels: Tensor) -> Tensor

World states of frames (B, T, C, H, W) from the frozen target encoder: (B, T, P, target_dim).

Source code in torch_world/models/jepa/_vlajepa.py
python
@torch.no_grad()
def encode(self, pixels: Tensor) -> Tensor:
    """World states of frames ``(B, T, C, H, W)`` from the frozen target encoder: ``(B, T, P, target_dim)``."""
    z = self.target_encoder(pixels.flatten(0, 1))
    return (z if z.dim() == 3 else z[:, None]).unflatten(0, pixels.shape[:2]).float()

method context ​

torch_world.models.VLAJEPA.context GitHub

python
context(
    image: Tensor, ids: Tensor, mask: Tensor | None = None
) -> tuple[Tensor, Tensor]

Run the VLM on images (B, C, H, W) and instructions ids (B, L) (mask is True on words).

Returns the latent-action tokens (B, frames - 1, latent_tokens, dim) and the embodied-action tokens (B, action_tokens, dim).

Source code in torch_world/models/jepa/_vlajepa.py
python
def context(self, image: Tensor, ids: Tensor, mask: Tensor | None = None) -> tuple[Tensor, Tensor]:
    """Run the VLM on images ``(B, C, H, W)`` and instructions ``ids`` ``(B, L)`` (``mask`` is ``True`` on words).

    Returns the latent-action tokens ``(B, frames - 1, latent_tokens, dim)`` and the embodied-action tokens
    ``(B, action_tokens, dim)``.
    """
    v = self.vision(image)
    v = self.vision_proj(v if v.dim() == 3 else v[:, None])
    B, n = len(v), (self.frames - 1) * self.latent_tokens
    queries = torch.cat(
        [
            self.latent_query.repeat_interleave(self.latent_tokens, 0),
            self.action_query.expand(self.action_tokens, -1),
        ]
    )
    x = torch.cat([v, self.word_embed(ids), queries.expand(B, -1, -1)], dim=1)
    x = x + sincos_1d(self.dim, torch.arange(x.size(1))).to(x)
    mask = torch.ones_like(ids, dtype=torch.bool) if mask is None else mask.bool()
    valid = torch.cat([mask.new_ones(B, v.size(1)), mask, mask.new_ones(B, len(queries))], dim=1)
    causal = torch.ones(x.size(1), x.size(1), dtype=torch.bool, device=x.device).tril()
    h = self.vlm(x, attn_mask=(causal & valid[:, None, :])[:, None])
    return h[:, -n - self.action_tokens : -self.action_tokens].unflatten(1, (-1, self.latent_tokens)), h[
        :, -self.action_tokens :
    ]

method predict ​

torch_world.models.VLAJEPA.predict GitHub

python
predict(z: Tensor, actions: Tensor) -> Tensor

Next world states (B, T, P, D) from states z (B, T, P, D) and latent-action tokens actions(B, T, latent_tokens, dim); step t sees the tokens of steps <= t only.

Source code in torch_world/models/jepa/_vlajepa.py
python
def predict(self, z: Tensor, actions: Tensor) -> Tensor:
    """Next world states ``(B, T, P, D)`` from states ``z`` ``(B, T, P, D)`` and latent-action tokens ``actions``
    ``(B, T, latent_tokens, dim)``; step ``t`` sees the tokens of steps ``<= t`` only."""
    T, P, K = z.size(1), z.size(2), actions.size(2)
    x = torch.cat([self.latent_embed(actions), self.state_embed(z) + self.patch_pos[:, :, :P]], dim=2)
    x = x + sincos_1d(x.size(-1), torch.arange(T))[None, :, None].to(x)
    step = torch.arange(T, device=x.device).repeat_interleave(K + P)
    h = self.predictor(x.flatten(1, 2), attn_mask=step[None, :] <= step[:, None])
    return self.predictor_proj(h.unflatten(1, (T, K + P))[:, :, K:])

method predict_future ​

torch_world.models.VLAJEPA.predict_future GitHub

python
predict_future(
    z: Tensor, actions: Tensor, goal: Tensor | None = None
) -> Tensor

Unroll the world model from z[:, :1] with latent-action tokens (B, T, K, dim): (B, T, P, D).

Source code in torch_world/models/jepa/_vlajepa.py
python
def predict_future(self, z: Tensor, actions: Tensor, goal: Tensor | None = None) -> Tensor:
    """Unroll the world model from ``z[:, :1]`` with latent-action tokens ``(B, T, K, dim)``: ``(B, T, P, D)``."""
    return self.rollout(z[:, :1], actions)[:, 1:]

method velocity ​

torch_world.models.VLAJEPA.velocity GitHub

python
velocity(
    x: Tensor, t: Tensor, cond: Tensor, state: Tensor | None = None
) -> Tensor

Action velocity (B, H, action_dim) at noisy chunks x and flow times t (B,), given the embodied-action tokens cond (B, M, dim) and optional states (B, state_dim).

Source code in torch_world/models/jepa/_vlajepa.py
python
def velocity(self, x: Tensor, t: Tensor, cond: Tensor, state: Tensor | None = None) -> Tensor:
    """Action velocity ``(B, H, action_dim)`` at noisy chunks ``x`` and flow times ``t`` ``(B,)``, given the
    embodied-action tokens ``cond`` ``(B, M, dim)`` and optional states ``(B, state_dim)``."""
    tokens = [self.cond_proj(cond)]
    if self.state_in is not None:
        tokens.append(self.state_in(state)[:, None])
    tokens.append(self.action_in(x) + self.action_pos[:, : x.size(1)])
    c = self.time_mlp(time_embedding(t, self.time_mlp[0].in_features).to(x))[:, None]
    return self.action_out(self.expert(torch.cat(tokens, dim=1), c)[:, -x.size(1) :])

method sample_actions ​

torch_world.models.VLAJEPA.sample_actions GitHub

python
sample_actions(
    image: Tensor,
    ids: Tensor,
    mask: Tensor | None = None,
    state: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
) -> Tensor

Action chunk (B, chunk_size, action_dim) for images (B, C, H, W) and instructions (B, L).

Source code in torch_world/models/jepa/_vlajepa.py
python
def sample_actions(
    self,
    image: Tensor,
    ids: Tensor,
    mask: Tensor | None = None,
    state: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
) -> Tensor:
    """Action chunk ``(B, chunk_size, action_dim)`` for images ``(B, C, H, W)`` and instructions ``(B, L)``."""
    return self._sample(self.context(image, ids, mask)[1], state, steps, generator)

method imagine ​

torch_world.models.VLAJEPA.imagine GitHub

python
imagine(
    image: Tensor,
    ids: Tensor,
    mask: Tensor | None = None,
    state: Tensor | None = None,
    **kwargs,
) -> tuple[Tensor, Tensor]

An action chunk and the world states the VLM expects under the instruction, (B, frames, P, D).

Source code in torch_world/models/jepa/_vlajepa.py
python
def imagine(
    self, image: Tensor, ids: Tensor, mask: Tensor | None = None, state: Tensor | None = None, **kwargs
) -> tuple[Tensor, Tensor]:
    """An action chunk and the world states the VLM expects under the instruction, ``(B, frames, P, D)``."""
    latent, cond = self.context(image, ids, mask)
    return self._sample(cond, state, kwargs.get("steps"), kwargs.get("generator")), self.rollout(
        self.encode(image[:, None]), latent
    )

method forward ​

torch_world.models.VLAJEPA.forward GitHub

python
forward(
    pixels: Tensor,
    ids: Tensor,
    mask: Tensor | None = None,
    actions: Tensor | None = None,
    state: Tensor | None = None,
    latents: Tensor | None = None,
) -> dict[str, Tensor]

pixels (B, T, C, H, W) with T <= frames: the VLM sees pixels[:, 0] and the target encoder every frame, unless precomputed world states latents (B, T, P, D) are given (then pixels may hold the first frame only). actions (B, chunk_size, action_dim) are the chunk from the first frame; without them only the world-model loss is trained, as for human videos.

Source code in torch_world/models/jepa/_vlajepa.py
python
def forward(
    self,
    pixels: Tensor,
    ids: Tensor,
    mask: Tensor | None = None,
    actions: Tensor | None = None,
    state: Tensor | None = None,
    latents: Tensor | None = None,
) -> dict[str, Tensor]:
    """``pixels`` ``(B, T, C, H, W)`` with ``T <= frames``: the VLM sees ``pixels[:, 0]`` and the target encoder
    every frame, unless precomputed world states ``latents`` ``(B, T, P, D)`` are given (then ``pixels`` may hold
    the first frame only). ``actions`` ``(B, chunk_size, action_dim)`` are the chunk from the first frame; without
    them only the world-model loss is trained, as for human videos."""
    z = self.encode(pixels) if latents is None else latents.float()
    latent, cond = self.context(pixels[:, 0], ids, mask)
    wm = F.l1_loss(self.predict(z[:, :-1], latent[:, : z.size(1) - 1]), z[:, 1:])
    if actions is None:
        return {"loss": wm, "wm_loss": wm}
    r = self.flow_repeats
    a, cond = actions.repeat(r, 1, 1), cond.repeat(r, 1, 1)
    state = None if state is None else state.repeat(r, 1)
    noise = torch.randn_like(a)
    t = sample_time(len(a), device=a.device, dtype=a.dtype, alpha=self.time_alpha)
    fm = (self.velocity(interpolate(noise, a, t), t, cond, state) - velocity_target(noise, a)).square().mean()
    return {"loss": fm + self.wm_weight * wm, "action_loss": fm, "wm_loss": wm}

class RoboJEPA ​

torch_world.models.RoboJEPA GitHub

python
RoboJEPA(
    embed_dim: int,
    action_dim: int,
    state_dim: int = 0,
    num_views: int = 1,
    num_embodiments: int = 1,
    predictor_dim: int = 512,
    depth: int = 7,
    num_heads: int = 4,
    mlp_ratio: float = 4.0,
    window: int | None = 8,
    rollout_steps: int = 2,
    encoder: nn.Module | None = None,
)

RoboJEPA: an action-conditioned predictor in the latent space of a frozen V-JEPA 2.1 encoder, for many robots.

Every timestep contributes the patch tokens of all camera views, one action token and one proprioceptive state token. Actions and states are projected per embodiment. Attention is causal over frames within a window of past frames, and positions use 3D RoPE (t, h, w). The loss is L1 on layer-normalized features, under teacher forcing and over rollout_steps autoregressive steps, as in V-JEPA 2-AC.

Zholus et al., "RoboJEPA: Scaling Robotic Latent World Models", 2026. Paper: https://arxiv.org/abs/2610.10515 Code: https://github.com/facebookresearch/robo_jepa

Assran et al., "V-JEPA 2: Self-Supervised Video Models Enable Understanding, Prediction and Planning", 2025. Paper: https://arxiv.org/abs/2506.09985 Code: https://github.com/facebookresearch/vjepa2

Latents are (B, T, V, H, W, embed_dim): V views on an H x W patch grid.

Members

MemberDescription
encodeframes (B, T, V, C, H, W) to layer-normalized features (B, T, V, h, w, D) with the frozen encoder.
rolloutStates past the given ones repeat the last known state.
forwardz (B, T, V, H, W, D) encoder features, actions (B, T, A) and states (B, T, S).
Source code in torch_world/models/jepa/_robojepa.py
python
class RoboJEPA(WorldModel):
    """RoboJEPA: an action-conditioned predictor in the latent space of a frozen V-JEPA 2.1 encoder, for many robots.

    Every timestep contributes the patch tokens of all camera views, one action token and one proprioceptive state
    token. Actions and states are projected per embodiment. Attention is causal over frames within a ``window`` of
    past frames, and positions use 3D RoPE ``(t, h, w)``. The loss is L1 on layer-normalized features, under
    teacher forcing and over ``rollout_steps`` autoregressive steps, as in V-JEPA 2-AC.

    Zholus et al., "RoboJEPA: Scaling Robotic Latent World Models", 2026.
    Paper: https://arxiv.org/abs/2610.10515
    Code: https://github.com/facebookresearch/robo_jepa

    Assran et al., "V-JEPA 2: Self-Supervised Video Models Enable Understanding, Prediction and Planning", 2025.
    Paper: https://arxiv.org/abs/2506.09985
    Code: https://github.com/facebookresearch/vjepa2

    Latents are ``(B, T, V, H, W, embed_dim)``: ``V`` views on an ``H x W`` patch grid.
    """

    def __init__(
        self,
        embed_dim: int,
        action_dim: int,
        state_dim: int = 0,
        num_views: int = 1,
        num_embodiments: int = 1,
        predictor_dim: int = 512,
        depth: int = 7,
        num_heads: int = 4,
        mlp_ratio: float = 4.0,
        window: int | None = 8,
        rollout_steps: int = 2,
        encoder: nn.Module | None = None,
    ):
        super().__init__()
        self.window = window
        self.rollout_steps = rollout_steps
        self.encoder = encoder.requires_grad_(False).eval() if encoder is not None else None
        self.embed = nn.Linear(embed_dim, predictor_dim)
        self.view_embed = nn.Parameter(torch.zeros(num_views, predictor_dim))
        self.embodiment_embed = nn.Embedding(num_embodiments, predictor_dim)
        self.action_proj = EmbodimentLinear(action_dim, predictor_dim, num_embodiments)
        self.state_proj = EmbodimentLinear(state_dim, predictor_dim, num_embodiments) if state_dim else None
        self.predictor = Transformer(
            predictor_dim, depth, num_heads, mlp_dim=int(predictor_dim * mlp_ratio), use_rope=True
        )
        self.proj = nn.Linear(predictor_dim, embed_dim)
        init_weights(self.predictor)
        rescale_blocks(self.predictor.blocks)
        nn.init.trunc_normal_(self.view_embed, std=0.02)

    @property
    def num_cond(self) -> int:
        return 1 + (self.state_proj is not None)

    def train(self, mode: bool = True):
        super().train(mode)
        if self.encoder is not None:
            self.encoder.eval()
        return self

    @torch.no_grad()
    def encode(self, frames: Tensor, grid: tuple[int, int] | None = None) -> Tensor:
        """``frames`` ``(B, T, V, C, H, W)`` to layer-normalized features ``(B, T, V, h, w, D)`` with the frozen encoder.

        Frames ``(B, T, C, H, W)`` are one view. Without ``grid``, the patch grid is taken to be square.
        """
        frames = frames[:, :, None] if frames.dim() == 5 else frames
        z = self.encoder(frames.flatten(0, 2))
        if grid is None:
            side = math.isqrt(z.size(1))
            grid = (side, z.size(1) // side)
        z = z.unflatten(1, grid).unflatten(0, frames.shape[:3])
        return F.layer_norm(z, z.shape[-1:])

    def _positions(self, T: int, V: int, H: int, W: int, device) -> Tensor:
        t, h, w = torch.meshgrid(torch.arange(T), torch.arange(H), torch.arange(W), indexing="ij")
        patches = torch.stack([t, h, w], dim=-1)[:, None].expand(T, V, H, W, 3).reshape(T, V * H * W, 3)
        cond = torch.stack(
            [torch.arange(T), torch.zeros(T, dtype=torch.long), torch.zeros(T, dtype=torch.long)], dim=-1
        )
        cond = cond[:, None].expand(T, self.num_cond, 3)
        return torch.cat([patches, cond], dim=1).flatten(0, 1).float().to(device)

    def predict(
        self, z: Tensor, actions: Tensor, states: Tensor | None = None, embodiment: Tensor | None = None
    ) -> Tensor:
        B, T, V, H, W, _ = z.shape
        ids = embodiment if embodiment is not None else torch.zeros(B, dtype=torch.long, device=z.device)
        x = self.embed(z) + self.view_embed[:V, None, None] + self.embodiment_embed(ids)[:, None, None, None, None]
        cond = [self.action_proj(actions, ids)]
        if self.state_proj is not None:
            cond.append(self.state_proj(states, ids))
        x = torch.cat([x.flatten(2, 4), torch.stack(cond, dim=2)], dim=2)
        n = x.size(2)
        mask = frame_causal_mask(T, n, self.window, device=z.device)
        x = self.predictor(x.flatten(1, 2), attn_mask=mask, pos=self._positions(T, V, H, W, z.device))
        return self.proj(x.unflatten(1, (T, n))[:, :, : V * H * W]).unflatten(2, (V, H, W))

    def rollout(
        self, z: Tensor, actions: Tensor, states: Tensor | None = None, embodiment: Tensor | None = None
    ) -> Tensor:
        """States past the given ones repeat the last known state."""
        if states is not None and states.size(1) < actions.size(1):
            pad = states[:, -1:].expand(-1, actions.size(1) - states.size(1), -1)
            states = torch.cat([states, pad], dim=1)
        for t in range(z.size(1), actions.size(1) + 1):
            s = None if states is None else states[:, :t]
            z = torch.cat([z, self.predict(z, actions[:, :t], s, embodiment)[:, -1:]], dim=1)
        return z

    def cost(self, z: Tensor, goal: Tensor) -> Tensor:
        return (z[:, -1] - goal).abs().flatten(1).mean(1)

    def forward(
        self, z: Tensor, actions: Tensor, states: Tensor | None = None, embodiment: Tensor | None = None
    ) -> dict[str, Tensor]:
        """``z`` ``(B, T, V, H, W, D)`` encoder features, ``actions`` ``(B, T, A)`` and ``states`` ``(B, T, S)``."""
        z = F.layer_norm(z, z.shape[-1:])
        tf = self.predict(z[:, :-1], actions[:, :-1], None if states is None else states[:, :-1], embodiment)
        tf_loss = (tf - z[:, 1:]).abs().mean()
        ar = torch.cat([z[:, :1], tf[:, :1]], dim=1)
        for n in range(1, self.rollout_steps):
            s = None if states is None else states[:, : n + 1]
            ar = torch.cat([ar, self.predict(ar, actions[:, : n + 1], s, embodiment)[:, -1:]], dim=1)
        ar_loss = (ar[:, 1:] - z[:, 1 : self.rollout_steps + 1]).abs().mean()
        return {"loss": tf_loss + ar_loss, "tf_loss": tf_loss, "rollout_loss": ar_loss}

method encode ​

torch_world.models.RoboJEPA.encode GitHub

python
encode(frames: Tensor, grid: tuple[int, int] | None = None) -> Tensor

frames (B, T, V, C, H, W) to layer-normalized features (B, T, V, h, w, D) with the frozen encoder.

Frames (B, T, C, H, W) are one view. Without grid, the patch grid is taken to be square.

Source code in torch_world/models/jepa/_robojepa.py
python
@torch.no_grad()
def encode(self, frames: Tensor, grid: tuple[int, int] | None = None) -> Tensor:
    """``frames`` ``(B, T, V, C, H, W)`` to layer-normalized features ``(B, T, V, h, w, D)`` with the frozen encoder.

    Frames ``(B, T, C, H, W)`` are one view. Without ``grid``, the patch grid is taken to be square.
    """
    frames = frames[:, :, None] if frames.dim() == 5 else frames
    z = self.encoder(frames.flatten(0, 2))
    if grid is None:
        side = math.isqrt(z.size(1))
        grid = (side, z.size(1) // side)
    z = z.unflatten(1, grid).unflatten(0, frames.shape[:3])
    return F.layer_norm(z, z.shape[-1:])

method rollout ​

torch_world.models.RoboJEPA.rollout GitHub

python
rollout(
    z: Tensor,
    actions: Tensor,
    states: Tensor | None = None,
    embodiment: Tensor | None = None,
) -> Tensor

States past the given ones repeat the last known state.

Source code in torch_world/models/jepa/_robojepa.py
python
def rollout(
    self, z: Tensor, actions: Tensor, states: Tensor | None = None, embodiment: Tensor | None = None
) -> Tensor:
    """States past the given ones repeat the last known state."""
    if states is not None and states.size(1) < actions.size(1):
        pad = states[:, -1:].expand(-1, actions.size(1) - states.size(1), -1)
        states = torch.cat([states, pad], dim=1)
    for t in range(z.size(1), actions.size(1) + 1):
        s = None if states is None else states[:, :t]
        z = torch.cat([z, self.predict(z, actions[:, :t], s, embodiment)[:, -1:]], dim=1)
    return z

method forward ​

torch_world.models.RoboJEPA.forward GitHub

python
forward(
    z: Tensor,
    actions: Tensor,
    states: Tensor | None = None,
    embodiment: Tensor | None = None,
) -> dict[str, Tensor]

z (B, T, V, H, W, D) encoder features, actions (B, T, A) and states (B, T, S).

Source code in torch_world/models/jepa/_robojepa.py
python
def forward(
    self, z: Tensor, actions: Tensor, states: Tensor | None = None, embodiment: Tensor | None = None
) -> dict[str, Tensor]:
    """``z`` ``(B, T, V, H, W, D)`` encoder features, ``actions`` ``(B, T, A)`` and ``states`` ``(B, T, S)``."""
    z = F.layer_norm(z, z.shape[-1:])
    tf = self.predict(z[:, :-1], actions[:, :-1], None if states is None else states[:, :-1], embodiment)
    tf_loss = (tf - z[:, 1:]).abs().mean()
    ar = torch.cat([z[:, :1], tf[:, :1]], dim=1)
    for n in range(1, self.rollout_steps):
        s = None if states is None else states[:, : n + 1]
        ar = torch.cat([ar, self.predict(ar, actions[:, : n + 1], s, embodiment)[:, -1:]], dim=1)
    ar_loss = (ar[:, 1:] - z[:, 1 : self.rollout_steps + 1]).abs().mean()
    return {"loss": tf_loss + ar_loss, "tf_loss": tf_loss, "rollout_loss": ar_loss}

class EmbodimentLinear ​

torch_world.models.jepa.EmbodimentLinear GitHub

python
EmbodimentLinear(in_dim: int, out_dim: int, num_embodiments: int = 1)

Linear map with separate weights per embodiment, selected by ids (B,).

Source code in torch_world/models/jepa/_robojepa.py
python
class EmbodimentLinear(nn.Module):
    """Linear map with separate weights per embodiment, selected by ``ids`` ``(B,)``."""

    def __init__(self, in_dim: int, out_dim: int, num_embodiments: int = 1):
        super().__init__()
        self.weight = nn.Parameter(torch.empty(num_embodiments, in_dim, out_dim))
        self.bias = nn.Parameter(torch.zeros(num_embodiments, out_dim))
        nn.init.trunc_normal_(self.weight, std=0.02)

    def forward(self, x: Tensor, ids: Tensor) -> Tensor:
        return torch.einsum("bti,bio->bto", x, self.weight[ids]) + self.bias[ids, None]

class DINOv2 ​

torch_world.models.DINOv2 GitHub

python
DINOv2(
    encoder: DINOv2Encoder,
    head: DINOHead,
    ibot_weight: float = 1.0,
    koleo_weight: float = 0.1,
    student_temp: float = 0.1,
    sinkhorn_iterations: int = 3,
)

DINOv2: a student matches an EMA teacher's prototype assignments, image-level (DINO) and patch-level (iBOT).

The teacher reads the G global crops of each image; the student reads them with masked patches and the V local crops. Three terms:

  • DINO: every student [cls] predicts the teacher's centered assignment of every other global crop (cross-entropy, averaged over the G * (G + V) - G pairs).
  • iBOT: each masked patch predicts the teacher's assignment of the same, unmasked patch, averaged per image and then over all global crops.
  • KoLeo: spreads the student's global [cls] tokens within each crop's batch, weighted by koleo_weight.

Teacher scores are centered by Sinkhorn-Knopp and sharpened by teacher_temp, the student's by student_temp. Call update_teacher(momentum) after each optimizer step (reference: a cosine schedule from 0.992 to 1); the reference warms teacher_temp linearly from 0.04 to 0.07.

Oquab et al., "DINOv2: Learning Robust Visual Features without Supervision", TMLR 2024. Paper: https://arxiv.org/abs/2304.07193 Code: https://github.com/facebookresearch/dinov2

Example::

encoder = DINOv2Encoder(img_size=224, patch_size=14, embed_dim=384, depth=12, num_heads=6)
model = DINOv2(encoder, DINOHead(384))
mask = BlockwiseMask((16, 16))(2 * batch_size).view(2, batch_size, -1)
loss = model(global_crops, local_crops, mask, teacher_temp=0.07)["loss"]

Members

MemberDescription
encodeImage embedding (B, D): the student's [cls] token.
targetsTeacher assignments of the global crops' [cls] tokens (G, B, K) and of the masked patches (M, K).
forwardglobal_crops (G, B, C, H, W); local_crops (V, B, C, h, w) or V tensors (B, C, h, w); mask (G, B, N) is True for the masked patches of each global crop.
Source code in torch_world/models/dino/_dinov2.py
python
class DINOv2(nn.Module):
    """DINOv2: a student matches an EMA teacher's prototype assignments, image-level (DINO) and patch-level (iBOT).

    The teacher reads the ``G`` global crops of each image; the student reads them with masked patches and the ``V``
    local crops. Three terms:

    - **DINO**: every student [cls] predicts the teacher's centered assignment of every other global crop
      (cross-entropy, averaged over the ``G * (G + V) - G`` pairs).
    - **iBOT**: each masked patch predicts the teacher's assignment of the same, unmasked patch, averaged per image
      and then over all global crops.
    - **KoLeo**: spreads the student's global [cls] tokens within each crop's batch, weighted by ``koleo_weight``.

    Teacher scores are centered by Sinkhorn-Knopp and sharpened by ``teacher_temp``, the student's by
    ``student_temp``. Call ``update_teacher(momentum)`` after each optimizer step (reference: a cosine schedule from
    0.992 to 1); the reference warms ``teacher_temp`` linearly from 0.04 to 0.07.

    Oquab et al., "DINOv2: Learning Robust Visual Features without Supervision", TMLR 2024.
    Paper: https://arxiv.org/abs/2304.07193
    Code: https://github.com/facebookresearch/dinov2

    Example::

        encoder = DINOv2Encoder(img_size=224, patch_size=14, embed_dim=384, depth=12, num_heads=6)
        model = DINOv2(encoder, DINOHead(384))
        mask = BlockwiseMask((16, 16))(2 * batch_size).view(2, batch_size, -1)
        loss = model(global_crops, local_crops, mask, teacher_temp=0.07)["loss"]
    """

    def __init__(
        self,
        encoder: DINOv2Encoder,
        head: DINOHead,
        ibot_weight: float = 1.0,
        koleo_weight: float = 0.1,
        student_temp: float = 0.1,
        sinkhorn_iterations: int = 3,
    ):
        super().__init__()
        self.encoder, self.head = encoder, head
        self.teacher_encoder = copy.deepcopy(encoder).requires_grad_(False)
        self.teacher_head = copy.deepcopy(head).requires_grad_(False)
        self.ibot_weight, self.koleo_weight = ibot_weight, koleo_weight
        self.student_temp = student_temp
        self.sinkhorn_iterations = sinkhorn_iterations

    def update_teacher(self, momentum: float):
        ema_update(self.teacher_encoder, self.encoder, momentum)
        ema_update(self.teacher_head, self.head, momentum)

    def encode(self, x: Tensor) -> Tensor:
        """Image embedding ``(B, D)``: the student's [cls] token."""
        return self.encoder(x)[:, 0]

    @torch.no_grad()
    def targets(self, global_crops: Tensor, mask: Tensor, teacher_temp: float) -> tuple[Tensor, Tensor]:
        """Teacher assignments of the global crops' [cls] tokens ``(G, B, K)`` and of the masked patches ``(M, K)``."""
        tokens = self.teacher_encoder(global_crops.flatten(0, 1))
        cls = sinkhorn_knopp(self.teacher_head(tokens[:, 0]), teacher_temp, self.sinkhorn_iterations)
        patches = tokens[:, 1:][mask.flatten(0, 1)]
        if len(patches):
            patches = sinkhorn_knopp(self.teacher_head(patches), teacher_temp, self.sinkhorn_iterations)
        return cls.unflatten(0, global_crops.shape[:2]), patches

    def forward(
        self, global_crops: Tensor, local_crops: Tensor | Sequence[Tensor], mask: Tensor, teacher_temp: float = 0.07
    ) -> dict[str, Tensor]:
        """``global_crops`` ``(G, B, C, H, W)``; ``local_crops`` ``(V, B, C, h, w)`` or ``V`` tensors ``(B, C, h, w)``;
        ``mask`` ``(G, B, N)`` is True for the masked patches of each global crop."""
        G, B = global_crops.shape[:2]
        teacher_cls, teacher_patches = self.targets(global_crops, mask, teacher_temp)

        mask = mask.flatten(0, 1)
        tokens = self.encoder(global_crops.flatten(0, 1), mask)
        local_cls = torch.stack([self.encoder(v)[:, 0] for v in local_crops])
        global_cls = tokens[:, 0].unflatten(0, (G, B))
        student = F.log_softmax(self.head(torch.cat([global_cls, local_cls])) / self.student_temp, dim=-1)

        cross_entropy = -(teacher_cls[:, None] * student[None]).sum(-1).mean(-1)  # (G, G + V) pairs
        other_view = ~torch.eye(G, len(student), dtype=torch.bool, device=student.device)
        dino = cross_entropy[other_view].mean()

        patches = F.log_softmax(self.head(tokens[:, 1:][mask]) / self.student_temp, dim=-1)
        per_image = 1 / mask.sum(1, keepdim=True).clamp(min=1)
        ibot = -((teacher_patches * patches).sum(-1) * per_image.expand_as(mask)[mask]).sum() / len(mask)

        spread = sum(koleo(c) for c in global_cls)
        loss = dino + self.ibot_weight * ibot + self.koleo_weight * spread
        return {"loss": loss, "dino_loss": dino, "ibot_loss": ibot, "koleo_loss": spread}

method encode ​

torch_world.models.DINOv2.encode GitHub

python
encode(x: Tensor) -> Tensor

Image embedding (B, D): the student's [cls] token.

Source code in torch_world/models/dino/_dinov2.py
python
def encode(self, x: Tensor) -> Tensor:
    """Image embedding ``(B, D)``: the student's [cls] token."""
    return self.encoder(x)[:, 0]

method targets ​

torch_world.models.DINOv2.targets GitHub

python
targets(
    global_crops: Tensor, mask: Tensor, teacher_temp: float
) -> tuple[Tensor, Tensor]

Teacher assignments of the global crops' [cls] tokens (G, B, K) and of the masked patches (M, K).

Source code in torch_world/models/dino/_dinov2.py
python
@torch.no_grad()
def targets(self, global_crops: Tensor, mask: Tensor, teacher_temp: float) -> tuple[Tensor, Tensor]:
    """Teacher assignments of the global crops' [cls] tokens ``(G, B, K)`` and of the masked patches ``(M, K)``."""
    tokens = self.teacher_encoder(global_crops.flatten(0, 1))
    cls = sinkhorn_knopp(self.teacher_head(tokens[:, 0]), teacher_temp, self.sinkhorn_iterations)
    patches = tokens[:, 1:][mask.flatten(0, 1)]
    if len(patches):
        patches = sinkhorn_knopp(self.teacher_head(patches), teacher_temp, self.sinkhorn_iterations)
    return cls.unflatten(0, global_crops.shape[:2]), patches

method forward ​

torch_world.models.DINOv2.forward GitHub

python
forward(
    global_crops: Tensor,
    local_crops: Tensor | Sequence[Tensor],
    mask: Tensor,
    teacher_temp: float = 0.07,
) -> dict[str, Tensor]

global_crops (G, B, C, H, W); local_crops (V, B, C, h, w) or V tensors (B, C, h, w); mask (G, B, N) is True for the masked patches of each global crop.

Source code in torch_world/models/dino/_dinov2.py
python
def forward(
    self, global_crops: Tensor, local_crops: Tensor | Sequence[Tensor], mask: Tensor, teacher_temp: float = 0.07
) -> dict[str, Tensor]:
    """``global_crops`` ``(G, B, C, H, W)``; ``local_crops`` ``(V, B, C, h, w)`` or ``V`` tensors ``(B, C, h, w)``;
    ``mask`` ``(G, B, N)`` is True for the masked patches of each global crop."""
    G, B = global_crops.shape[:2]
    teacher_cls, teacher_patches = self.targets(global_crops, mask, teacher_temp)

    mask = mask.flatten(0, 1)
    tokens = self.encoder(global_crops.flatten(0, 1), mask)
    local_cls = torch.stack([self.encoder(v)[:, 0] for v in local_crops])
    global_cls = tokens[:, 0].unflatten(0, (G, B))
    student = F.log_softmax(self.head(torch.cat([global_cls, local_cls])) / self.student_temp, dim=-1)

    cross_entropy = -(teacher_cls[:, None] * student[None]).sum(-1).mean(-1)  # (G, G + V) pairs
    other_view = ~torch.eye(G, len(student), dtype=torch.bool, device=student.device)
    dino = cross_entropy[other_view].mean()

    patches = F.log_softmax(self.head(tokens[:, 1:][mask]) / self.student_temp, dim=-1)
    per_image = 1 / mask.sum(1, keepdim=True).clamp(min=1)
    ibot = -((teacher_patches * patches).sum(-1) * per_image.expand_as(mask)[mask]).sum() / len(mask)

    spread = sum(koleo(c) for c in global_cls)
    loss = dino + self.ibot_weight * ibot + self.koleo_weight * spread
    return {"loss": loss, "dino_loss": dino, "ibot_loss": ibot, "koleo_loss": spread}

class DINOv2Encoder ​

torch_world.models.DINOv2Encoder GitHub

python
DINOv2Encoder(
    img_size: int = 224,
    patch_size: int = 14,
    in_chans: int = 3,
    embed_dim: int = 768,
    depth: int = 12,
    num_heads: int = 12,
    mlp_ratio: float = 4.0,
    drop_path: float = 0.0,
    init_std: float = 0.02,
)

The ViT of DINOv2: a [cls] token, learned position embeddings resized to each input, and a mask token for iBOT.

Images (B, C, H, W) of any size divisible by patch_size become normalized tokens (B, 1 + N, D), [cls] first. Position embeddings are learned for img_size and resized bicubically to other grids, such as those of local crops. Blocks are the library's pre-norm blocks, without LayerScale.

Members

MemberDescription
positionsPosition embeddings (1, 1 + h * w, D) for a grid of patches, [cls] first.
forwardmask (B, N) is True for patches whose embedding the mask token replaces.
Source code in torch_world/models/dino/_dinov2.py
python
class DINOv2Encoder(nn.Module):
    """The ViT of DINOv2: a [cls] token, learned position embeddings resized to each input, and a mask token for iBOT.

    Images ``(B, C, H, W)`` of any size divisible by ``patch_size`` become normalized tokens ``(B, 1 + N, D)``,
    [cls] first. Position embeddings are learned for ``img_size`` and resized bicubically to other grids, such as
    those of local crops. Blocks are the library's pre-norm blocks, without LayerScale.
    """

    def __init__(
        self,
        img_size: int = 224,
        patch_size: int = 14,
        in_chans: int = 3,
        embed_dim: int = 768,
        depth: int = 12,
        num_heads: int = 12,
        mlp_ratio: float = 4.0,
        drop_path: float = 0.0,
        init_std: float = 0.02,
    ):
        super().__init__()
        self.patch_size, self.embed_dim = patch_size, embed_dim
        self.grid = (img_size // patch_size, img_size // patch_size)
        self.patch_embed = PatchEmbed(patch_size, in_chans, embed_dim)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
        self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
        self.pos_embed = nn.Parameter(torch.zeros(1, 1 + self.grid[0] * self.grid[1], embed_dim))
        self.transformer = Transformer(embed_dim, depth, num_heads, drop_path, mlp_dim=int(embed_dim * mlp_ratio))
        init_weights(self, init_std)
        nn.init.trunc_normal_(self.pos_embed, std=0.02)
        nn.init.normal_(self.cls_token, std=1e-6)

    def positions(self, grid: tuple[int, int]) -> Tensor:
        """Position embeddings ``(1, 1 + h * w, D)`` for a ``grid`` of patches, [cls] first."""
        cls, patches = self.pos_embed[:, :1], self.pos_embed[:, 1:]
        if grid != self.grid:
            patches = patches.unflatten(1, self.grid).permute(0, 3, 1, 2)
            patches = F.interpolate(patches, size=grid, mode="bicubic").flatten(2).transpose(1, 2)
        return torch.cat([cls, patches], dim=1)

    def forward(self, x: Tensor, mask: Tensor | None = None) -> Tensor:
        """``mask`` ``(B, N)`` is True for patches whose embedding the mask token replaces."""
        grid = (x.size(-2) // self.patch_size, x.size(-1) // self.patch_size)
        x = self.patch_embed(x)
        if mask is not None:
            x = torch.where(mask[..., None], self.mask_token.to(x.dtype), x)
        x = torch.cat([self.cls_token.expand(len(x), -1, -1), x], dim=1)
        return self.transformer(x + self.positions(grid))

method positions ​

torch_world.models.DINOv2Encoder.positions GitHub

python
positions(grid: tuple[int, int]) -> Tensor

Position embeddings (1, 1 + h * w, D) for a grid of patches, [cls] first.

Source code in torch_world/models/dino/_dinov2.py
python
def positions(self, grid: tuple[int, int]) -> Tensor:
    """Position embeddings ``(1, 1 + h * w, D)`` for a ``grid`` of patches, [cls] first."""
    cls, patches = self.pos_embed[:, :1], self.pos_embed[:, 1:]
    if grid != self.grid:
        patches = patches.unflatten(1, self.grid).permute(0, 3, 1, 2)
        patches = F.interpolate(patches, size=grid, mode="bicubic").flatten(2).transpose(1, 2)
    return torch.cat([cls, patches], dim=1)

method forward ​

torch_world.models.DINOv2Encoder.forward GitHub

python
forward(x: Tensor, mask: Tensor | None = None) -> Tensor

mask (B, N) is True for patches whose embedding the mask token replaces.

Source code in torch_world/models/dino/_dinov2.py
python
def forward(self, x: Tensor, mask: Tensor | None = None) -> Tensor:
    """``mask`` ``(B, N)`` is True for patches whose embedding the mask token replaces."""
    grid = (x.size(-2) // self.patch_size, x.size(-1) // self.patch_size)
    x = self.patch_embed(x)
    if mask is not None:
        x = torch.where(mask[..., None], self.mask_token.to(x.dtype), x)
    x = torch.cat([self.cls_token.expand(len(x), -1, -1), x], dim=1)
    return self.transformer(x + self.positions(grid))

class DINOHead ​

torch_world.models.DINOHead GitHub

python
DINOHead(
    in_dim: int,
    num_prototypes: int = 65536,
    hidden_dim: int = 2048,
    bottleneck_dim: int = 256,
    depth: int = 3,
)

The DINO head: an MLP to a bottleneck, L2 normalization, then weight-normalized prototypes.

Maps (..., in_dim) to prototype scores (..., num_prototypes). DINOv2 scores [cls] tokens (DINO) and patch tokens (iBOT) with the same head.

Source code in torch_world/models/dino/_dinov2.py
python
class DINOHead(nn.Module):
    """The DINO head: an MLP to a bottleneck, L2 normalization, then weight-normalized prototypes.

    Maps ``(..., in_dim)`` to prototype scores ``(..., num_prototypes)``. DINOv2 scores [cls] tokens (DINO) and patch
    tokens (iBOT) with the same head.
    """

    def __init__(
        self,
        in_dim: int,
        num_prototypes: int = 65536,
        hidden_dim: int = 2048,
        bottleneck_dim: int = 256,
        depth: int = 3,
    ):
        super().__init__()
        self.mlp = MLP([in_dim, *[hidden_dim] * (depth - 1), bottleneck_dim])
        init_weights(self.mlp)
        self.prototypes = weight_norm(nn.Linear(bottleneck_dim, num_prototypes, bias=False))
        self.prototypes.parametrizations.weight.original0.data.fill_(1)

    def forward(self, x: Tensor) -> Tensor:
        return self.prototypes(F.normalize(self.mlp(x), dim=-1))

function sinkhorn_knopp ​

torch_world.models.dino.sinkhorn_knopp GitHub

python
sinkhorn_knopp(
    scores: Tensor, temperature: float, iterations: int = 3
) -> Tensor

Teacher targets (N, K) from prototype scores: each row a distribution, each prototype used equally.

The sharpened scores exp(scores / temperature) are rescaled alternately so that every prototype gets mass 1 / K and every sample 1 / N; rows are then returned summing to one. This is the centering of SwAV and DINOv2, in place of DINO's moving-average center.

Source code in torch_world/models/dino/_dinov2.py
python
@torch.no_grad()
def sinkhorn_knopp(scores: Tensor, temperature: float, iterations: int = 3) -> Tensor:
    """Teacher targets ``(N, K)`` from prototype scores: each row a distribution, each prototype used equally.

    The sharpened scores ``exp(scores / temperature)`` are rescaled alternately so that every prototype gets mass
    ``1 / K`` and every sample ``1 / N``; rows are then returned summing to one. This is the centering of SwAV and
    DINOv2, in place of DINO's moving-average center.
    """
    q = torch.exp((scores.float() - scores.max()) / temperature)
    q /= q.sum()
    n, k = q.shape
    for _ in range(iterations):
        q /= q.sum(dim=0, keepdim=True) * k
        q /= q.sum(dim=1, keepdim=True) * n
    return q * n

class DINOWM ​

torch_world.models.DINOWM GitHub

python
DINOWM(
    encoder: nn.Module,
    num_patches: int,
    embed_dim: int,
    action_dim: int,
    proprio_dim: int = 0,
    action_emb_dim: int = 10,
    proprio_emb_dim: int = 10,
    history: int = 3,
    depth: int = 6,
    num_heads: int = 16,
    head_dim: int = 64,
    mlp_dim: int = 2048,
    dropout: float = 0.1,
)

DINO-WM: a world model over the patch features of a frozen pre-trained encoder (DINOv2).

Proprioception and action embeddings are tiled over every patch and concatenated on the feature dim. A ViT predictor with frame-level causal attention predicts the next frame's visual and proprio features, trained with MSE against detached targets. Latents from encode are (B, T, P, D + proprio_emb_dim).

Zhou et al., "DINO-WM: World Models on Pre-trained Visual Features enable Zero-shot Planning", ICML 2025. Paper: https://arxiv.org/abs/2411.04983 Code: https://github.com/gaoyuezhou/dino_wm

Parameters

NameTypeDescriptionDefault
encodernn.Modulefrozen module mapping images (N, C, H, W) to patch tokens (N, num_patches, embed_dim).required

Members

MemberDescription
encodepixels (B, T, C, H, W) and proprio (B, T, proprio_dim) to (B, T, P, D').
forwardpixels (B, history + 1, C, H, W), actions (B, history + 1, action_dim).
Source code in torch_world/models/dino/_dinowm.py
python
class DINOWM(WorldModel):
    """DINO-WM: a world model over the patch features of a frozen pre-trained encoder (DINOv2).

    Proprioception and action embeddings are tiled over every patch and concatenated on the feature dim. A ViT
    predictor with frame-level causal attention predicts the next frame's visual and proprio features, trained with
    MSE against detached targets. Latents from ``encode`` are ``(B, T, P, D + proprio_emb_dim)``.

    Zhou et al., "DINO-WM: World Models on Pre-trained Visual Features enable Zero-shot Planning", ICML 2025.
    Paper: https://arxiv.org/abs/2411.04983
    Code: https://github.com/gaoyuezhou/dino_wm

    Args:
        encoder: frozen module mapping images ``(N, C, H, W)`` to patch tokens ``(N, num_patches, embed_dim)``.
    """

    def __init__(
        self,
        encoder: nn.Module,
        num_patches: int,
        embed_dim: int,
        action_dim: int,
        proprio_dim: int = 0,
        action_emb_dim: int = 10,
        proprio_emb_dim: int = 10,
        history: int = 3,
        depth: int = 6,
        num_heads: int = 16,
        head_dim: int = 64,
        mlp_dim: int = 2048,
        dropout: float = 0.1,
    ):
        super().__init__()
        self.history = history
        self.num_patches = num_patches
        self.action_emb_dim = action_emb_dim
        self.encoder = encoder.requires_grad_(False).eval()
        self.action_encoder = nn.Linear(action_dim, action_emb_dim)
        self.proprio_encoder = nn.Linear(proprio_dim, proprio_emb_dim) if proprio_dim else None
        dim = embed_dim + action_emb_dim + (proprio_emb_dim if proprio_dim else 0)
        self.pos_embed = nn.Parameter(torch.randn(1, history * num_patches, dim))
        self.predictor = Transformer(
            dim, depth, num_heads, mlp_dim=mlp_dim, head_dim=head_dim, qkv_bias=False, dropout=dropout
        )
        self.register_buffer("attn_mask", frame_causal_mask(history, num_patches), persistent=False)

    def train(self, mode: bool = True):
        super().train(mode)
        self.encoder.eval()
        return self

    def encode(self, pixels: Tensor, proprio: Tensor | None = None) -> Tensor:
        """``pixels`` ``(B, T, C, H, W)`` and ``proprio`` ``(B, T, proprio_dim)`` to ``(B, T, P, D')``."""
        with torch.no_grad():
            z = self.encoder(pixels.flatten(0, 1)).unflatten(0, pixels.shape[:2])
        if self.proprio_encoder is not None:
            z = torch.cat([z, self._tile(self.proprio_encoder(proprio))], dim=-1)
        return z

    def _tile(self, x: Tensor) -> Tensor:
        return x[:, :, None].expand(-1, -1, self.num_patches, -1)

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        T, P = z.shape[1:3]
        x = torch.cat([z, self._tile(self.action_encoder(actions))], dim=-1).flatten(1, 2)
        x = self.predictor(x + self.pos_embed[:, : T * P], attn_mask=self.attn_mask[: T * P, : T * P])
        return x.unflatten(1, (T, P))[..., : -self.action_emb_dim]

    def forward(self, pixels: Tensor, actions: Tensor, proprio: Tensor | None = None) -> dict[str, Tensor]:
        """``pixels`` ``(B, history + 1, C, H, W)``, ``actions`` ``(B, history + 1, action_dim)``."""
        z = self.encode(pixels, proprio)
        pred = self.predict(z[:, : self.history], actions[:, : self.history])
        target = z[:, 1 : self.history + 1].detach()
        out = {"loss": F.mse_loss(pred, target)}
        if self.proprio_encoder is not None:
            d = self.proprio_encoder.out_features
            out["visual_loss"] = F.mse_loss(pred[..., :-d], target[..., :-d])
            out["proprio_loss"] = F.mse_loss(pred[..., -d:], target[..., -d:])
        return out

method encode ​

torch_world.models.DINOWM.encode GitHub

python
encode(pixels: Tensor, proprio: Tensor | None = None) -> Tensor

pixels (B, T, C, H, W) and proprio (B, T, proprio_dim) to (B, T, P, D').

Source code in torch_world/models/dino/_dinowm.py
python
def encode(self, pixels: Tensor, proprio: Tensor | None = None) -> Tensor:
    """``pixels`` ``(B, T, C, H, W)`` and ``proprio`` ``(B, T, proprio_dim)`` to ``(B, T, P, D')``."""
    with torch.no_grad():
        z = self.encoder(pixels.flatten(0, 1)).unflatten(0, pixels.shape[:2])
    if self.proprio_encoder is not None:
        z = torch.cat([z, self._tile(self.proprio_encoder(proprio))], dim=-1)
    return z

method forward ​

torch_world.models.DINOWM.forward GitHub

python
forward(
    pixels: Tensor, actions: Tensor, proprio: Tensor | None = None
) -> dict[str, Tensor]

pixels (B, history + 1, C, H, W), actions (B, history + 1, action_dim).

Source code in torch_world/models/dino/_dinowm.py
python
def forward(self, pixels: Tensor, actions: Tensor, proprio: Tensor | None = None) -> dict[str, Tensor]:
    """``pixels`` ``(B, history + 1, C, H, W)``, ``actions`` ``(B, history + 1, action_dim)``."""
    z = self.encode(pixels, proprio)
    pred = self.predict(z[:, : self.history], actions[:, : self.history])
    target = z[:, 1 : self.history + 1].detach()
    out = {"loss": F.mse_loss(pred, target)}
    if self.proprio_encoder is not None:
        d = self.proprio_encoder.out_features
        out["visual_loss"] = F.mse_loss(pred[..., :-d], target[..., :-d])
        out["proprio_loss"] = F.mse_loss(pred[..., -d:], target[..., -d:])
    return out

class TDMPC2 ​

torch_world.models.TDMPC2 GitHub

python
TDMPC2(
    encoder: nn.Module,
    action_dim: int,
    latent_dim: int = 512,
    mlp_dim: int = 512,
    num_q: int = 5,
    dropout: float = 0.01,
    simnorm_dim: int = 8,
    num_bins: int = 101,
    vmin: float = -10.0,
    vmax: float = 10.0,
    log_std_min: float = -10.0,
    log_std_max: float = 2.0,
    discount: float = 0.99,
    rho: float = 0.5,
    consistency_coef: float = 20.0,
    reward_coef: float = 0.1,
    value_coef: float = 0.1,
    termination_coef: float = 1.0,
    entropy_coef: float = 0.0001,
    scale_momentum: float = 0.99,
    episodic: bool = False,
    goal_conditioned: bool = False,
)

TD-MPC2: a decoder-free latent world model trained with temporal-difference learning, planned with MPPI.

An encoder maps observations to SimNorm latents. From the first latent, a deterministic MLP dynamics model unrolls the batch's actions; every imagined latent is pulled toward the encoding of the real next observation (consistency), and predicts the reward and, through an ensemble of num_q Q-functions, the TD target r + discount * Q_target(z', pi(z')). Rewards and values are regressed as discrete distributions: cross-entropy against two-hot targets over num_bins bins in symlog space. All terms are weighted by rho ** t.

A tanh-Gaussian policy prior maximizes the scale-normalized Q-value plus an entropy bonus, on detached latents and through Q-functions it cannot update; it proposes trajectories to the planner and bootstraps returns. Plan with MPPI, which scores action sequences with estimate_value. Actions are in [-1, 1].

forward returns the world-model loss plus the policy loss: their gradients reach disjoint parameters, so one backward pass matches the reference's two updates, except that the policy loss sees the Q-functions before, not after, this step's update. Train with param_groups, clip with clip_grad_norm and call update_target after every optimizer step. The reference's multi-task embeddings are not included.

With goal_conditioned, observations carry a goal stacked on their channel (or feature) dimension 2, as (B, T, 2 * C, ...): the encoder maps the observation and the goal separately, and the latent is both, side by side, (..., 2 * latent_dim). Dynamics move the observation's half and carry the goal's, so the consistency loss has no reason to drop the goal, and the reward, Q-functions and policy read it, as they read the task embedding in the reference's multi-task agent. Train on goals relabelled in hindsight, with rewards that measure progress to them. Trained offline this way, the reference weights (consistency 20, reward and value 0.1) can collapse the encoder to a near-constant latent, as nothing but the weak reward and value terms keeps latents apart; TDMPC2.offline_goal_conditioned builds the model with the weights that work there.

Hansen et al., "TD-MPC2: Scalable, Robust World Models for Continuous Control", ICLR 2024. Paper: https://arxiv.org/abs/2310.16828 Code: https://github.com/nicklashansen/tdmpc2

Parameters

NameTypeDescriptionDefault
encodernn.Modulemodule mapping observations (N, ...) to SimNorm latents (N, latent_dim), such as state_encoder or pixel_encoder.required
action_dimintdimension of one action.required
discountfloatreward discount; TDMPC2.episode_discount gives the reference's choice for an episode length.0.99
episodicboollearn a termination head, used in the TD targets and to stop imagined returns.False
goal_conditionedboolobservations carry a goal on dimension 2; every head reads its latent.False

Members

MemberDescription
offline_goal_conditionedTD-MPC2 for offline goal-conditioned training: goal_conditioned and episodic, with the loss weights of OFFLINE_GOAL_COEFS (consistency 2, reward 1, value 1) unless kwargs override them.
episode_discountThe reference's discount for fixed-length episodes: (L / denom - 1) / (L / denom), clipped.
param_groupsAdam groups as in the reference: the encoder at encoder_lr_scale * lr, the policy with eps=1e-5.
clip_grad_normClip the world model's and the policy's gradients separately, as the reference does; returns both norms.
update_targetPolyak update of the target Q-functions; the reference's tau is 1 - momentum.
two_hotScalars (...) to soft two-hot targets (..., num_bins) over bins evenly spaced in symlog space.
two_hot_invLogits (..., num_bins) to the scalars (...) of their expected bin.
soft_ceCross-entropy (...) of logits (..., num_bins) against the two-hot encoding of target (...).
encode(B, T, ...) to (B, T, latent_dim), or (B, T, 2 * latent_dim) with goal_conditioned.
predictNext latents from latents (..., latent_dim) and actions (..., action_dim); a goal's half is kept.
qQ-values of latents (..., latent_dim) and actions (..., action_dim).
piSample tanh-squashed actions (..., action_dim) from the policy prior.
estimate_valueDiscounted return (N,) of action sequences (N, H, action_dim) from latents (N, latent_dim): predicted rewards, then the mean of two Q-values for a policy action at the last latent.
forwardobs (B, H + 1, ...), actions (B, H, action_dim), rewards (B, H) and, when episodic, terminated (B, H): whether obs[:, t + 1] ends the episode.
Source code in torch_world/models/tdmpc/_tdmpc2.py
python
class TDMPC2(WorldModel):
    """TD-MPC2: a decoder-free latent world model trained with temporal-difference learning, planned with MPPI.

    An encoder maps observations to ``SimNorm`` latents. From the first latent, a deterministic MLP dynamics model
    unrolls the batch's actions; every imagined latent is pulled toward the encoding of the real next observation
    (consistency), and predicts the reward and, through an ensemble of ``num_q`` Q-functions, the TD target
    ``r + discount * Q_target(z', pi(z'))``. Rewards and values are regressed as discrete distributions: cross-entropy
    against two-hot targets over ``num_bins`` bins in symlog space. All terms are weighted by ``rho ** t``.

    A tanh-Gaussian policy prior maximizes the scale-normalized Q-value plus an entropy bonus, on detached latents and
    through Q-functions it cannot update; it proposes trajectories to the planner and bootstraps returns. Plan with
    ``MPPI``, which scores action sequences with ``estimate_value``. Actions are in ``[-1, 1]``.

    ``forward`` returns the world-model loss plus the policy loss: their gradients reach disjoint parameters, so one
    backward pass matches the reference's two updates, except that the policy loss sees the Q-functions before, not
    after, this step's update. Train with ``param_groups``, clip with ``clip_grad_norm`` and call ``update_target``
    after every optimizer step. The reference's multi-task embeddings are not included.

    With ``goal_conditioned``, observations carry a goal stacked on their channel (or feature) dimension ``2``, as
    ``(B, T, 2 * C, ...)``: the encoder maps the observation and the goal separately, and the latent is both, side by
    side, ``(..., 2 * latent_dim)``. Dynamics move the observation's half and carry the goal's, so the consistency
    loss has no reason to drop the goal, and the reward, Q-functions and policy read it, as they read the task
    embedding in the reference's multi-task agent. Train on goals relabelled in hindsight, with rewards that measure
    progress to them. Trained offline this way, the reference weights (consistency 20, reward and value 0.1) can
    collapse the encoder to a near-constant latent, as nothing but the weak reward and value terms keeps latents
    apart; ``TDMPC2.offline_goal_conditioned`` builds the model with the weights that work there.

    Hansen et al., "TD-MPC2: Scalable, Robust World Models for Continuous Control", ICLR 2024.
    Paper: https://arxiv.org/abs/2310.16828
    Code: https://github.com/nicklashansen/tdmpc2

    Args:
        encoder: module mapping observations ``(N, ...)`` to ``SimNorm`` latents ``(N, latent_dim)``, such as
            ``state_encoder`` or ``pixel_encoder``.
        action_dim: dimension of one action.
        discount: reward discount; ``TDMPC2.episode_discount`` gives the reference's choice for an episode length.
        episodic: learn a termination head, used in the TD targets and to stop imagined returns.
        goal_conditioned: observations carry a goal on dimension 2; every head reads its latent.
    """

    history = 1

    def __init__(
        self,
        encoder: nn.Module,
        action_dim: int,
        latent_dim: int = 512,
        mlp_dim: int = 512,
        num_q: int = 5,
        dropout: float = 0.01,
        simnorm_dim: int = 8,
        num_bins: int = 101,
        vmin: float = -10.0,
        vmax: float = 10.0,
        log_std_min: float = -10.0,
        log_std_max: float = 2.0,
        discount: float = 0.99,
        rho: float = 0.5,
        consistency_coef: float = 20.0,
        reward_coef: float = 0.1,
        value_coef: float = 0.1,
        termination_coef: float = 1.0,
        entropy_coef: float = 1e-4,
        scale_momentum: float = 0.99,
        episodic: bool = False,
        goal_conditioned: bool = False,
    ):
        super().__init__()
        self.action_dim, self.num_q, self.discount, self.rho = action_dim, num_q, discount, rho
        self.vmin, self.vmax, self.bin_size = vmin, vmax, (vmax - vmin) / (num_bins - 1)
        self.log_std_min, self.log_std_max = log_std_min, log_std_max
        self.consistency_coef, self.reward_coef, self.value_coef = consistency_coef, reward_coef, value_coef
        self.termination_coef, self.entropy_coef, self.scale_momentum = termination_coef, entropy_coef, scale_momentum
        self.latent_dim, self.goal_conditioned = latent_dim, goal_conditioned
        z_dim = 2 * latent_dim if goal_conditioned else latent_dim  # what the heads read: the goal's latent too
        za, hidden = z_dim + action_dim, [mlp_dim, mlp_dim]
        self.encoder = encoder
        self.dynamics = _init(mlp([latent_dim + action_dim, *hidden, latent_dim], act=SimNorm(simnorm_dim)))
        self.reward = _init(mlp([za, *hidden, num_bins]))
        self.termination = _init(mlp([z_dim, *hidden, 1])) if episodic else None
        self.policy = _init(mlp([z_dim, *hidden, 2 * action_dim]))
        self.qs = nn.ModuleList(_init(mlp([za, *hidden, num_bins], dropout=dropout)) for _ in range(num_q))
        for head in [self.reward, *self.qs]:
            nn.init.zeros_(head[-1].weight)
        self.target_qs = copy.deepcopy(self.qs).requires_grad_(False).eval()
        self.register_buffer("bins", torch.linspace(vmin, vmax, num_bins))
        self.register_buffer("q_scale", torch.ones(()))
        if goal_conditioned and (consistency_coef, reward_coef, value_coef) == (20.0, 0.1, 0.1):
            warnings.warn(
                "TDMPC2 with goal_conditioned=True and the reference loss weights (consistency 20, reward 0.1, "
                "value 0.1) can collapse its encoder when trained offline; use TDMPC2.offline_goal_conditioned or "
                "pass consistency_coef=2, reward_coef=1, value_coef=1.",
                stacklevel=2,
            )

    OFFLINE_GOAL_COEFS: ClassVar[dict[str, float]] = {"consistency_coef": 2.0, "reward_coef": 1.0, "value_coef": 1.0}

    @classmethod
    def offline_goal_conditioned(cls, encoder: nn.Module, action_dim: int, **kwargs) -> "TDMPC2":
        """TD-MPC2 for offline goal-conditioned training: ``goal_conditioned`` and ``episodic``, with the loss
        weights of ``OFFLINE_GOAL_COEFS`` (consistency 2, reward 1, value 1) unless ``kwargs`` override them.

        Offline, with goals relabelled in hindsight and a reward of -1 per step until the goal, the reference
        weights let the consistency loss, which a constant encoder drives to zero, outweigh the reward and value
        terms 200 to 1, and the encoder collapses. Pair it with temporal-distance relabelling: goals a geometric
        number of steps ahead in the same episode, some from other episodes, and termination at the goal.
        """
        kwargs = {"goal_conditioned": True, "episodic": True, **cls.OFFLINE_GOAL_COEFS, **kwargs}
        return cls(encoder, action_dim, **kwargs)

    @staticmethod
    def episode_discount(episode_length: int, denom: float = 5, low: float = 0.95, high: float = 0.995) -> float:
        """The reference's discount for fixed-length episodes: ``(L / denom - 1) / (L / denom)``, clipped."""
        frac = episode_length / denom
        return min(max((frac - 1) / frac, low), high)

    def train(self, mode: bool = True):
        super().train(mode)
        self.target_qs.eval()
        return self

    def param_groups(self, lr: float = 3e-4, encoder_lr_scale: float = 0.3) -> list[dict]:
        """Adam groups as in the reference: the encoder at ``encoder_lr_scale * lr``, the policy with ``eps=1e-5``."""
        encoder, policy = list(self.encoder.parameters()), list(self.policy.parameters())
        skip = {id(p) for p in encoder + policy}
        rest = [p for p in self.parameters() if p.requires_grad and id(p) not in skip]
        return [
            {"params": encoder, "lr": lr * encoder_lr_scale},
            {"params": rest, "lr": lr},
            {"params": policy, "lr": lr, "eps": 1e-5},
        ]

    def clip_grad_norm(self, max_norm: float = 20.0) -> tuple[Tensor, Tensor]:
        """Clip the world model's and the policy's gradients separately, as the reference does; returns both norms."""
        policy = {id(p) for p in self.policy.parameters()}
        world = [p for p in self.parameters() if p.requires_grad and id(p) not in policy]
        return nn.utils.clip_grad_norm_(world, max_norm), nn.utils.clip_grad_norm_(self.policy.parameters(), max_norm)

    def update_target(self, momentum: float = 0.99):
        """Polyak update of the target Q-functions; the reference's ``tau`` is ``1 - momentum``."""
        ema_update(self.target_qs, self.qs, momentum)

    def two_hot(self, x: Tensor) -> Tensor:
        """Scalars ``(...)`` to soft two-hot targets ``(..., num_bins)`` over bins evenly spaced in symlog space."""
        pos = (symlog(x).clamp(self.vmin, self.vmax) - self.vmin) / self.bin_size
        idx = pos.floor()
        offset = (pos - idx)[..., None]
        idx = idx.long()[..., None]
        out = x.new_zeros(*x.shape, self.bins.numel()).scatter(-1, idx, 1 - offset)
        return out.scatter(-1, (idx + 1) % self.bins.numel(), offset)

    def two_hot_inv(self, logits: Tensor) -> Tensor:
        """Logits ``(..., num_bins)`` to the scalars ``(...)`` of their expected bin."""
        return symexp((logits.softmax(-1) * self.bins).sum(-1))

    def soft_ce(self, logits: Tensor, target: Tensor) -> Tensor:
        """Cross-entropy ``(...)`` of logits ``(..., num_bins)`` against the two-hot encoding of ``target`` ``(...)``."""
        return -(self.two_hot(target) * logits.log_softmax(-1)).sum(-1)

    def encode(self, obs: Tensor) -> Tensor:
        """``(B, T, ...)`` to ``(B, T, latent_dim)``, or ``(B, T, 2 * latent_dim)`` with ``goal_conditioned``."""
        if self.goal_conditioned:
            return torch.cat([self._encode(half) for half in obs.chunk(2, dim=2)], dim=-1)
        return self._encode(obs)

    def _encode(self, obs: Tensor) -> Tensor:
        return self.encoder(obs.flatten(0, 1)).unflatten(0, obs.shape[:2])

    def predict(self, z: Tensor, actions: Tensor) -> Tensor:
        """Next latents from latents ``(..., latent_dim)`` and actions ``(..., action_dim)``; a goal's half is kept."""
        if self.goal_conditioned:
            z, goal = z.split(self.latent_dim, dim=-1)
            return torch.cat([self.dynamics(torch.cat([z, actions], dim=-1)), goal], dim=-1)
        return self.dynamics(torch.cat([z, actions], dim=-1))

    def q(self, z: Tensor, actions: Tensor, reduce: str = "all", target: bool = False, detach: bool = False) -> Tensor:
        """Q-values of latents ``(..., latent_dim)`` and actions ``(..., action_dim)``.

        ``"all"`` returns the logits ``(num_q, ..., num_bins)`` of every Q-function; ``"min"`` and ``"mean"`` return
        the min or mean ``(...)`` of two Q-functions drawn at random. ``target`` uses the target Q-functions;
        ``detach`` lets gradients reach the actions and latents but not the Q-functions.
        """
        x = torch.cat([z, actions], dim=-1)
        nets = self.target_qs if target else self.qs
        if detach:
            out = [functional_call(q, {k: v.detach() for k, v in q.named_parameters()}, (x,)) for q in nets]
        else:
            out = [q(x) for q in nets]
        logits = torch.stack(out)
        if reduce == "all":
            return logits
        values = self.two_hot_inv(logits[torch.randperm(self.num_q, device=x.device)[:2]])
        if reduce == "min":
            return values.min(0).values
        if reduce == "mean":
            return values.mean(0)
        raise ValueError(f"reduce must be 'all', 'min' or 'mean', not {reduce!r}")

    def pi(self, z: Tensor) -> tuple[Tensor, dict[str, Tensor]]:
        """Sample tanh-squashed actions ``(..., action_dim)`` from the policy prior.

        The info dict holds the squashed ``"mean"``, the ``"log_std"``, the ``"entropy"`` of the squashed sample and
        the reference's ``"scaled_entropy"``: the Gaussian's, before squashing, times ``action_dim``.
        """
        mean, log_std = self.policy(z).chunk(2, dim=-1)
        log_std = self.log_std_min + 0.5 * (self.log_std_max - self.log_std_min) * (log_std.tanh() + 1)
        eps = torch.randn_like(mean)
        log_prob = (-0.5 * eps.square() - log_std - 0.5 * math.log(2 * math.pi)).sum(-1)
        action = (mean + eps * log_std.exp()).tanh()
        squashed = log_prob - torch.log(F.relu(1 - action.square()) + 1e-6).sum(-1)
        info = {
            "mean": mean.tanh(),
            "log_std": log_std,
            "entropy": -squashed,
            "scaled_entropy": -log_prob * eps.size(-1),
        }
        return action, info

    def estimate_value(self, z: Tensor, actions: Tensor) -> Tensor:
        """Discounted return ``(N,)`` of action sequences ``(N, H, action_dim)`` from latents ``(N, latent_dim)``:
        predicted rewards, then the mean of two Q-values for a policy action at the last latent."""
        ret, discount, alive = 0.0, 1.0, z.new_ones(z.size(0))
        for a in actions.unbind(1):
            reward = self.two_hot_inv(self.reward(torch.cat([z, a], dim=-1)))
            z = self.predict(z, a)
            ret = ret + discount * alive * reward
            discount = discount * self.discount
            if self.termination is not None:
                alive = alive * (self.termination(z).squeeze(-1) <= 0)
        return ret + discount * alive * self.q(z, self.pi(z)[0], "mean")

    def forward(
        self, obs: Tensor, actions: Tensor, rewards: Tensor, terminated: Tensor | None = None
    ) -> dict[str, Tensor]:
        """``obs`` ``(B, H + 1, ...)``, ``actions`` ``(B, H, action_dim)``, ``rewards`` ``(B, H)`` and, when
        episodic, ``terminated`` ``(B, H)``: whether ``obs[:, t + 1]`` ends the episode. ``actions[:, t]`` is applied
        at ``obs[:, t]`` and earns ``rewards[:, t]``."""
        H = actions.size(1)
        terminated = torch.zeros_like(rewards) if terminated is None else terminated.to(rewards.dtype)
        with torch.no_grad():
            next_z = self.encode(obs[:, 1:])
            td_target = rewards + self.discount * (1 - terminated) * self.q(
                next_z, self.pi(next_z)[0], "min", target=True
            )

        zs = [self.encode(obs[:, :1])[:, 0]]
        for t in range(H):
            zs.append(self.predict(zs[-1], actions[:, t]))
        zs = torch.stack(zs, dim=1)
        rho = self.rho ** torch.arange(H + 1, device=zs.device, dtype=zs.dtype)
        x = torch.cat([zs[:, :-1], actions], dim=-1)
        consistency = ((zs[:, 1:] - next_z).square().mean((0, 2)) * rho[:H]).sum() / H
        reward = (self.soft_ce(self.reward(x), rewards).mean(0) * rho[:H]).sum() / H
        value = (self.soft_ce(self.q(zs[:, :-1], actions), td_target).mean((0, 1)) * rho[:H]).sum() / H
        loss = self.consistency_coef * consistency + self.reward_coef * reward + self.value_coef * value
        out = {"consistency_loss": consistency, "reward_loss": reward, "value_loss": value}
        if self.termination is not None:
            out["termination_loss"] = F.binary_cross_entropy_with_logits(
                self.termination(zs[:, 1:]).squeeze(-1), terminated
            )
            loss = loss + self.termination_coef * out["termination_loss"]

        z = zs.detach()
        action, info = self.pi(z)
        q = self.q(z, action, "mean", detach=True)
        if self.training:
            low, high = torch.quantile(q[:, 0].detach(), q.new_tensor([0.05, 0.95]))
            self.q_scale.lerp_((high - low).clamp(min=1.0), 1 - self.scale_momentum)
        pi = (-(self.entropy_coef * info["scaled_entropy"] + q / self.q_scale).mean(0) * rho).mean()
        return {"loss": loss + pi, **out, "pi_loss": pi}

method offline_goal_conditioned ​

torch_world.models.TDMPC2.offline_goal_conditioned GitHub

python
offline_goal_conditioned(
    encoder: nn.Module, action_dim: int, **kwargs
) -> TDMPC2

TD-MPC2 for offline goal-conditioned training: goal_conditioned and episodic, with the loss weights of OFFLINE_GOAL_COEFS (consistency 2, reward 1, value 1) unless kwargs override them.

Offline, with goals relabelled in hindsight and a reward of -1 per step until the goal, the reference weights let the consistency loss, which a constant encoder drives to zero, outweigh the reward and value terms 200 to 1, and the encoder collapses. Pair it with temporal-distance relabelling: goals a geometric number of steps ahead in the same episode, some from other episodes, and termination at the goal.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
@classmethod
def offline_goal_conditioned(cls, encoder: nn.Module, action_dim: int, **kwargs) -> "TDMPC2":
    """TD-MPC2 for offline goal-conditioned training: ``goal_conditioned`` and ``episodic``, with the loss
    weights of ``OFFLINE_GOAL_COEFS`` (consistency 2, reward 1, value 1) unless ``kwargs`` override them.

    Offline, with goals relabelled in hindsight and a reward of -1 per step until the goal, the reference
    weights let the consistency loss, which a constant encoder drives to zero, outweigh the reward and value
    terms 200 to 1, and the encoder collapses. Pair it with temporal-distance relabelling: goals a geometric
    number of steps ahead in the same episode, some from other episodes, and termination at the goal.
    """
    kwargs = {"goal_conditioned": True, "episodic": True, **cls.OFFLINE_GOAL_COEFS, **kwargs}
    return cls(encoder, action_dim, **kwargs)

method episode_discount ​

torch_world.models.TDMPC2.episode_discount GitHub

python
episode_discount(
    episode_length: int,
    denom: float = 5,
    low: float = 0.95,
    high: float = 0.995,
) -> float

The reference's discount for fixed-length episodes: (L / denom - 1) / (L / denom), clipped.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
@staticmethod
def episode_discount(episode_length: int, denom: float = 5, low: float = 0.95, high: float = 0.995) -> float:
    """The reference's discount for fixed-length episodes: ``(L / denom - 1) / (L / denom)``, clipped."""
    frac = episode_length / denom
    return min(max((frac - 1) / frac, low), high)

method param_groups ​

torch_world.models.TDMPC2.param_groups GitHub

python
param_groups(
    lr: float = 0.0003, encoder_lr_scale: float = 0.3
) -> list[dict]

Adam groups as in the reference: the encoder at encoder_lr_scale * lr, the policy with eps=1e-5.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def param_groups(self, lr: float = 3e-4, encoder_lr_scale: float = 0.3) -> list[dict]:
    """Adam groups as in the reference: the encoder at ``encoder_lr_scale * lr``, the policy with ``eps=1e-5``."""
    encoder, policy = list(self.encoder.parameters()), list(self.policy.parameters())
    skip = {id(p) for p in encoder + policy}
    rest = [p for p in self.parameters() if p.requires_grad and id(p) not in skip]
    return [
        {"params": encoder, "lr": lr * encoder_lr_scale},
        {"params": rest, "lr": lr},
        {"params": policy, "lr": lr, "eps": 1e-5},
    ]

method clip_grad_norm ​

torch_world.models.TDMPC2.clip_grad_norm GitHub

python
clip_grad_norm(max_norm: float = 20.0) -> tuple[Tensor, Tensor]

Clip the world model's and the policy's gradients separately, as the reference does; returns both norms.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def clip_grad_norm(self, max_norm: float = 20.0) -> tuple[Tensor, Tensor]:
    """Clip the world model's and the policy's gradients separately, as the reference does; returns both norms."""
    policy = {id(p) for p in self.policy.parameters()}
    world = [p for p in self.parameters() if p.requires_grad and id(p) not in policy]
    return nn.utils.clip_grad_norm_(world, max_norm), nn.utils.clip_grad_norm_(self.policy.parameters(), max_norm)

method update_target ​

torch_world.models.TDMPC2.update_target GitHub

python
update_target(momentum: float = 0.99)

Polyak update of the target Q-functions; the reference's tau is 1 - momentum.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def update_target(self, momentum: float = 0.99):
    """Polyak update of the target Q-functions; the reference's ``tau`` is ``1 - momentum``."""
    ema_update(self.target_qs, self.qs, momentum)

method two_hot ​

torch_world.models.TDMPC2.two_hot GitHub

python
two_hot(x: Tensor) -> Tensor

Scalars (...) to soft two-hot targets (..., num_bins) over bins evenly spaced in symlog space.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def two_hot(self, x: Tensor) -> Tensor:
    """Scalars ``(...)`` to soft two-hot targets ``(..., num_bins)`` over bins evenly spaced in symlog space."""
    pos = (symlog(x).clamp(self.vmin, self.vmax) - self.vmin) / self.bin_size
    idx = pos.floor()
    offset = (pos - idx)[..., None]
    idx = idx.long()[..., None]
    out = x.new_zeros(*x.shape, self.bins.numel()).scatter(-1, idx, 1 - offset)
    return out.scatter(-1, (idx + 1) % self.bins.numel(), offset)

method two_hot_inv ​

torch_world.models.TDMPC2.two_hot_inv GitHub

python
two_hot_inv(logits: Tensor) -> Tensor

Logits (..., num_bins) to the scalars (...) of their expected bin.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def two_hot_inv(self, logits: Tensor) -> Tensor:
    """Logits ``(..., num_bins)`` to the scalars ``(...)`` of their expected bin."""
    return symexp((logits.softmax(-1) * self.bins).sum(-1))

method soft_ce ​

torch_world.models.TDMPC2.soft_ce GitHub

python
soft_ce(logits: Tensor, target: Tensor) -> Tensor

Cross-entropy (...) of logits (..., num_bins) against the two-hot encoding of target (...).

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def soft_ce(self, logits: Tensor, target: Tensor) -> Tensor:
    """Cross-entropy ``(...)`` of logits ``(..., num_bins)`` against the two-hot encoding of ``target`` ``(...)``."""
    return -(self.two_hot(target) * logits.log_softmax(-1)).sum(-1)

method encode ​

torch_world.models.TDMPC2.encode GitHub

python
encode(obs: Tensor) -> Tensor

(B, T, ...) to (B, T, latent_dim), or (B, T, 2 * latent_dim) with goal_conditioned.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def encode(self, obs: Tensor) -> Tensor:
    """``(B, T, ...)`` to ``(B, T, latent_dim)``, or ``(B, T, 2 * latent_dim)`` with ``goal_conditioned``."""
    if self.goal_conditioned:
        return torch.cat([self._encode(half) for half in obs.chunk(2, dim=2)], dim=-1)
    return self._encode(obs)

method predict ​

torch_world.models.TDMPC2.predict GitHub

python
predict(z: Tensor, actions: Tensor) -> Tensor

Next latents from latents (..., latent_dim) and actions (..., action_dim); a goal's half is kept.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def predict(self, z: Tensor, actions: Tensor) -> Tensor:
    """Next latents from latents ``(..., latent_dim)`` and actions ``(..., action_dim)``; a goal's half is kept."""
    if self.goal_conditioned:
        z, goal = z.split(self.latent_dim, dim=-1)
        return torch.cat([self.dynamics(torch.cat([z, actions], dim=-1)), goal], dim=-1)
    return self.dynamics(torch.cat([z, actions], dim=-1))

method q ​

torch_world.models.TDMPC2.q GitHub

python
q(
    z: Tensor,
    actions: Tensor,
    reduce: str = "all",
    target: bool = False,
    detach: bool = False,
) -> Tensor

Q-values of latents (..., latent_dim) and actions (..., action_dim).

"all" returns the logits (num_q, ..., num_bins) of every Q-function; "min" and "mean" return the min or mean (...) of two Q-functions drawn at random. target uses the target Q-functions; detach lets gradients reach the actions and latents but not the Q-functions.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def q(self, z: Tensor, actions: Tensor, reduce: str = "all", target: bool = False, detach: bool = False) -> Tensor:
    """Q-values of latents ``(..., latent_dim)`` and actions ``(..., action_dim)``.

    ``"all"`` returns the logits ``(num_q, ..., num_bins)`` of every Q-function; ``"min"`` and ``"mean"`` return
    the min or mean ``(...)`` of two Q-functions drawn at random. ``target`` uses the target Q-functions;
    ``detach`` lets gradients reach the actions and latents but not the Q-functions.
    """
    x = torch.cat([z, actions], dim=-1)
    nets = self.target_qs if target else self.qs
    if detach:
        out = [functional_call(q, {k: v.detach() for k, v in q.named_parameters()}, (x,)) for q in nets]
    else:
        out = [q(x) for q in nets]
    logits = torch.stack(out)
    if reduce == "all":
        return logits
    values = self.two_hot_inv(logits[torch.randperm(self.num_q, device=x.device)[:2]])
    if reduce == "min":
        return values.min(0).values
    if reduce == "mean":
        return values.mean(0)
    raise ValueError(f"reduce must be 'all', 'min' or 'mean', not {reduce!r}")

method pi ​

torch_world.models.TDMPC2.pi GitHub

python
pi(z: Tensor) -> tuple[Tensor, dict[str, Tensor]]

Sample tanh-squashed actions (..., action_dim) from the policy prior.

The info dict holds the squashed "mean", the "log_std", the "entropy" of the squashed sample and the reference's "scaled_entropy": the Gaussian's, before squashing, times action_dim.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def pi(self, z: Tensor) -> tuple[Tensor, dict[str, Tensor]]:
    """Sample tanh-squashed actions ``(..., action_dim)`` from the policy prior.

    The info dict holds the squashed ``"mean"``, the ``"log_std"``, the ``"entropy"`` of the squashed sample and
    the reference's ``"scaled_entropy"``: the Gaussian's, before squashing, times ``action_dim``.
    """
    mean, log_std = self.policy(z).chunk(2, dim=-1)
    log_std = self.log_std_min + 0.5 * (self.log_std_max - self.log_std_min) * (log_std.tanh() + 1)
    eps = torch.randn_like(mean)
    log_prob = (-0.5 * eps.square() - log_std - 0.5 * math.log(2 * math.pi)).sum(-1)
    action = (mean + eps * log_std.exp()).tanh()
    squashed = log_prob - torch.log(F.relu(1 - action.square()) + 1e-6).sum(-1)
    info = {
        "mean": mean.tanh(),
        "log_std": log_std,
        "entropy": -squashed,
        "scaled_entropy": -log_prob * eps.size(-1),
    }
    return action, info

method estimate_value ​

torch_world.models.TDMPC2.estimate_value GitHub

python
estimate_value(z: Tensor, actions: Tensor) -> Tensor

Discounted return (N,) of action sequences (N, H, action_dim) from latents (N, latent_dim): predicted rewards, then the mean of two Q-values for a policy action at the last latent.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def estimate_value(self, z: Tensor, actions: Tensor) -> Tensor:
    """Discounted return ``(N,)`` of action sequences ``(N, H, action_dim)`` from latents ``(N, latent_dim)``:
    predicted rewards, then the mean of two Q-values for a policy action at the last latent."""
    ret, discount, alive = 0.0, 1.0, z.new_ones(z.size(0))
    for a in actions.unbind(1):
        reward = self.two_hot_inv(self.reward(torch.cat([z, a], dim=-1)))
        z = self.predict(z, a)
        ret = ret + discount * alive * reward
        discount = discount * self.discount
        if self.termination is not None:
            alive = alive * (self.termination(z).squeeze(-1) <= 0)
    return ret + discount * alive * self.q(z, self.pi(z)[0], "mean")

method forward ​

torch_world.models.TDMPC2.forward GitHub

python
forward(
    obs: Tensor,
    actions: Tensor,
    rewards: Tensor,
    terminated: Tensor | None = None,
) -> dict[str, Tensor]

obs (B, H + 1, ...), actions (B, H, action_dim), rewards (B, H) and, when episodic, terminated (B, H): whether obs[:, t + 1] ends the episode. actions[:, t] is applied at obs[:, t] and earns rewards[:, t].

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def forward(
    self, obs: Tensor, actions: Tensor, rewards: Tensor, terminated: Tensor | None = None
) -> dict[str, Tensor]:
    """``obs`` ``(B, H + 1, ...)``, ``actions`` ``(B, H, action_dim)``, ``rewards`` ``(B, H)`` and, when
    episodic, ``terminated`` ``(B, H)``: whether ``obs[:, t + 1]`` ends the episode. ``actions[:, t]`` is applied
    at ``obs[:, t]`` and earns ``rewards[:, t]``."""
    H = actions.size(1)
    terminated = torch.zeros_like(rewards) if terminated is None else terminated.to(rewards.dtype)
    with torch.no_grad():
        next_z = self.encode(obs[:, 1:])
        td_target = rewards + self.discount * (1 - terminated) * self.q(
            next_z, self.pi(next_z)[0], "min", target=True
        )

    zs = [self.encode(obs[:, :1])[:, 0]]
    for t in range(H):
        zs.append(self.predict(zs[-1], actions[:, t]))
    zs = torch.stack(zs, dim=1)
    rho = self.rho ** torch.arange(H + 1, device=zs.device, dtype=zs.dtype)
    x = torch.cat([zs[:, :-1], actions], dim=-1)
    consistency = ((zs[:, 1:] - next_z).square().mean((0, 2)) * rho[:H]).sum() / H
    reward = (self.soft_ce(self.reward(x), rewards).mean(0) * rho[:H]).sum() / H
    value = (self.soft_ce(self.q(zs[:, :-1], actions), td_target).mean((0, 1)) * rho[:H]).sum() / H
    loss = self.consistency_coef * consistency + self.reward_coef * reward + self.value_coef * value
    out = {"consistency_loss": consistency, "reward_loss": reward, "value_loss": value}
    if self.termination is not None:
        out["termination_loss"] = F.binary_cross_entropy_with_logits(
            self.termination(zs[:, 1:]).squeeze(-1), terminated
        )
        loss = loss + self.termination_coef * out["termination_loss"]

    z = zs.detach()
    action, info = self.pi(z)
    q = self.q(z, action, "mean", detach=True)
    if self.training:
        low, high = torch.quantile(q[:, 0].detach(), q.new_tensor([0.05, 0.95]))
        self.q_scale.lerp_((high - low).clamp(min=1.0), 1 - self.scale_momentum)
    pi = (-(self.entropy_coef * info["scaled_entropy"] + q / self.q_scale).mean(0) * rho).mean()
    return {"loss": loss + pi, **out, "pi_loss": pi}

class DreamZero ​

torch_world.models.DreamZero GitHub

python
DreamZero(
    latent_channels: int,
    latent_size: tuple[int, int],
    action_dim: int,
    *,
    state_dim: int = 0,
    patch_size: int = 1,
    chunk_frames: int = 2,
    chunk_actions: int = 8,
    num_chunks: int = 4,
    dim: int = 256,
    depth: int = 6,
    num_heads: int = 8,
    mlp_dim: int | None = None,
    dropout: float = 0.0,
    flow_steps: int = 16,
    goal_conditioned: bool = False,
    action_weight: float = 1.0,
    video_weight: float = 1.0,
    time_schedule: str = "uniform",
    flash_alpha: float | None = None,
    action_scale=None,
    action_mean=None,
    action_std=None,
    autoencoder: nn.Module | None = None,
    attention: str = "sdpa",
)

Autoregressive joint video-action diffusion transformer (Ye et al., 2026).

A World Action Model: one causal DiT denoises the next chunk of video latents and the action chunk that produces them with a single flow-matching objective. Chunk k holds chunk_frames latent frames, the chunk_actions actions executed over them and, with state_dim, the proprioceptive state q_k at its start. Training uses chunk-wise teacher forcing: every chunk of a clip is noised with its own flow time and attends to an anchor frame (and a goal frame when goal_conditioned), the clean earlier chunks and itself. Video and actions of a chunk share their time, except with flash_alpha, which draws video times from 1 - Beta(flash_alpha, 1) (DreamZero-Flash) so that few-step sampling denoises actions from still-noisy video. The loss is video_weight * flow_video + action_weight * flow_action; video_weight=0 keeps the architecture but trains a pure policy, the ablation that measures what predicting video adds. time_schedule="logit_normal" draws shared times from sigmoid(N(0, 1)) instead of the paper's U(0, 1).

Inputs are latents of a video autoencoder (ConvVideoAE, or the Wan VideoVAE of the paper). forward takes (B, 1 + num_chunks * chunk_frames, C, h, w) latents, (B, num_chunks * chunk_actions, A) actions in environment units and optional (B, num_chunks, state_dim) states. At inference imagine samples the next chunk from the latest num_chunks - 1 past chunks; DreamZeroPolicy runs it in closed loop, replacing the predicted latents in that context with encoded real observations after each chunk.

action_scale sets per-coordinate physical action units; action_mean/action_std z-score actions instead. Sampled actions are clipped to ±action_scale.

attention="flex" runs the block-causal mask as a FlexAttention BlockMask, compiled on CUDA, so masked-out blocks are skipped instead of materialized; masks are cached per sequence layout. Sampling computes the keys and values of the clean context once per chunk (context_cache) and denoises only the new chunk at every step.

Paper: https://arxiv.org/abs/2602.15922

Members

MemberDescription
normalize_actionsPhysical controls to training coordinates (z-score when statistics exist).
denormalize_actionsTraining coordinates to physical controls; bounds apply after conversion.
encodeVideo (B, T, 3, H, W) in [0, 1] to latents (B, T', C, h, w) with the autoencoder.
raw_frames_per_chunkVideo frames each chunk covers before the autoencoder's temporal compression.
attention_maskMask of prefix | clean chunks 1..clean | noisy chunks start.., cached per layout.
joint_velocityVideo and action velocities of n noisy chunks numbered start, ..., start + n - 1.
context_cachePer-layer keys and values of anchor (| goal) | clean chunks, computed once per chunk.
cached_velocityjoint_velocity of the one chunk after the cached context; it attends to all of it.
forwardTeacher-forced joint flow matching over num_chunks chunks.
imagineJointly sample the next chunk: latents (B, K, C, h, w) and physical actions (B, H, A).
inverse_dynamicsActions (B, H, A) denoised with the next chunk's video given clean, future (B, K, C, h, w).
sample_actionsThe policy: the action half of imagine.
predict_futureForward dynamics: denoise the next chunk's latents given its clean physical actions (B, H, A).
rolloutUnroll (B, T, A) actions, T a multiple of chunk_actions, chunk by chunk from context z.
Source code in torch_world/models/wam/_dreamzero.py
python
class DreamZero(WorldActionModel):
    """Autoregressive joint video-action diffusion transformer (Ye et al., 2026).

    A World Action Model: one causal DiT denoises the next chunk of video latents *and* the action chunk that
    produces them with a single flow-matching objective. Chunk ``k`` holds ``chunk_frames`` latent frames, the
    ``chunk_actions`` actions executed over them and, with ``state_dim``, the proprioceptive state ``q_k`` at its
    start. Training uses chunk-wise teacher forcing: every chunk of a clip is noised with its own flow time and attends
    to an anchor frame (and a goal frame when ``goal_conditioned``), the *clean* earlier chunks and itself. Video and
    actions of a chunk share their time, except with ``flash_alpha``, which draws video times from
    ``1 - Beta(flash_alpha, 1)`` (DreamZero-Flash) so that few-step sampling denoises actions from still-noisy video.
    The loss is ``video_weight * flow_video + action_weight * flow_action``; ``video_weight=0`` keeps the architecture
    but trains a pure policy, the ablation that measures what predicting video adds. ``time_schedule="logit_normal"``
    draws shared times from ``sigmoid(N(0, 1))`` instead of the paper's ``U(0, 1)``.

    Inputs are latents of a video autoencoder (``ConvVideoAE``, or the Wan ``VideoVAE`` of the paper). ``forward``
    takes ``(B, 1 + num_chunks * chunk_frames, C, h, w)`` latents, ``(B, num_chunks * chunk_actions, A)`` actions in
    environment units and optional ``(B, num_chunks, state_dim)`` states. At inference ``imagine`` samples the next
    chunk from the latest ``num_chunks - 1`` past chunks; ``DreamZeroPolicy`` runs it in closed loop, replacing the
    predicted latents in that context with encoded real observations after each chunk.

    ``action_scale`` sets per-coordinate physical action units; ``action_mean``/``action_std`` z-score actions instead.
    Sampled actions are clipped to ``±action_scale``.

    ``attention="flex"`` runs the block-causal mask as a FlexAttention ``BlockMask``, compiled on CUDA, so masked-out
    blocks are skipped instead of materialized; masks are cached per sequence layout. Sampling computes the keys and
    values of the clean context once per chunk (``context_cache``) and denoises only the new chunk at every step.

    Paper: https://arxiv.org/abs/2602.15922
    """

    history = None

    def __init__(
        self,
        latent_channels: int,
        latent_size: tuple[int, int],
        action_dim: int,
        *,
        state_dim: int = 0,
        patch_size: int = 1,
        chunk_frames: int = 2,
        chunk_actions: int = 8,
        num_chunks: int = 4,
        dim: int = 256,
        depth: int = 6,
        num_heads: int = 8,
        mlp_dim: int | None = None,
        dropout: float = 0.0,
        flow_steps: int = 16,
        goal_conditioned: bool = False,
        action_weight: float = 1.0,
        video_weight: float = 1.0,
        time_schedule: str = "uniform",
        flash_alpha: float | None = None,
        action_scale=None,
        action_mean=None,
        action_std=None,
        autoencoder: nn.Module | None = None,
        attention: str = "sdpa",
    ):
        super().__init__()
        h, w = latent_size
        if h % patch_size or w % patch_size:
            raise ValueError("latent_size must be divisible by patch_size")
        if min(latent_channels, action_dim, chunk_frames, chunk_actions, num_chunks, flow_steps) < 1 or state_dim < 0:
            raise ValueError("Model sizes and flow_steps must be positive")
        if dim % num_heads:
            raise ValueError("dim must be divisible by num_heads")
        if flash_alpha is not None and flash_alpha <= 0:
            raise ValueError("flash_alpha must be positive")
        if time_schedule not in ("uniform", "logit_normal") or min(action_weight, video_weight) < 0:
            raise ValueError("time_schedule must be 'uniform' or 'logit_normal', with nonnegative loss weights")
        if attention not in ("sdpa", "flex"):
            raise ValueError("attention must be 'sdpa' or 'flex'")
        self.attention, self._masks = attention, {}
        self.latent_channels, self.latent_size, self.patch_size = latent_channels, (h, w), patch_size
        self.grid = (h // patch_size, w // patch_size)
        self.tokens_per_frame = self.grid[0] * self.grid[1]
        self.action_dim, self.state_dim = action_dim, state_dim
        self.chunk_frames, self.chunk_size, self.num_chunks = chunk_frames, chunk_actions, num_chunks
        self.dim, self.flow_steps, self.goal_conditioned = dim, flow_steps, goal_conditioned
        self.action_weight, self.video_weight, self.flash_alpha = action_weight, video_weight, flash_alpha
        self.time_schedule = time_schedule
        self.autoencoder = autoencoder
        scale = torch.ones(action_dim) if action_scale is None else torch.as_tensor(action_scale, dtype=torch.float32)
        if scale.shape != (action_dim,) or (scale <= 0).any():
            raise ValueError("action_scale must hold one positive scale per action coordinate")
        if (action_mean is None) != (action_std is None):
            raise ValueError("Supply both action_mean and action_std")
        self.register_buffer("action_scale", scale.clone())
        self.register_buffer("action_mean", None if action_mean is None else torch.as_tensor(action_mean).float())
        self.register_buffer("action_std", None if action_std is None else torch.as_tensor(action_std).float())

        patch_dim = latent_channels * patch_size**2
        self.video_in, self.video_out = nn.Linear(patch_dim, dim), nn.Linear(dim, patch_dim)
        self.action_encoder = MLP([action_dim, dim, dim], act=nn.SiLU)
        self.action_decoder = MLP([dim, dim, action_dim], act=nn.SiLU)
        self.state_encoder = MLP([state_dim, dim, dim], act=nn.SiLU) if state_dim else None
        self.token_type = nn.Embedding(5, dim)
        self.time_mlp = MLP([dim, dim, dim], act=nn.SiLU)
        self.blocks = nn.ModuleList(
            AdaLNBlock(dim, num_heads, mlp_dim=mlp_dim, dropout=dropout, act=nn.SiLU) for _ in range(depth)
        )
        self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
        self.final_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 2 * dim))
        init_weights(self.video_in)
        init_weights(self.blocks)
        for module in [*(b.modulation[-1] for b in self.blocks), self.final_modulation[-1]]:
            nn.init.zeros_(module.weight)
            nn.init.zeros_(module.bias)

    # Actions and latents ----------------------------------------------------------------------------------------

    def normalize_actions(self, actions: Tensor) -> Tensor:
        """Physical controls to training coordinates (z-score when statistics exist)."""
        if self.action_mean is not None:
            return (actions - self.action_mean) / self.action_std
        return actions / self.action_scale

    def denormalize_actions(self, actions: Tensor, *, clamp: bool = False) -> Tensor:
        """Training coordinates to physical controls; bounds apply after conversion."""
        raw = actions * self.action_scale if self.action_mean is None else actions * self.action_std + self.action_mean
        return raw.maximum(-self.action_scale).minimum(self.action_scale) if clamp else raw

    def encode(self, pixels: Tensor) -> Tensor:
        """Video ``(B, T, 3, H, W)`` in ``[0, 1]`` to latents ``(B, T', C, h, w)`` with the autoencoder."""
        if self.autoencoder is None:
            raise ValueError("encode needs an autoencoder; pass precomputed latents instead")
        return self.autoencoder.encode(pixels)

    def decode(self, z: Tensor) -> Tensor | None:
        return None if self.autoencoder is None else self.autoencoder.decode(z)

    @property
    def raw_frames_per_chunk(self) -> int:
        """Video frames each chunk covers before the autoencoder's temporal compression."""
        return self.chunk_frames * getattr(self.autoencoder, "temporal_ratio", 1)

    # Sequence --------------------------------------------------------------------------------------------------

    def _video_tokens(self, latents: Tensor, first: int, kind: int) -> Tensor:
        """Tokens of ``(B, T, C, h, w)`` latent frames at time indices ``first, first + 1, ...``."""
        B, T = latents.shape[:2]
        x = F.pixel_unshuffle(latents.flatten(0, 1), self.patch_size).flatten(2).transpose(1, 2)
        x = self.video_in(x.unflatten(0, (B, T)).flatten(1, 2))
        axes = (torch.arange(first, first + T), torch.arange(self.grid[0]), torch.arange(self.grid[1]))
        coords = torch.stack(torch.meshgrid(*axes, indexing="ij"), dim=-1).flatten(0, -2)
        return x + _sincos_3d(self.dim, coords).to(x) + self.token_type.weight[kind]

    def _video_output(self, tokens: Tensor) -> Tensor:
        """Tokens ``(B, T * P, D)`` back to latents ``(B, T, C, h, w)``."""
        B = tokens.size(0)
        x = self.video_out(tokens).unflatten(1, (-1, self.tokens_per_frame))
        x = x.flatten(0, 1).transpose(1, 2).unflatten(-1, self.grid)
        return F.pixel_shuffle(x, self.patch_size).unflatten(0, (B, -1))

    def _chunk_tokens(self, video: Tensor, actions: Tensor, state: Tensor | None, chunk: int) -> Tensor:
        index = torch.arange(self.chunk_size) + (chunk - 1) * self.chunk_size
        parts = [
            self._video_tokens(video, 1 + (chunk - 1) * self.chunk_frames, _VIDEO),
            self.action_encoder(actions) + sincos_1d(self.dim, index).to(actions) + self.token_type.weight[_ACTION],
        ]
        if self.state_encoder is not None:
            position = sincos_1d(self.dim, torch.tensor([float(chunk)])).to(actions)
            parts.append(self.state_encoder(state[:, None]) + position + self.token_type.weight[_STATE])
        return torch.cat(parts, dim=1)

    @property
    def _chunk_length(self) -> int:
        return self.chunk_frames * self.tokens_per_frame + self.chunk_size + int(self.state_encoder is not None)

    def _prefix_tokens(self, anchor: Tensor, goal: Tensor | None) -> Tensor:
        if self.goal_conditioned != (goal is not None):
            raise ValueError("Pass a goal latent exactly when the model is goal-conditioned")
        tokens = [self._video_tokens(anchor[:, None], 0, _ANCHOR)]
        if goal is not None:
            tokens.append(self._video_tokens(goal[:, None], 0, _GOAL))
        return torch.cat(tokens, dim=1)

    def _chunks(self, video: Tensor, actions: Tensor, states: Tensor | None, first: int) -> list[Tensor]:
        """Tokens of consecutive chunks ``first, first + 1, ...``; ``states`` is indexed by chunk number."""
        K, H = self.chunk_frames, self.chunk_size
        return [
            self._chunk_tokens(
                video[:, i * K : (i + 1) * K],
                actions[:, i * H : (i + 1) * H],
                None if self.state_encoder is None else states[:, first + i - 1],
                first + i,
            )
            for i in range(video.size(1) // K)
        ]

    def attention_mask(self, clean: int, noisy: int, start: int, device=None):
        """Mask of ``prefix | clean chunks 1..clean | noisy chunks start..``, cached per layout.

        Noisy chunk ``k`` attends to the prefix, clean chunks before ``k`` and itself; clean chunk ``k`` to the prefix
        and clean chunks up to ``k``. A boolean ``(N, N)`` tensor, or a FlexAttention ``BlockMask`` with
        ``attention="flex"``.
        """
        key = (clean, noisy, start, str(device))
        if key not in self._masks:
            prefix, L = self.tokens_per_frame * (1 + int(self.goal_conditioned)), self._chunk_length
            chunk = [0] * prefix + [k for k in range(1, clean + 1) for _ in range(L)]
            chunk += [k for k in range(start, start + noisy) for _ in range(L)]
            chunk = torch.tensor(chunk, device=device)
            is_noisy = torch.arange(len(chunk), device=device) >= prefix + clean * L

            def allowed(q, kv):
                clean_key = ~is_noisy[kv] & (chunk[kv] <= chunk[q] - is_noisy[q].long())
                return clean_key | (is_noisy[kv] & is_noisy[q] & (chunk[kv] == chunk[q]))

            if self.attention == "flex":
                from torch.nn.attention.flex_attention import create_block_mask

                n = len(chunk)
                mask = create_block_mask(lambda b, h, q, kv: allowed(q, kv), None, None, n, n, device=device)
            else:
                index = torch.arange(len(chunk), device=device)
                mask = allowed(index[:, None], index[None])
            self._masks[key] = mask
        return self._masks[key]

    def _condition(self, time: Tensor, like: Tensor) -> Tensor:
        return self.time_mlp(time_embedding(time, self.dim).to(like))

    def _noisy_time(self, t_video: Tensor, t_action: Tensor) -> Tensor:
        """Per-token times ``(B, n * L)`` of noisy chunks: video tokens at ``t_video``, the rest at ``t_action``."""
        video = self.chunk_frames * self.tokens_per_frame
        return torch.cat(
            (t_video[..., None].expand(-1, -1, video), t_action[..., None].expand(-1, -1, self._chunk_length - video)),
            dim=-1,
        ).flatten(1)

    def _output(self, x: Tensor, c: Tensor) -> tuple[Tensor, Tensor]:
        """Velocities from the final tokens ``(B, n * L, D)`` of ``n`` noisy chunks."""
        K, H, P = self.chunk_frames, self.chunk_size, self.tokens_per_frame
        shift, scale = self.final_modulation(c).chunk(2, dim=-1)
        x = (self.norm(x) * (1 + scale) + shift).unflatten(1, (-1, self._chunk_length))
        return self._video_output(x[:, :, : K * P].flatten(1, 2)), self.action_decoder(
            x[:, :, K * P : K * P + H]
        ).flatten(1, 2)

    def _check(self, anchor, video, actions, noisy_video, noisy_actions, t_video, t_action, start, states):
        K, H = self.chunk_frames, self.chunk_size
        j, n = video.size(1) // K, noisy_video.size(1) // K
        if video.size(1) != j * K or actions.size(1) != j * H or noisy_video.size(1) != n * K or n < 1:
            raise ValueError("Video and actions must hold whole chunks")
        if noisy_actions.size(1) != n * H or t_video.shape != (anchor.size(0), n) or t_action.shape != t_video.shape:
            raise ValueError("Noisy actions and times must match the noisy chunks")
        if start not in (1, j + 1):
            raise ValueError("Noisy chunks start at chunk 1 (teacher forcing) or right after the clean ones")
        if self.state_encoder is not None and (states is None or states.size(1) < max(j, start + n - 1)):
            raise ValueError("Pass one state per chunk")
        return j, n

    def joint_velocity(
        self,
        anchor: Tensor,
        video: Tensor,
        actions: Tensor,
        noisy_video: Tensor,
        noisy_actions: Tensor,
        t_video: Tensor,
        t_action: Tensor,
        *,
        start: int,
        states: Tensor | None = None,
        goal: Tensor | None = None,
    ) -> tuple[Tensor, Tensor]:
        """Video and action velocities of ``n`` noisy chunks numbered ``start, ..., start + n - 1``.

        The sequence is ``anchor (| goal) | clean chunks 1..j | noisy chunks``, with ``anchor`` ``(B, C, h, w)`` the
        latent frame before chunk 1, clean ``video`` ``(B, j * K, C, h, w)`` and normalized ``actions``
        ``(B, j * H, A)``. Noisy chunks are ``(B, n * K, C, h, w)`` and ``(B, n * H, A)`` with times ``(B, n)``.
        ``states`` ``(B, max(j, start + n - 1), S)`` holds ``q_k`` for every chunk ``k``; see ``attention_mask``.
        Training passes ``j = n - 1`` and ``start = 1``; sampling the next chunk passes ``n = 1`` and ``start = j + 1``.
        """
        j, n = self._check(anchor, video, actions, noisy_video, noisy_actions, t_video, t_action, start, states)
        prefix = self._prefix_tokens(anchor, goal)
        x = torch.cat(
            [
                prefix,
                *self._chunks(video, actions, states, 1),
                *self._chunks(noisy_video, noisy_actions, states, start),
            ],
            dim=1,
        )
        context = prefix.size(1) + j * self._chunk_length
        time = torch.cat((x.new_ones(x.size(0), context), self._noisy_time(t_video, t_action).to(x)), dim=1)
        c = self._condition(time, x)
        mask = self.attention_mask(j, n, start, x.device)
        for block in self.blocks:
            x = block(x, c, attn_mask=mask)
        return self._output(x[:, context:], c[:, context:])

    # Key-value cache -------------------------------------------------------------------------------------------

    @staticmethod
    def _block(block: AdaLNBlock, x: Tensor, c: Tensor, mask=None, cache: tuple[Tensor, Tensor] | None = None):
        """``AdaLNBlock.forward`` (in eval) that prepends cached keys and values and returns its own."""
        shift1, scale1, gate1, shift2, scale2, gate2 = block.modulation(c).chunk(6, dim=-1)
        attn, (B, N, _) = block.attn, x.shape
        q, k, v = (
            attn.qkv(block.norm1(x) * (1 + scale1) + shift1).view(B, N, 3, attn.num_heads, -1).permute(2, 0, 3, 1, 4)
        )
        keys, values = (k, v) if cache is None else (torch.cat((cache[0], k), 2), torch.cat((cache[1], v), 2))
        if mask is not None and not isinstance(mask, Tensor):
            out = flex_attention(q, keys, values, mask)
        else:
            out = F.scaled_dot_product_attention(q, keys, values, attn_mask=mask)
        x = x + gate1 * attn.proj(out.transpose(1, 2).reshape(B, N, -1))
        return x + gate2 * block.mlp(block.norm2(x) * (1 + scale2) + shift2), (k, v)

    def context_cache(
        self,
        anchor: Tensor,
        video: Tensor,
        actions: Tensor,
        *,
        states: Tensor | None = None,
        goal: Tensor | None = None,
    ) -> list[tuple[Tensor, Tensor]]:
        """Per-layer keys and values of ``anchor (| goal) | clean chunks``, computed once per chunk.

        Clean tokens never attend to noisy ones, so the context is the same at every denoising step of the next chunk.
        """
        prefix = self._prefix_tokens(anchor, goal)
        x = torch.cat([prefix, *self._chunks(video, actions, states, 1)], dim=1)
        c = self._condition(x.new_ones(x.shape[:2]), x)
        mask = self.attention_mask(video.size(1) // self.chunk_frames, 0, 1, x.device)
        cache = []
        for block in self.blocks:
            x, kv = self._block(block, x, c, mask)
            cache.append(kv)
        return cache

    def cached_velocity(
        self,
        cache: list[tuple[Tensor, Tensor]],
        noisy_video: Tensor,
        noisy_actions: Tensor,
        t_video: Tensor,
        t_action: Tensor,
        *,
        start: int,
        states: Tensor | None = None,
    ) -> tuple[Tensor, Tensor]:
        """``joint_velocity`` of the one chunk after the cached context; it attends to all of it."""
        x = torch.cat(self._chunks(noisy_video, noisy_actions, states, start), dim=1)
        c = self._condition(self._noisy_time(t_video, t_action).to(x), x)
        for block, kv in zip(self.blocks, cache):
            x = self._block(block, x, c, cache=kv)[0]
        return self._output(x, c)

    # Training --------------------------------------------------------------------------------------------------

    def forward(
        self,
        latents: Tensor,
        actions: Tensor,
        states: Tensor | None = None,
        *,
        goal: Tensor | None = None,
        action_valid: Tensor | None = None,
        generator: torch.Generator | None = None,
    ) -> dict[str, Tensor]:
        """Teacher-forced joint flow matching over ``num_chunks`` chunks.

        ``latents`` ``(B, 1 + M * K, C, h, w)``: an anchor frame then ``M`` chunks of ``K`` frames. ``actions``
        ``(B, M * H, A)`` in environment units, ``states`` ``(B, M, S)``, ``goal`` latent ``(B, C, h, w)``.
        ``action_valid`` ``(B, M * H)`` weights the action loss, for example to drop padded actions.
        """
        B, M, K, H = latents.size(0), self.num_chunks, self.chunk_frames, self.chunk_size
        if latents.size(1) != 1 + M * K or actions.shape != (B, M * H, self.action_dim):
            raise ValueError("Expected 1 + num_chunks * chunk_frames latents and num_chunks * chunk_actions actions")
        video, target = latents[:, 1:], self.normalize_actions(actions)
        schedule = (0.0, 1.0) if self.time_schedule == "logit_normal" else None
        t_action = sample_time(
            (B, M), device=latents.device, dtype=latents.dtype, generator=generator, logit_normal=schedule
        )
        t_video = (
            t_action
            if self.flash_alpha is None
            else sample_time(
                (B, M), device=latents.device, dtype=latents.dtype, generator=generator, alpha=self.flash_alpha
            )
        )
        video_noise = torch.randn(video.shape, device=video.device, dtype=video.dtype, generator=generator)
        action_noise = torch.randn(target.shape, device=target.device, dtype=target.dtype, generator=generator)
        noisy_video = interpolate(video_noise, video, t_video.repeat_interleave(K, 1))
        noisy_actions = interpolate(action_noise, target, t_action.repeat_interleave(H, 1))
        v_video, v_action = self.joint_velocity(
            latents[:, 0],
            video[:, : (M - 1) * K],
            target[:, : (M - 1) * H],
            noisy_video,
            noisy_actions,
            t_video,
            t_action,
            start=1,
            states=states,
            goal=goal,
        )
        video_loss = (v_video - velocity_target(video_noise, video)).square().mean()
        error = (v_action - velocity_target(action_noise, target)).square().mean(-1)
        if action_valid is None:
            action_loss = error.mean()
        else:
            if action_valid.shape != error.shape:
                raise ValueError("action_valid must have shape (B, num_chunks * chunk_actions)")
            action_loss = (error * action_valid).sum() / action_valid.sum().clamp_min(1)
        return {
            "loss": self.video_weight * video_loss + self.action_weight * action_loss,
            "video_loss": video_loss,
            "action_loss": action_loss,
        }

    # Inference -------------------------------------------------------------------------------------------------

    def _context(self, z: Tensor, past_actions: Tensor | None, states: Tensor | None):
        """Keep the latest ``num_chunks - 1`` whole chunks; the frame before them becomes the anchor."""
        K, H = self.chunk_frames, self.chunk_size
        j = (z.size(1) - 1) // K
        if z.size(1) != 1 + j * K:
            raise ValueError("Context latents must be an anchor frame then whole chunks")
        past_actions = z.new_zeros(z.size(0), 0, self.action_dim) if past_actions is None else past_actions
        if past_actions.shape != (z.size(0), j * self.chunk_size, self.action_dim):
            raise ValueError("past_actions must hold chunk_actions actions per context chunk")
        if self.state_encoder is not None and (states is None or states.size(1) != j + 1):
            raise ValueError("Pass one state per context chunk plus the current state")
        drop = max(0, j - (self.num_chunks - 1))
        z, past_actions = z[:, drop * K :], past_actions[:, drop * H :]
        states = None if states is None else states[:, drop:]
        return z[:, 0], z[:, 1:], self.normalize_actions(past_actions), states, j - drop

    def _sample(self, z, goal, past_actions, states, steps, generator, noise, video_noise, actions=None, video=None):
        """Integrate the flow of the next chunk's video and actions, keeping whichever is given clean (time 1)."""
        anchor, context, past, states, j = self._context(z, past_actions, states)
        B, K, H = z.size(0), self.chunk_frames, self.chunk_size
        steps = self.flow_steps if steps is None else steps
        shape_v, shape_a = (B, K, self.latent_channels, *self.latent_size), (B, H, self.action_dim)
        if video is None and video_noise is None:
            video_noise = torch.randn(shape_v, device=z.device, dtype=z.dtype, generator=generator)
        if actions is None and noise is None:
            noise = torch.randn(shape_a, device=z.device, dtype=z.dtype, generator=generator)
        if (video is None and video_noise.shape != shape_v) or (actions is None and noise.shape != shape_a):
            raise ValueError("Noise must match one chunk")
        if (video is not None and video.shape != shape_v) or (actions is not None and actions.shape != shape_a):
            raise ValueError("Clean video and actions must be one chunk")
        cache = self.context_cache(anchor, context, past, states=states, goal=goal)
        split = 0 if video is not None else video_noise[0].numel()

        def unpack(x):
            v = video if video is not None else x[:, :split].view(shape_v)
            a = actions if actions is not None else x[:, split:].view(shape_a)
            return v, a

        def velocity(x, time):
            v, a = unpack(x)
            one = time.new_ones(B, 1)
            t_video, t_action = (
                (one if video is not None else time[:, None]),
                (one if actions is not None else time[:, None]),
            )
            dv, da = self.cached_velocity(cache, v, a, t_video, t_action, start=j + 1, states=states)
            return torch.cat([d.flatten(1) for d, given in ((dv, video), (da, actions)) if given is None], dim=1)

        x = torch.cat([n.flatten(1) for n, given in ((video_noise, video), (noise, actions)) if given is None], dim=1)
        return unpack(euler_sample(velocity, x, steps))

    def imagine(
        self,
        z: Tensor,
        goal: Tensor | None = None,
        *,
        past_actions: Tensor | None = None,
        states: Tensor | None = None,
        steps: int | None = None,
        generator: torch.Generator | None = None,
        noise: Tensor | None = None,
        video_noise: Tensor | None = None,
        clamp: bool = True,
    ) -> tuple[Tensor, Tensor]:
        """Jointly sample the next chunk: latents ``(B, K, C, h, w)`` and physical actions ``(B, H, A)``.

        ``z`` ``(B, 1 + j * K, C, h, w)`` is an anchor frame then ``j`` past chunks, ``past_actions``
        ``(B, j * H, A)`` the actions executed over them and ``states`` ``(B, j + 1, S)`` the state at the start of
        each past chunk and now. ``noise`` and ``video_noise`` fix the starting Gaussian draws.
        """
        future, actions = self._sample(z, goal, past_actions, states, steps, generator, noise, video_noise)
        return future, self.denormalize_actions(actions, clamp=clamp)

    def inverse_dynamics(
        self,
        z: Tensor,
        future: Tensor,
        goal: Tensor | None = None,
        *,
        past_actions: Tensor | None = None,
        states: Tensor | None = None,
        steps: int | None = None,
        generator: torch.Generator | None = None,
        noise: Tensor | None = None,
        clamp: bool = True,
    ) -> Tensor:
        """Actions ``(B, H, A)`` denoised with the next chunk's video given clean, ``future`` ``(B, K, C, h, w)``.

        A diagnostic: with the true future, its error against the recorded actions bounds what the joint policy can
        reach when its imagined video is perfect.
        """
        normalized = self._sample(z, goal, past_actions, states, steps, generator, noise, None, video=future)[1]
        return self.denormalize_actions(normalized, clamp=clamp)

    def sample_actions(
        self,
        z: Tensor,
        goal: Tensor | None = None,
        *,
        history_pad: Tensor | None = None,
        remaining: Tensor | None = None,
        **kwargs,
    ) -> Tensor:
        """The policy: the action half of ``imagine``. Takes the same arguments."""
        if history_pad is not None or remaining is not None:
            raise ValueError("DreamZero does not use history_pad or remaining")
        return self.imagine(z, goal, **kwargs)[1]

    def predict_future(
        self,
        z: Tensor,
        actions: Tensor,
        goal: Tensor | None = None,
        *,
        past_actions: Tensor | None = None,
        states: Tensor | None = None,
        steps: int | None = None,
        generator: torch.Generator | None = None,
        video_noise: Tensor | None = None,
        history_pad: Tensor | None = None,
    ) -> Tensor:
        """Forward dynamics: denoise the next chunk's latents given its clean physical ``actions`` ``(B, H, A)``.

        Differentiable in ``actions``, for gradient-based refinement. A goal-conditioned model needs its ``goal``.
        """
        if history_pad is not None:
            raise ValueError("DreamZero does not use history_pad")
        if actions.shape != (z.size(0), self.chunk_size, self.action_dim):
            raise ValueError("predict_future needs one action chunk")
        normalized = self.normalize_actions(actions)
        return self._sample(z, goal, past_actions, states, steps, generator, None, video_noise, normalized)[0]

    def rollout(self, z: Tensor, actions: Tensor, *, goal: Tensor | None = None, **kwargs) -> Tensor:
        """Unroll ``(B, T, A)`` actions, ``T`` a multiple of ``chunk_actions``, chunk by chunk from context ``z``.

        Returns ``z`` followed by the predicted latents of every chunk, so ``cost`` scores the last predicted frame.
        """
        H = self.chunk_size
        if actions.size(1) % H:
            raise ValueError("rollout needs whole action chunks")
        past = kwargs.pop("past_actions", None)
        past = z.new_zeros(z.size(0), 0, self.action_dim) if past is None else past
        for c in range(actions.size(1) // H):
            chunk = actions[:, c * H : (c + 1) * H]
            future = self.predict_future(z, chunk, goal=goal, past_actions=past, **kwargs)
            z, past = torch.cat((z, future), dim=1), torch.cat((past, chunk), dim=1)
        return z

method normalize_actions ​

torch_world.models.DreamZero.normalize_actions GitHub

python
normalize_actions(actions: Tensor) -> Tensor

Physical controls to training coordinates (z-score when statistics exist).

Source code in torch_world/models/wam/_dreamzero.py
python
def normalize_actions(self, actions: Tensor) -> Tensor:
    """Physical controls to training coordinates (z-score when statistics exist)."""
    if self.action_mean is not None:
        return (actions - self.action_mean) / self.action_std
    return actions / self.action_scale

method denormalize_actions ​

torch_world.models.DreamZero.denormalize_actions GitHub

python
denormalize_actions(actions: Tensor, *, clamp: bool = False) -> Tensor

Training coordinates to physical controls; bounds apply after conversion.

Source code in torch_world/models/wam/_dreamzero.py
python
def denormalize_actions(self, actions: Tensor, *, clamp: bool = False) -> Tensor:
    """Training coordinates to physical controls; bounds apply after conversion."""
    raw = actions * self.action_scale if self.action_mean is None else actions * self.action_std + self.action_mean
    return raw.maximum(-self.action_scale).minimum(self.action_scale) if clamp else raw

method encode ​

torch_world.models.DreamZero.encode GitHub

python
encode(pixels: Tensor) -> Tensor

Video (B, T, 3, H, W) in [0, 1] to latents (B, T', C, h, w) with the autoencoder.

Source code in torch_world/models/wam/_dreamzero.py
python
def encode(self, pixels: Tensor) -> Tensor:
    """Video ``(B, T, 3, H, W)`` in ``[0, 1]`` to latents ``(B, T', C, h, w)`` with the autoencoder."""
    if self.autoencoder is None:
        raise ValueError("encode needs an autoencoder; pass precomputed latents instead")
    return self.autoencoder.encode(pixels)

property raw_frames_per_chunk ​

torch_world.models.DreamZero.raw_frames_per_chunk GitHub

python
raw_frames_per_chunk: int

Video frames each chunk covers before the autoencoder's temporal compression.

Source code in torch_world/models/wam/_dreamzero.py
python
def raw_frames_per_chunk(self) -> int:
    """Video frames each chunk covers before the autoencoder's temporal compression."""
    return self.chunk_frames * getattr(self.autoencoder, "temporal_ratio", 1)

method attention_mask ​

torch_world.models.DreamZero.attention_mask GitHub

python
attention_mask(clean: int, noisy: int, start: int, device=None)

Mask of prefix | clean chunks 1..clean | noisy chunks start.., cached per layout.

Noisy chunk k attends to the prefix, clean chunks before k and itself; clean chunk k to the prefix and clean chunks up to k. A boolean (N, N) tensor, or a FlexAttention BlockMask with attention="flex".

Source code in torch_world/models/wam/_dreamzero.py
python
def attention_mask(self, clean: int, noisy: int, start: int, device=None):
    """Mask of ``prefix | clean chunks 1..clean | noisy chunks start..``, cached per layout.

    Noisy chunk ``k`` attends to the prefix, clean chunks before ``k`` and itself; clean chunk ``k`` to the prefix
    and clean chunks up to ``k``. A boolean ``(N, N)`` tensor, or a FlexAttention ``BlockMask`` with
    ``attention="flex"``.
    """
    key = (clean, noisy, start, str(device))
    if key not in self._masks:
        prefix, L = self.tokens_per_frame * (1 + int(self.goal_conditioned)), self._chunk_length
        chunk = [0] * prefix + [k for k in range(1, clean + 1) for _ in range(L)]
        chunk += [k for k in range(start, start + noisy) for _ in range(L)]
        chunk = torch.tensor(chunk, device=device)
        is_noisy = torch.arange(len(chunk), device=device) >= prefix + clean * L

        def allowed(q, kv):
            clean_key = ~is_noisy[kv] & (chunk[kv] <= chunk[q] - is_noisy[q].long())
            return clean_key | (is_noisy[kv] & is_noisy[q] & (chunk[kv] == chunk[q]))

        if self.attention == "flex":
            from torch.nn.attention.flex_attention import create_block_mask

            n = len(chunk)
            mask = create_block_mask(lambda b, h, q, kv: allowed(q, kv), None, None, n, n, device=device)
        else:
            index = torch.arange(len(chunk), device=device)
            mask = allowed(index[:, None], index[None])
        self._masks[key] = mask
    return self._masks[key]

method joint_velocity ​

torch_world.models.DreamZero.joint_velocity GitHub

python
joint_velocity(
    anchor: Tensor,
    video: Tensor,
    actions: Tensor,
    noisy_video: Tensor,
    noisy_actions: Tensor,
    t_video: Tensor,
    t_action: Tensor,
    *,
    start: int,
    states: Tensor | None = None,
    goal: Tensor | None = None,
) -> tuple[Tensor, Tensor]

Video and action velocities of n noisy chunks numbered start, ..., start + n - 1.

The sequence is anchor (| goal) | clean chunks 1..j | noisy chunks, with anchor (B, C, h, w) the latent frame before chunk 1, clean video (B, j * K, C, h, w) and normalized actions(B, j * H, A). Noisy chunks are (B, n * K, C, h, w) and (B, n * H, A) with times (B, n). states (B, max(j, start + n - 1), S) holds q_k for every chunk k; see attention_mask. Training passes j = n - 1 and start = 1; sampling the next chunk passes n = 1 and start = j + 1.

Source code in torch_world/models/wam/_dreamzero.py
python
def joint_velocity(
    self,
    anchor: Tensor,
    video: Tensor,
    actions: Tensor,
    noisy_video: Tensor,
    noisy_actions: Tensor,
    t_video: Tensor,
    t_action: Tensor,
    *,
    start: int,
    states: Tensor | None = None,
    goal: Tensor | None = None,
) -> tuple[Tensor, Tensor]:
    """Video and action velocities of ``n`` noisy chunks numbered ``start, ..., start + n - 1``.

    The sequence is ``anchor (| goal) | clean chunks 1..j | noisy chunks``, with ``anchor`` ``(B, C, h, w)`` the
    latent frame before chunk 1, clean ``video`` ``(B, j * K, C, h, w)`` and normalized ``actions``
    ``(B, j * H, A)``. Noisy chunks are ``(B, n * K, C, h, w)`` and ``(B, n * H, A)`` with times ``(B, n)``.
    ``states`` ``(B, max(j, start + n - 1), S)`` holds ``q_k`` for every chunk ``k``; see ``attention_mask``.
    Training passes ``j = n - 1`` and ``start = 1``; sampling the next chunk passes ``n = 1`` and ``start = j + 1``.
    """
    j, n = self._check(anchor, video, actions, noisy_video, noisy_actions, t_video, t_action, start, states)
    prefix = self._prefix_tokens(anchor, goal)
    x = torch.cat(
        [
            prefix,
            *self._chunks(video, actions, states, 1),
            *self._chunks(noisy_video, noisy_actions, states, start),
        ],
        dim=1,
    )
    context = prefix.size(1) + j * self._chunk_length
    time = torch.cat((x.new_ones(x.size(0), context), self._noisy_time(t_video, t_action).to(x)), dim=1)
    c = self._condition(time, x)
    mask = self.attention_mask(j, n, start, x.device)
    for block in self.blocks:
        x = block(x, c, attn_mask=mask)
    return self._output(x[:, context:], c[:, context:])

method context_cache ​

torch_world.models.DreamZero.context_cache GitHub

python
context_cache(
    anchor: Tensor,
    video: Tensor,
    actions: Tensor,
    *,
    states: Tensor | None = None,
    goal: Tensor | None = None,
) -> list[tuple[Tensor, Tensor]]

Per-layer keys and values of anchor (| goal) | clean chunks, computed once per chunk.

Clean tokens never attend to noisy ones, so the context is the same at every denoising step of the next chunk.

Source code in torch_world/models/wam/_dreamzero.py
python
def context_cache(
    self,
    anchor: Tensor,
    video: Tensor,
    actions: Tensor,
    *,
    states: Tensor | None = None,
    goal: Tensor | None = None,
) -> list[tuple[Tensor, Tensor]]:
    """Per-layer keys and values of ``anchor (| goal) | clean chunks``, computed once per chunk.

    Clean tokens never attend to noisy ones, so the context is the same at every denoising step of the next chunk.
    """
    prefix = self._prefix_tokens(anchor, goal)
    x = torch.cat([prefix, *self._chunks(video, actions, states, 1)], dim=1)
    c = self._condition(x.new_ones(x.shape[:2]), x)
    mask = self.attention_mask(video.size(1) // self.chunk_frames, 0, 1, x.device)
    cache = []
    for block in self.blocks:
        x, kv = self._block(block, x, c, mask)
        cache.append(kv)
    return cache

method cached_velocity ​

torch_world.models.DreamZero.cached_velocity GitHub

python
cached_velocity(
    cache: list[tuple[Tensor, Tensor]],
    noisy_video: Tensor,
    noisy_actions: Tensor,
    t_video: Tensor,
    t_action: Tensor,
    *,
    start: int,
    states: Tensor | None = None,
) -> tuple[Tensor, Tensor]

joint_velocity of the one chunk after the cached context; it attends to all of it.

Source code in torch_world/models/wam/_dreamzero.py
python
def cached_velocity(
    self,
    cache: list[tuple[Tensor, Tensor]],
    noisy_video: Tensor,
    noisy_actions: Tensor,
    t_video: Tensor,
    t_action: Tensor,
    *,
    start: int,
    states: Tensor | None = None,
) -> tuple[Tensor, Tensor]:
    """``joint_velocity`` of the one chunk after the cached context; it attends to all of it."""
    x = torch.cat(self._chunks(noisy_video, noisy_actions, states, start), dim=1)
    c = self._condition(self._noisy_time(t_video, t_action).to(x), x)
    for block, kv in zip(self.blocks, cache):
        x = self._block(block, x, c, cache=kv)[0]
    return self._output(x, c)

method forward ​

torch_world.models.DreamZero.forward GitHub

python
forward(
    latents: Tensor,
    actions: Tensor,
    states: Tensor | None = None,
    *,
    goal: Tensor | None = None,
    action_valid: Tensor | None = None,
    generator: torch.Generator | None = None,
) -> dict[str, Tensor]

Teacher-forced joint flow matching over num_chunks chunks.

latents (B, 1 + M * K, C, h, w): an anchor frame then M chunks of K frames. actions(B, M * H, A) in environment units, states (B, M, S), goal latent (B, C, h, w). action_valid (B, M * H) weights the action loss, for example to drop padded actions.

Source code in torch_world/models/wam/_dreamzero.py
python
def forward(
    self,
    latents: Tensor,
    actions: Tensor,
    states: Tensor | None = None,
    *,
    goal: Tensor | None = None,
    action_valid: Tensor | None = None,
    generator: torch.Generator | None = None,
) -> dict[str, Tensor]:
    """Teacher-forced joint flow matching over ``num_chunks`` chunks.

    ``latents`` ``(B, 1 + M * K, C, h, w)``: an anchor frame then ``M`` chunks of ``K`` frames. ``actions``
    ``(B, M * H, A)`` in environment units, ``states`` ``(B, M, S)``, ``goal`` latent ``(B, C, h, w)``.
    ``action_valid`` ``(B, M * H)`` weights the action loss, for example to drop padded actions.
    """
    B, M, K, H = latents.size(0), self.num_chunks, self.chunk_frames, self.chunk_size
    if latents.size(1) != 1 + M * K or actions.shape != (B, M * H, self.action_dim):
        raise ValueError("Expected 1 + num_chunks * chunk_frames latents and num_chunks * chunk_actions actions")
    video, target = latents[:, 1:], self.normalize_actions(actions)
    schedule = (0.0, 1.0) if self.time_schedule == "logit_normal" else None
    t_action = sample_time(
        (B, M), device=latents.device, dtype=latents.dtype, generator=generator, logit_normal=schedule
    )
    t_video = (
        t_action
        if self.flash_alpha is None
        else sample_time(
            (B, M), device=latents.device, dtype=latents.dtype, generator=generator, alpha=self.flash_alpha
        )
    )
    video_noise = torch.randn(video.shape, device=video.device, dtype=video.dtype, generator=generator)
    action_noise = torch.randn(target.shape, device=target.device, dtype=target.dtype, generator=generator)
    noisy_video = interpolate(video_noise, video, t_video.repeat_interleave(K, 1))
    noisy_actions = interpolate(action_noise, target, t_action.repeat_interleave(H, 1))
    v_video, v_action = self.joint_velocity(
        latents[:, 0],
        video[:, : (M - 1) * K],
        target[:, : (M - 1) * H],
        noisy_video,
        noisy_actions,
        t_video,
        t_action,
        start=1,
        states=states,
        goal=goal,
    )
    video_loss = (v_video - velocity_target(video_noise, video)).square().mean()
    error = (v_action - velocity_target(action_noise, target)).square().mean(-1)
    if action_valid is None:
        action_loss = error.mean()
    else:
        if action_valid.shape != error.shape:
            raise ValueError("action_valid must have shape (B, num_chunks * chunk_actions)")
        action_loss = (error * action_valid).sum() / action_valid.sum().clamp_min(1)
    return {
        "loss": self.video_weight * video_loss + self.action_weight * action_loss,
        "video_loss": video_loss,
        "action_loss": action_loss,
    }

method imagine ​

torch_world.models.DreamZero.imagine GitHub

python
imagine(
    z: Tensor,
    goal: Tensor | None = None,
    *,
    past_actions: Tensor | None = None,
    states: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
    noise: Tensor | None = None,
    video_noise: Tensor | None = None,
    clamp: bool = True,
) -> tuple[Tensor, Tensor]

Jointly sample the next chunk: latents (B, K, C, h, w) and physical actions (B, H, A).

z (B, 1 + j * K, C, h, w) is an anchor frame then j past chunks, past_actions(B, j * H, A) the actions executed over them and states (B, j + 1, S) the state at the start of each past chunk and now. noise and video_noise fix the starting Gaussian draws.

Source code in torch_world/models/wam/_dreamzero.py
python
def imagine(
    self,
    z: Tensor,
    goal: Tensor | None = None,
    *,
    past_actions: Tensor | None = None,
    states: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
    noise: Tensor | None = None,
    video_noise: Tensor | None = None,
    clamp: bool = True,
) -> tuple[Tensor, Tensor]:
    """Jointly sample the next chunk: latents ``(B, K, C, h, w)`` and physical actions ``(B, H, A)``.

    ``z`` ``(B, 1 + j * K, C, h, w)`` is an anchor frame then ``j`` past chunks, ``past_actions``
    ``(B, j * H, A)`` the actions executed over them and ``states`` ``(B, j + 1, S)`` the state at the start of
    each past chunk and now. ``noise`` and ``video_noise`` fix the starting Gaussian draws.
    """
    future, actions = self._sample(z, goal, past_actions, states, steps, generator, noise, video_noise)
    return future, self.denormalize_actions(actions, clamp=clamp)

method inverse_dynamics ​

torch_world.models.DreamZero.inverse_dynamics GitHub

python
inverse_dynamics(
    z: Tensor,
    future: Tensor,
    goal: Tensor | None = None,
    *,
    past_actions: Tensor | None = None,
    states: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
    noise: Tensor | None = None,
    clamp: bool = True,
) -> Tensor

Actions (B, H, A) denoised with the next chunk's video given clean, future (B, K, C, h, w).

A diagnostic: with the true future, its error against the recorded actions bounds what the joint policy can reach when its imagined video is perfect.

Source code in torch_world/models/wam/_dreamzero.py
python
def inverse_dynamics(
    self,
    z: Tensor,
    future: Tensor,
    goal: Tensor | None = None,
    *,
    past_actions: Tensor | None = None,
    states: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
    noise: Tensor | None = None,
    clamp: bool = True,
) -> Tensor:
    """Actions ``(B, H, A)`` denoised with the next chunk's video given clean, ``future`` ``(B, K, C, h, w)``.

    A diagnostic: with the true future, its error against the recorded actions bounds what the joint policy can
    reach when its imagined video is perfect.
    """
    normalized = self._sample(z, goal, past_actions, states, steps, generator, noise, None, video=future)[1]
    return self.denormalize_actions(normalized, clamp=clamp)

method sample_actions ​

torch_world.models.DreamZero.sample_actions GitHub

python
sample_actions(
    z: Tensor,
    goal: Tensor | None = None,
    *,
    history_pad: Tensor | None = None,
    remaining: Tensor | None = None,
    **kwargs,
) -> Tensor

The policy: the action half of imagine. Takes the same arguments.

Source code in torch_world/models/wam/_dreamzero.py
python
def sample_actions(
    self,
    z: Tensor,
    goal: Tensor | None = None,
    *,
    history_pad: Tensor | None = None,
    remaining: Tensor | None = None,
    **kwargs,
) -> Tensor:
    """The policy: the action half of ``imagine``. Takes the same arguments."""
    if history_pad is not None or remaining is not None:
        raise ValueError("DreamZero does not use history_pad or remaining")
    return self.imagine(z, goal, **kwargs)[1]

method predict_future ​

torch_world.models.DreamZero.predict_future GitHub

python
predict_future(
    z: Tensor,
    actions: Tensor,
    goal: Tensor | None = None,
    *,
    past_actions: Tensor | None = None,
    states: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
    video_noise: Tensor | None = None,
    history_pad: Tensor | None = None,
) -> Tensor

Forward dynamics: denoise the next chunk's latents given its clean physical actions (B, H, A).

Differentiable in actions, for gradient-based refinement. A goal-conditioned model needs its goal.

Source code in torch_world/models/wam/_dreamzero.py
python
def predict_future(
    self,
    z: Tensor,
    actions: Tensor,
    goal: Tensor | None = None,
    *,
    past_actions: Tensor | None = None,
    states: Tensor | None = None,
    steps: int | None = None,
    generator: torch.Generator | None = None,
    video_noise: Tensor | None = None,
    history_pad: Tensor | None = None,
) -> Tensor:
    """Forward dynamics: denoise the next chunk's latents given its clean physical ``actions`` ``(B, H, A)``.

    Differentiable in ``actions``, for gradient-based refinement. A goal-conditioned model needs its ``goal``.
    """
    if history_pad is not None:
        raise ValueError("DreamZero does not use history_pad")
    if actions.shape != (z.size(0), self.chunk_size, self.action_dim):
        raise ValueError("predict_future needs one action chunk")
    normalized = self.normalize_actions(actions)
    return self._sample(z, goal, past_actions, states, steps, generator, None, video_noise, normalized)[0]

method rollout ​

torch_world.models.DreamZero.rollout GitHub

python
rollout(
    z: Tensor, actions: Tensor, *, goal: Tensor | None = None, **kwargs
) -> Tensor

Unroll (B, T, A) actions, T a multiple of chunk_actions, chunk by chunk from context z.

Returns z followed by the predicted latents of every chunk, so cost scores the last predicted frame.

Source code in torch_world/models/wam/_dreamzero.py
python
def rollout(self, z: Tensor, actions: Tensor, *, goal: Tensor | None = None, **kwargs) -> Tensor:
    """Unroll ``(B, T, A)`` actions, ``T`` a multiple of ``chunk_actions``, chunk by chunk from context ``z``.

    Returns ``z`` followed by the predicted latents of every chunk, so ``cost`` scores the last predicted frame.
    """
    H = self.chunk_size
    if actions.size(1) % H:
        raise ValueError("rollout needs whole action chunks")
    past = kwargs.pop("past_actions", None)
    past = z.new_zeros(z.size(0), 0, self.action_dim) if past is None else past
    for c in range(actions.size(1) // H):
        chunk = actions[:, c * H : (c + 1) * H]
        future = self.predict_future(z, chunk, goal=goal, past_actions=past, **kwargs)
        z, past = torch.cat((z, future), dim=1), torch.cat((past, chunk), dim=1)
    return z

class DreamerV3 ​

torch_world.models.DreamerV3 GitHub

python
DreamerV3(
    action_dim: int,
    in_channels: int = 3,
    img_size: int = 64,
    encoder: nn.Module | None = None,
    decoder: nn.Module | None = None,
    embed_dim: int | None = None,
    cnn_depth: int = 16,
    deter_dim: int = 256,
    stoch: int = 32,
    classes: int = 16,
    hidden_dim: int = 256,
    mlp_layers: int = 2,
    num_bins: int = 255,
    unimix: float = 0.01,
    free_nats: float = 1.0,
    dyn_coef: float = 0.5,
    rep_coef: float = 0.1,
    horizon: int = 15,
    discount: float = 1 - 1 / 333,
    lam: float = 0.95,
    entropy_coef: float = 0.0003,
    slow_reg: float = 1.0,
    retnorm_decay: float = 0.99,
    min_std: float = 0.1,
    max_std: float = 1.0,
    actor_grad: str = "dynamics",
    sample: bool = False,
    cost_on: str = "full",
)

DreamerV3: a recurrent state-space model (RSSM) learned by reconstruction, and an actor-critic learned in its imagination.

The model state s_t = (h_t, z_t) joins a deterministic GRU state h_t = f(h_{t-1}, z_{t-1}, a_{t-1}) and a stochastic state of stoch categoricals with classes classes each, drawn with straight-through gradients from the posterior q(z_t | h_t, x_t) when the image is seen and from the prior p(z_t | h_t) when it is imagined; both mix 1% uniform into their probabilities. From s_t a CNN decoder reconstructs the image, a reward head regresses the reward with two-hot symlog bins and a continue head predicts whether the episode goes on. KL balancing with free bits trains the prior toward the posterior (dyn) and, more weakly, the reverse (rep):

L = E[ ||x̂_t - x_t||² - ln p(r_t | s_t) - ln p(c_t | s_t) + β_dyn max(1, KL[sg(q) || p])
       + β_rep max(1, KL[q || sg(p)]) ]

With rewards, an actor and a critic learn on trajectories imagined from every posterior state for horizon steps. The critic regresses two-hot λ-returns R_t = r_{t+1} + γ c_{t+1} ((1 - λ) v_{t+1} + λ R_{t+1}) and the outputs of its own EMA; the actor maximizes (R_t - v_t) / max(1, S), with S the EMA of the 5th to 95th percentile range of the returns, plus η times its entropy. Without rewards only the world model learns.

The model state, flattened to (..., deter_dim + stoch * classes), is the latent of encode, predict and rollout, so CEM can plan on it toward an encoded goal image; act gives the actor's actions. forward sums the world-model, critic and actor losses: their gradients reach disjoint parameters, as with the reference's three optimizers. Train with param_groups, clip_grad_norm and update_target.

Hafner et al., "Mastering Diverse Domains through World Models", 2023. Paper: https://arxiv.org/abs/2301.04104 Code: https://github.com/danijar/dreamerv3

Parameters

NameTypeDescriptionDefault
encoder`nn.ModuleNone`module mapping images (N, C, H, W) to embeddings (N, embed_dim); conv_encoder by default.
decoder`nn.ModuleNone`module mapping model states (N, feat_dim) to images; conv_decoder by default.
cnn_depthintchannels of the first convolution of the default encoder and decoder (the paper's multiplier).16
free_natsfloatfree bits of both KL terms, summed over the categoricals.1.0
unimixfloatshare of the uniform distribution mixed into every categorical.0.01
actor_gradstr"dynamics" backpropagates returns through the imagined dynamics (the paper's first version for continuous actions), "reinforce" uses the score function (its 2024 revision).'dynamics'
samplebooldraw the stochastic state in encode, predict and rollout; otherwise take its mode.False
cost_onstrthe part of the model state that cost compares with the goal: "stoch", "deter" or "full" (the default, which planned best on Two-Rooms).'full'

Members

MemberDescription
initialThe learned initial model state (batch_size, feat_dim): tanh of a learned h, and the mode of its prior.
img_stepPrior step from model states (..., feat_dim) and actions (..., action_dim); returns the next state and the prior log-probabilities (..., stoch, classes).
obs_stepPosterior step: the next state (..., feat_dim) given the next image's embedding, with the posterior and prior log-probabilities.
observeFilter images (B, T, C, H, W) with the T - 1 actions between them (B, T - 1, action_dim) (zeros when omitted).
encodeImages (B, T, C, H, W) to filtered model states (B, T, feat_dim); see observe.
stepTrack the model state online: from state (B, feat_dim), action and the next image (B, C, H, W) to the next posterior state.
predictPrior next states from model states (..., feat_dim) and actions (..., action_dim).
costSquared distance between the final model state of each rollout (B, T, feat_dim) and the goal state (B, feat_dim), on the part named by cost_on: the stochastic state, the deterministic one or both.
decodeModel states (..., feat_dim) to images (..., C, H, W).
policyThe actor's Gaussian over actions at model states (..., feat_dim): mean tanh(μ) and std in [min_std, max_std], as in the reference's continuous actor.
actActions (..., action_dim) in [-1, 1] at model states: the actor's mean, or a clipped sample.
valueThe critic's (or its EMA's) value (...) of model states (..., feat_dim).
imagineRoll the actor out in imagination from states (N, feat_dim); returns states (N, H + 1, feat_dim) and the sampled actions (N, H + 1, action_dim) (the last one is never executed).
lambda_returnsλ-returns (N, H) from rewards and continue flags (N, H) of states 1..H and values (N, H + 1) of states 0..H: R_t = r_{t+1} + γ c_{t+1} ((1 - λ) v_{t+1} + λ R_{t+1}), R_H = v_H.
actor_critic_lossCritic and actor losses on imagined trajectories from start states (N, feat_dim) (detached), whose continue flags cont (N,) default to 1.
forwardobs (B, T + 1, C, H, W) in [0, 1], actions (B, T, action_dim) and optionally rewards and terminated (B, T): actions[:, t] is applied at obs[:, t], earns rewards[:, t] and leads to obs[:, t + 1], which terminated[:, t] marks as terminal.
param_groupsAdam groups with the paper's rates: the world model at 1e-4 (eps=1e-8), the actor and the critic at 3e-5 (eps=1e-5).
clip_grad_normClip the world model's, the actor's and the critic's gradients separately (the paper's norms); returns the three norms.
update_targetEMA update of the slow critic that regularizes the critic.
Source code in torch_world/models/dreamer/_dreamerv3.py
python
class DreamerV3(WorldModel):
    """DreamerV3: a recurrent state-space model (RSSM) learned by reconstruction, and an actor-critic learned in its
    imagination.

    The model state ``s_t = (h_t, z_t)`` joins a deterministic GRU state ``h_t = f(h_{t-1}, z_{t-1}, a_{t-1})`` and a
    stochastic state of ``stoch`` categoricals with ``classes`` classes each, drawn with straight-through gradients
    from the posterior ``q(z_t | h_t, x_t)`` when the image is seen and from the prior ``p(z_t | h_t)`` when it is
    imagined; both mix 1% uniform into their probabilities. From ``s_t`` a CNN decoder reconstructs the image, a reward
    head regresses the reward with two-hot symlog bins and a continue head predicts whether the episode goes on. KL
    balancing with free bits trains the prior toward the posterior (``dyn``) and, more weakly, the reverse (``rep``):

        L = E[ ||x̂_t - x_t||² - ln p(r_t | s_t) - ln p(c_t | s_t) + β_dyn max(1, KL[sg(q) || p])
               + β_rep max(1, KL[q || sg(p)]) ]

    With rewards, an actor and a critic learn on trajectories imagined from every posterior state for ``horizon``
    steps. The critic regresses two-hot λ-returns ``R_t = r_{t+1} + γ c_{t+1} ((1 - λ) v_{t+1} + λ R_{t+1})`` and the
    outputs of its own EMA; the actor maximizes ``(R_t - v_t) / max(1, S)``, with ``S`` the EMA of the 5th to 95th
    percentile range of the returns, plus ``η`` times its entropy. Without rewards only the world model learns.

    The model state, flattened to ``(..., deter_dim + stoch * classes)``, is the latent of ``encode``, ``predict``
    and ``rollout``, so ``CEM`` can plan on it toward an encoded goal image; ``act`` gives the actor's actions.
    ``forward`` sums the world-model, critic and actor losses: their gradients reach disjoint parameters, as with the
    reference's three optimizers. Train with ``param_groups``, ``clip_grad_norm`` and ``update_target``.

    Hafner et al., "Mastering Diverse Domains through World Models", 2023.
    Paper: https://arxiv.org/abs/2301.04104
    Code: https://github.com/danijar/dreamerv3

    Args:
        encoder: module mapping images ``(N, C, H, W)`` to embeddings ``(N, embed_dim)``; ``conv_encoder`` by default.
        decoder: module mapping model states ``(N, feat_dim)`` to images; ``conv_decoder`` by default.
        cnn_depth: channels of the first convolution of the default encoder and decoder (the paper's multiplier).
        free_nats: free bits of both KL terms, summed over the categoricals.
        unimix: share of the uniform distribution mixed into every categorical.
        actor_grad: ``"dynamics"`` backpropagates returns through the imagined dynamics (the paper's first version
            for continuous actions), ``"reinforce"`` uses the score function (its 2024 revision).
        sample: draw the stochastic state in ``encode``, ``predict`` and ``rollout``; otherwise take its mode.
        cost_on: the part of the model state that ``cost`` compares with the goal: ``"stoch"``, ``"deter"`` or
            ``"full"`` (the default, which planned best on Two-Rooms).
    """

    history = 1

    def __init__(
        self,
        action_dim: int,
        in_channels: int = 3,
        img_size: int = 64,
        encoder: nn.Module | None = None,
        decoder: nn.Module | None = None,
        embed_dim: int | None = None,
        cnn_depth: int = 16,
        deter_dim: int = 256,
        stoch: int = 32,
        classes: int = 16,
        hidden_dim: int = 256,
        mlp_layers: int = 2,
        num_bins: int = 255,
        unimix: float = 0.01,
        free_nats: float = 1.0,
        dyn_coef: float = 0.5,
        rep_coef: float = 0.1,
        horizon: int = 15,
        discount: float = 1 - 1 / 333,
        lam: float = 0.95,
        entropy_coef: float = 3e-4,
        slow_reg: float = 1.0,
        retnorm_decay: float = 0.99,
        min_std: float = 0.1,
        max_std: float = 1.0,
        actor_grad: str = "dynamics",
        sample: bool = False,
        cost_on: str = "full",
    ):
        super().__init__()
        if cost_on not in ("stoch", "deter", "full"):
            raise ValueError(f"cost_on must be 'stoch', 'deter' or 'full', not {cost_on!r}")
        if actor_grad not in ("dynamics", "reinforce"):
            raise ValueError(f"actor_grad must be 'dynamics' or 'reinforce', not {actor_grad!r}")
        self.action_dim, self.deter_dim, self.stoch, self.classes = action_dim, deter_dim, stoch, classes
        self.unimix, self.free_nats, self.dyn_coef, self.rep_coef = unimix, free_nats, dyn_coef, rep_coef
        self.horizon, self.discount, self.lam, self.entropy_coef = horizon, discount, lam, entropy_coef
        self.slow_reg, self.retnorm_decay, self.min_std, self.max_std = slow_reg, retnorm_decay, min_std, max_std
        self.actor_grad, self.sample, self.cost_on = actor_grad, sample, cost_on
        self.feat_dim = feat = deter_dim + stoch * classes
        if encoder is None:
            encoder = conv_encoder(in_channels, cnn_depth, img_size)
            embed_dim = 16 * cnn_depth * 2 ** (int(math.log2(img_size // 4)) - 1)
        if embed_dim is None:
            raise ValueError("pass embed_dim with a custom encoder")
        self.encoder = encoder
        self.decoder = decoder if decoder is not None else conv_decoder(feat, in_channels, cnn_depth, img_size)
        self.img_in = nn.Sequential(
            nn.Linear(stoch * classes + action_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.SiLU()
        )
        self.gru = GRUCell(hidden_dim, deter_dim)
        self.prior = _mlp([deter_dim, hidden_dim, stoch * classes])
        self.posterior = _mlp([deter_dim + embed_dim, hidden_dim, stoch * classes])
        self.init_deter = nn.Parameter(torch.zeros(deter_dim))
        heads = [hidden_dim] * mlp_layers
        self.reward = _mlp([feat, *heads, num_bins])
        self.cont = _mlp([feat, *heads, 1])
        self.actor = _mlp([feat, *heads, 2 * action_dim])
        self.critic = _mlp([feat, *heads, num_bins])
        for head in (self.reward, self.critic):
            nn.init.zeros_(head[-1].weight)
            nn.init.zeros_(head[-1].bias)
        self.slow_critic = copy.deepcopy(self.critic).requires_grad_(False)
        self.register_buffer("bins", torch.linspace(-20.0, 20.0, num_bins))
        self.register_buffer("ret_low", torch.zeros(()))
        self.register_buffer("ret_high", torch.zeros(()))

    # ----- RSSM -----

    def _dist(self, logits: Tensor) -> Tensor:
        """Unimix log-probabilities ``(..., stoch, classes)`` from logits ``(..., stoch * classes)``."""
        probs = logits.unflatten(-1, (self.stoch, self.classes)).softmax(-1)
        return ((1 - self.unimix) * probs + self.unimix / self.classes).log()

    def _draw(self, logp: Tensor, sample: bool) -> Tensor:
        """One-hot states ``(..., stoch * classes)``: a straight-through sample, or the mode."""
        probs = logp.exp()
        idx = torch.multinomial(probs.flatten(0, -2), 1).view(probs.shape[:-1]) if sample else probs.argmax(-1)
        onehot = F.one_hot(idx, self.classes).to(probs)
        return (onehot + probs - probs.detach()).flatten(-2)

    def initial(self, batch_size: int) -> Tensor:
        """The learned initial model state ``(batch_size, feat_dim)``: ``tanh`` of a learned ``h``, and the mode of
        its prior."""
        h = self.init_deter.tanh().expand(batch_size, -1)
        return torch.cat([h, self._draw(self._dist(self.prior(h)), False)], -1)

    def img_step(self, s: Tensor, action: Tensor, sample: bool = True, frozen: bool = False) -> tuple[Tensor, Tensor]:
        """Prior step from model states ``(..., feat_dim)`` and actions ``(..., action_dim)``; returns the next state
        and the prior log-probabilities ``(..., stoch, classes)``. ``frozen`` keeps gradients out of the weights."""
        call = _frozen if frozen else _plain
        action = action / action.abs().clamp(min=1).detach()  # the reference's action clip at 1
        x = call(self.img_in, torch.cat([s[..., self.deter_dim :], action], -1))
        h = call(self.gru, x, s[..., : self.deter_dim])
        logp = self._dist(call(self.prior, h))
        return torch.cat([h, self._draw(logp, sample)], -1), logp

    def obs_step(self, s: Tensor, action: Tensor, embed: Tensor, sample: bool = True) -> tuple[Tensor, Tensor, Tensor]:
        """Posterior step: the next state ``(..., feat_dim)`` given the next image's embedding, with the posterior and
        prior log-probabilities."""
        prior, prior_logp = self.img_step(s, action, sample)
        h = prior[..., : self.deter_dim]
        logp = self._dist(self.posterior(torch.cat([h, embed], -1)))
        return torch.cat([h, self._draw(logp, sample)], -1), logp, prior_logp

    def observe(
        self, obs: Tensor, actions: Tensor | None = None, state: Tensor | None = None, sample: bool = True
    ) -> tuple[Tensor, Tensor, Tensor]:
        """Filter images ``(B, T, C, H, W)`` with the ``T - 1`` actions between them ``(B, T - 1, action_dim)``
        (zeros when omitted). The first step starts from ``state`` ``(B, feat_dim)``, the initial state by default,
        with a zero action, as in the reference. Returns posterior states ``(B, T, feat_dim)`` and the posterior and
        prior log-probabilities ``(B, T, stoch, classes)``."""
        B, T = obs.shape[:2]
        embed = self.encoder(obs.flatten(0, 1)).unflatten(0, (B, T))
        zero = embed.new_zeros(B, 1, self.action_dim)
        actions = zero.expand(-1, T - 1, -1) if actions is None else actions
        actions = torch.cat([zero, actions[:, : T - 1].to(embed)], 1)
        s = self.initial(B) if state is None else state
        posts, post_logps, prior_logps = [], [], []
        for t in range(T):
            s, post_logp, prior_logp = self.obs_step(s, actions[:, t], embed[:, t], sample)
            posts.append(s)
            post_logps.append(post_logp)
            prior_logps.append(prior_logp)
        return torch.stack(posts, 1), torch.stack(post_logps, 1), torch.stack(prior_logps, 1)

    def encode(self, obs: Tensor, actions: Tensor | None = None) -> Tensor:
        """Images ``(B, T, C, H, W)`` to filtered model states ``(B, T, feat_dim)``; see ``observe``."""
        return self.observe(obs, actions, sample=self.sample)[0]

    def step(self, state: Tensor, action: Tensor, obs: Tensor) -> Tensor:
        """Track the model state online: from ``state`` ``(B, feat_dim)``, ``action`` and the next image
        ``(B, C, H, W)`` to the next posterior state."""
        return self.obs_step(state, action, self.encoder(obs), self.sample)[0]

    def predict(self, z: Tensor, actions: Tensor, sample: bool | None = None) -> Tensor:
        """Prior next states from model states ``(..., feat_dim)`` and actions ``(..., action_dim)``."""
        return self.img_step(z, actions, self.sample if sample is None else sample)[0]

    def cost(self, z: Tensor, goal: Tensor) -> Tensor:
        """Squared distance between the final model state of each rollout ``(B, T, feat_dim)`` and the goal state
        ``(B, feat_dim)``, on the part named by ``cost_on``: the stochastic state, the deterministic one or both."""
        part = {"stoch": slice(self.deter_dim, None), "deter": slice(0, self.deter_dim), "full": slice(None)}
        part = part[self.cost_on]
        return (z[:, -1, part] - goal[:, part]).square().mean(-1)

    def decode(self, z: Tensor) -> Tensor:
        """Model states ``(..., feat_dim)`` to images ``(..., C, H, W)``."""
        return self.decoder(z.flatten(0, -2)).unflatten(0, z.shape[:-1])

    # ----- actor-critic -----

    def policy(self, s: Tensor, frozen: bool = False) -> torch.distributions.Normal:
        """The actor's Gaussian over actions at model states ``(..., feat_dim)``: mean ``tanh(μ)`` and std in
        ``[min_std, max_std]``, as in the reference's continuous actor."""
        mean, std = (_frozen if frozen else _plain)(self.actor, s).chunk(2, -1)
        std = (self.max_std - self.min_std) * (std + 2).sigmoid() + self.min_std
        return torch.distributions.Normal(mean.tanh(), std)

    def act(self, s: Tensor, sample: bool = False) -> Tensor:
        """Actions ``(..., action_dim)`` in ``[-1, 1]`` at model states: the actor's mean, or a clipped sample."""
        dist = self.policy(s)
        return (dist.sample() if sample else dist.mean).clamp(-1, 1)

    def value(self, s: Tensor, slow: bool = False, frozen: bool = False) -> Tensor:
        """The critic's (or its EMA's) value ``(...)`` of model states ``(..., feat_dim)``."""
        net = self.slow_critic if slow else self.critic
        return two_hot_inv((_frozen if frozen else _plain)(net, s), self.bins)

    def imagine(self, s: Tensor, horizon: int | None = None, frozen: bool = False) -> tuple[Tensor, Tensor]:
        """Roll the actor out in imagination from states ``(N, feat_dim)``; returns states ``(N, H + 1, feat_dim)``
        and the sampled actions ``(N, H + 1, action_dim)`` (the last one is never executed)."""
        states, actions = [s], []
        for _ in range(horizon or self.horizon):
            actions.append(self.policy(states[-1].detach() if self.actor_grad == "reinforce" else states[-1]).rsample())
            states.append(self.img_step(states[-1], actions[-1], sample=True, frozen=frozen)[0])
        actions.append(self.policy(states[-1].detach()).rsample())
        return torch.stack(states, 1), torch.stack(actions, 1)

    def lambda_returns(self, rewards: Tensor, conts: Tensor, values: Tensor) -> Tensor:
        """λ-returns ``(N, H)`` from rewards and continue flags ``(N, H)`` of states ``1..H`` and values
        ``(N, H + 1)`` of states ``0..H``: ``R_t = r_{t+1} + γ c_{t+1} ((1 - λ) v_{t+1} + λ R_{t+1})``, ``R_H = v_H``."""
        out, ret = [], values[:, -1]
        for t in reversed(range(rewards.size(1))):
            ret = rewards[:, t] + self.discount * conts[:, t] * ((1 - self.lam) * values[:, t + 1] + self.lam * ret)
            out.append(ret)
        return torch.stack(out[::-1], 1)

    def actor_critic_loss(self, start: Tensor, cont: Tensor | None = None) -> dict[str, Tensor]:
        """Critic and actor losses on imagined trajectories from start states ``(N, feat_dim)`` (detached), whose
        continue flags ``cont`` ``(N,)`` default to 1. Neither loss updates the world model."""
        start = start.detach()
        states, actions = self.imagine(start, frozen=True)
        conts = (_frozen(self.cont, states[:, 1:]).squeeze(-1) > 0).to(start)  # the mode, as in the reference
        rewards = two_hot_inv(_frozen(self.reward, states[:, 1:]), self.bins)
        values = self.value(states, frozen=True)
        rets = self.lambda_returns(rewards, conts, values)
        first = torch.ones_like(conts[:, 0]) if cont is None else cont.to(conts)
        weight = torch.cumprod(torch.cat([first[:, None], self.discount * conts[:, :-1]], 1), 1).detach()

        if self.training:
            low, high = torch.quantile(rets.detach().flatten().float(), rets.new_tensor([0.05, 0.95]))
            self.ret_low.lerp_(low, 1 - self.retnorm_decay)
            self.ret_high.lerp_(high, 1 - self.retnorm_decay)
        scale = (self.ret_high - self.ret_low).clamp(min=1.0)
        adv = (rets - values[:, :-1].detach()) / scale
        policy = self.policy(states[:, :-1].detach())
        entropy = policy.entropy().sum(-1)
        if self.actor_grad == "dynamics":
            actor = -adv
        else:
            actor = -policy.log_prob(actions[:, :-1].detach()).sum(-1) * adv.detach()
        actor = (weight * (actor - self.entropy_coef * entropy)).mean()

        traj = states[:, :-1].detach()
        logits = self.critic(traj).log_softmax(-1)
        with torch.no_grad():
            slow = self.value(traj, slow=True)
        critic = -(two_hot(rets.detach(), self.bins) * logits).sum(-1)
        critic = critic - self.slow_reg * (two_hot(slow, self.bins) * logits).sum(-1)
        critic = (weight * critic).mean()
        return {"critic_loss": critic, "actor_loss": actor, "entropy": entropy.mean().detach()}

    # ----- training -----

    def forward(
        self, obs: Tensor, actions: Tensor, rewards: Tensor | None = None, terminated: Tensor | None = None
    ) -> dict[str, Tensor]:
        """``obs`` ``(B, T + 1, C, H, W)`` in ``[0, 1]``, ``actions`` ``(B, T, action_dim)`` and optionally ``rewards``
        and ``terminated`` ``(B, T)``: ``actions[:, t]`` is applied at ``obs[:, t]``, earns ``rewards[:, t]`` and leads
        to ``obs[:, t + 1]``, which ``terminated[:, t]`` marks as terminal. Without rewards only the world model learns.
        """
        posts, post_logp, prior_logp = self.observe(obs, actions, sample=True)
        target = obs.float() / 255 if obs.dtype == torch.uint8 else obs
        image = (self.decode(posts) - target).square().flatten(2).sum(-1).mean()
        dyn = _kl(post_logp.detach(), prior_logp)
        rep = _kl(post_logp, prior_logp.detach())
        out = {
            "image_loss": image,
            "dyn_loss": dyn.clamp(min=self.free_nats).mean(),
            "rep_loss": rep.clamp(min=self.free_nats).mean(),
            "kl": dyn.mean().detach(),
        }
        loss = image + self.dyn_coef * out["dyn_loss"] + self.rep_coef * out["rep_loss"]
        if rewards is None:
            return {"loss": loss, **out}

        terminated = torch.zeros_like(rewards) if terminated is None else terminated.to(rewards.dtype)
        out["reward_loss"] = -(two_hot(rewards, self.bins) * self.reward(posts[:, 1:]).log_softmax(-1)).sum(-1).mean()
        out["continue_loss"] = F.binary_cross_entropy_with_logits(self.cont(posts[:, 1:]).squeeze(-1), 1 - terminated)
        loss = loss + out["reward_loss"] + out["continue_loss"]
        cont = torch.cat([torch.ones_like(terminated[:, :1]), 1 - terminated], 1)
        out.update(self.actor_critic_loss(posts.flatten(0, 1), cont.flatten()))
        return {"loss": loss + out["critic_loss"] + out["actor_loss"], **out}

    def param_groups(self, lr: float = 1e-4, actor_lr: float = 3e-5, critic_lr: float = 3e-5) -> list[dict]:
        """Adam groups with the paper's rates: the world model at ``1e-4`` (``eps=1e-8``), the actor and the critic at
        ``3e-5`` (``eps=1e-5``)."""
        actor, critic = list(self.actor.parameters()), list(self.critic.parameters())
        skip = {id(p) for p in actor + critic}
        world = [p for p in self.parameters() if p.requires_grad and id(p) not in skip]
        return [
            {"params": world, "lr": lr, "eps": 1e-8},
            {"params": actor, "lr": actor_lr, "eps": 1e-5},
            {"params": critic, "lr": critic_lr, "eps": 1e-5},
        ]

    def clip_grad_norm(self, world: float = 1000.0, actor: float = 100.0, critic: float = 100.0) -> list[Tensor]:
        """Clip the world model's, the actor's and the critic's gradients separately (the paper's norms); returns
        the three norms."""
        return [nn.utils.clip_grad_norm_(g["params"], m) for g, m in zip(self.param_groups(), (world, actor, critic))]

    def update_target(self, momentum: float = 0.98):
        """EMA update of the slow critic that regularizes the critic."""
        ema_update(self.slow_critic, self.critic, momentum)

method initial ​

torch_world.models.DreamerV3.initial GitHub

python
initial(batch_size: int) -> Tensor

The learned initial model state (batch_size, feat_dim): tanh of a learned h, and the mode of its prior.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def initial(self, batch_size: int) -> Tensor:
    """The learned initial model state ``(batch_size, feat_dim)``: ``tanh`` of a learned ``h``, and the mode of
    its prior."""
    h = self.init_deter.tanh().expand(batch_size, -1)
    return torch.cat([h, self._draw(self._dist(self.prior(h)), False)], -1)

method img_step ​

torch_world.models.DreamerV3.img_step GitHub

python
img_step(
    s: Tensor, action: Tensor, sample: bool = True, frozen: bool = False
) -> tuple[Tensor, Tensor]

Prior step from model states (..., feat_dim) and actions (..., action_dim); returns the next state and the prior log-probabilities (..., stoch, classes). frozen keeps gradients out of the weights.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def img_step(self, s: Tensor, action: Tensor, sample: bool = True, frozen: bool = False) -> tuple[Tensor, Tensor]:
    """Prior step from model states ``(..., feat_dim)`` and actions ``(..., action_dim)``; returns the next state
    and the prior log-probabilities ``(..., stoch, classes)``. ``frozen`` keeps gradients out of the weights."""
    call = _frozen if frozen else _plain
    action = action / action.abs().clamp(min=1).detach()  # the reference's action clip at 1
    x = call(self.img_in, torch.cat([s[..., self.deter_dim :], action], -1))
    h = call(self.gru, x, s[..., : self.deter_dim])
    logp = self._dist(call(self.prior, h))
    return torch.cat([h, self._draw(logp, sample)], -1), logp

method obs_step ​

torch_world.models.DreamerV3.obs_step GitHub

python
obs_step(
    s: Tensor, action: Tensor, embed: Tensor, sample: bool = True
) -> tuple[Tensor, Tensor, Tensor]

Posterior step: the next state (..., feat_dim) given the next image's embedding, with the posterior and prior log-probabilities.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def obs_step(self, s: Tensor, action: Tensor, embed: Tensor, sample: bool = True) -> tuple[Tensor, Tensor, Tensor]:
    """Posterior step: the next state ``(..., feat_dim)`` given the next image's embedding, with the posterior and
    prior log-probabilities."""
    prior, prior_logp = self.img_step(s, action, sample)
    h = prior[..., : self.deter_dim]
    logp = self._dist(self.posterior(torch.cat([h, embed], -1)))
    return torch.cat([h, self._draw(logp, sample)], -1), logp, prior_logp

method observe ​

torch_world.models.DreamerV3.observe GitHub

python
observe(
    obs: Tensor,
    actions: Tensor | None = None,
    state: Tensor | None = None,
    sample: bool = True,
) -> tuple[Tensor, Tensor, Tensor]

Filter images (B, T, C, H, W) with the T - 1 actions between them (B, T - 1, action_dim) (zeros when omitted). The first step starts from state (B, feat_dim), the initial state by default, with a zero action, as in the reference. Returns posterior states (B, T, feat_dim) and the posterior and prior log-probabilities (B, T, stoch, classes).

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def observe(
    self, obs: Tensor, actions: Tensor | None = None, state: Tensor | None = None, sample: bool = True
) -> tuple[Tensor, Tensor, Tensor]:
    """Filter images ``(B, T, C, H, W)`` with the ``T - 1`` actions between them ``(B, T - 1, action_dim)``
    (zeros when omitted). The first step starts from ``state`` ``(B, feat_dim)``, the initial state by default,
    with a zero action, as in the reference. Returns posterior states ``(B, T, feat_dim)`` and the posterior and
    prior log-probabilities ``(B, T, stoch, classes)``."""
    B, T = obs.shape[:2]
    embed = self.encoder(obs.flatten(0, 1)).unflatten(0, (B, T))
    zero = embed.new_zeros(B, 1, self.action_dim)
    actions = zero.expand(-1, T - 1, -1) if actions is None else actions
    actions = torch.cat([zero, actions[:, : T - 1].to(embed)], 1)
    s = self.initial(B) if state is None else state
    posts, post_logps, prior_logps = [], [], []
    for t in range(T):
        s, post_logp, prior_logp = self.obs_step(s, actions[:, t], embed[:, t], sample)
        posts.append(s)
        post_logps.append(post_logp)
        prior_logps.append(prior_logp)
    return torch.stack(posts, 1), torch.stack(post_logps, 1), torch.stack(prior_logps, 1)

method encode ​

torch_world.models.DreamerV3.encode GitHub

python
encode(obs: Tensor, actions: Tensor | None = None) -> Tensor

Images (B, T, C, H, W) to filtered model states (B, T, feat_dim); see observe.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def encode(self, obs: Tensor, actions: Tensor | None = None) -> Tensor:
    """Images ``(B, T, C, H, W)`` to filtered model states ``(B, T, feat_dim)``; see ``observe``."""
    return self.observe(obs, actions, sample=self.sample)[0]

method step ​

torch_world.models.DreamerV3.step GitHub

python
step(state: Tensor, action: Tensor, obs: Tensor) -> Tensor

Track the model state online: from state (B, feat_dim), action and the next image (B, C, H, W) to the next posterior state.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def step(self, state: Tensor, action: Tensor, obs: Tensor) -> Tensor:
    """Track the model state online: from ``state`` ``(B, feat_dim)``, ``action`` and the next image
    ``(B, C, H, W)`` to the next posterior state."""
    return self.obs_step(state, action, self.encoder(obs), self.sample)[0]

method predict ​

torch_world.models.DreamerV3.predict GitHub

python
predict(z: Tensor, actions: Tensor, sample: bool | None = None) -> Tensor

Prior next states from model states (..., feat_dim) and actions (..., action_dim).

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def predict(self, z: Tensor, actions: Tensor, sample: bool | None = None) -> Tensor:
    """Prior next states from model states ``(..., feat_dim)`` and actions ``(..., action_dim)``."""
    return self.img_step(z, actions, self.sample if sample is None else sample)[0]

method cost ​

torch_world.models.DreamerV3.cost GitHub

python
cost(z: Tensor, goal: Tensor) -> Tensor

Squared distance between the final model state of each rollout (B, T, feat_dim) and the goal state (B, feat_dim), on the part named by cost_on: the stochastic state, the deterministic one or both.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def cost(self, z: Tensor, goal: Tensor) -> Tensor:
    """Squared distance between the final model state of each rollout ``(B, T, feat_dim)`` and the goal state
    ``(B, feat_dim)``, on the part named by ``cost_on``: the stochastic state, the deterministic one or both."""
    part = {"stoch": slice(self.deter_dim, None), "deter": slice(0, self.deter_dim), "full": slice(None)}
    part = part[self.cost_on]
    return (z[:, -1, part] - goal[:, part]).square().mean(-1)

method decode ​

torch_world.models.DreamerV3.decode GitHub

python
decode(z: Tensor) -> Tensor

Model states (..., feat_dim) to images (..., C, H, W).

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def decode(self, z: Tensor) -> Tensor:
    """Model states ``(..., feat_dim)`` to images ``(..., C, H, W)``."""
    return self.decoder(z.flatten(0, -2)).unflatten(0, z.shape[:-1])

method policy ​

torch_world.models.DreamerV3.policy GitHub

python
policy(s: Tensor, frozen: bool = False) -> torch.distributions.Normal

The actor's Gaussian over actions at model states (..., feat_dim): mean tanh(μ) and std in [min_std, max_std], as in the reference's continuous actor.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def policy(self, s: Tensor, frozen: bool = False) -> torch.distributions.Normal:
    """The actor's Gaussian over actions at model states ``(..., feat_dim)``: mean ``tanh(μ)`` and std in
    ``[min_std, max_std]``, as in the reference's continuous actor."""
    mean, std = (_frozen if frozen else _plain)(self.actor, s).chunk(2, -1)
    std = (self.max_std - self.min_std) * (std + 2).sigmoid() + self.min_std
    return torch.distributions.Normal(mean.tanh(), std)

method act ​

torch_world.models.DreamerV3.act GitHub

python
act(s: Tensor, sample: bool = False) -> Tensor

Actions (..., action_dim) in [-1, 1] at model states: the actor's mean, or a clipped sample.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def act(self, s: Tensor, sample: bool = False) -> Tensor:
    """Actions ``(..., action_dim)`` in ``[-1, 1]`` at model states: the actor's mean, or a clipped sample."""
    dist = self.policy(s)
    return (dist.sample() if sample else dist.mean).clamp(-1, 1)

method value ​

torch_world.models.DreamerV3.value GitHub

python
value(s: Tensor, slow: bool = False, frozen: bool = False) -> Tensor

The critic's (or its EMA's) value (...) of model states (..., feat_dim).

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def value(self, s: Tensor, slow: bool = False, frozen: bool = False) -> Tensor:
    """The critic's (or its EMA's) value ``(...)`` of model states ``(..., feat_dim)``."""
    net = self.slow_critic if slow else self.critic
    return two_hot_inv((_frozen if frozen else _plain)(net, s), self.bins)

method imagine ​

torch_world.models.DreamerV3.imagine GitHub

python
imagine(
    s: Tensor, horizon: int | None = None, frozen: bool = False
) -> tuple[Tensor, Tensor]

Roll the actor out in imagination from states (N, feat_dim); returns states (N, H + 1, feat_dim) and the sampled actions (N, H + 1, action_dim) (the last one is never executed).

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def imagine(self, s: Tensor, horizon: int | None = None, frozen: bool = False) -> tuple[Tensor, Tensor]:
    """Roll the actor out in imagination from states ``(N, feat_dim)``; returns states ``(N, H + 1, feat_dim)``
    and the sampled actions ``(N, H + 1, action_dim)`` (the last one is never executed)."""
    states, actions = [s], []
    for _ in range(horizon or self.horizon):
        actions.append(self.policy(states[-1].detach() if self.actor_grad == "reinforce" else states[-1]).rsample())
        states.append(self.img_step(states[-1], actions[-1], sample=True, frozen=frozen)[0])
    actions.append(self.policy(states[-1].detach()).rsample())
    return torch.stack(states, 1), torch.stack(actions, 1)

method lambda_returns ​

torch_world.models.DreamerV3.lambda_returns GitHub

python
lambda_returns(rewards: Tensor, conts: Tensor, values: Tensor) -> Tensor

λ-returns (N, H) from rewards and continue flags (N, H) of states 1..H and values (N, H + 1) of states 0..H: R_t = r_{t+1} + γ c_{t+1} ((1 - λ) v_{t+1} + λ R_{t+1}), R_H = v_H.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def lambda_returns(self, rewards: Tensor, conts: Tensor, values: Tensor) -> Tensor:
    """λ-returns ``(N, H)`` from rewards and continue flags ``(N, H)`` of states ``1..H`` and values
    ``(N, H + 1)`` of states ``0..H``: ``R_t = r_{t+1} + γ c_{t+1} ((1 - λ) v_{t+1} + λ R_{t+1})``, ``R_H = v_H``."""
    out, ret = [], values[:, -1]
    for t in reversed(range(rewards.size(1))):
        ret = rewards[:, t] + self.discount * conts[:, t] * ((1 - self.lam) * values[:, t + 1] + self.lam * ret)
        out.append(ret)
    return torch.stack(out[::-1], 1)

method actor_critic_loss ​

torch_world.models.DreamerV3.actor_critic_loss GitHub

python
actor_critic_loss(
    start: Tensor, cont: Tensor | None = None
) -> dict[str, Tensor]

Critic and actor losses on imagined trajectories from start states (N, feat_dim) (detached), whose continue flags cont (N,) default to 1. Neither loss updates the world model.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def actor_critic_loss(self, start: Tensor, cont: Tensor | None = None) -> dict[str, Tensor]:
    """Critic and actor losses on imagined trajectories from start states ``(N, feat_dim)`` (detached), whose
    continue flags ``cont`` ``(N,)`` default to 1. Neither loss updates the world model."""
    start = start.detach()
    states, actions = self.imagine(start, frozen=True)
    conts = (_frozen(self.cont, states[:, 1:]).squeeze(-1) > 0).to(start)  # the mode, as in the reference
    rewards = two_hot_inv(_frozen(self.reward, states[:, 1:]), self.bins)
    values = self.value(states, frozen=True)
    rets = self.lambda_returns(rewards, conts, values)
    first = torch.ones_like(conts[:, 0]) if cont is None else cont.to(conts)
    weight = torch.cumprod(torch.cat([first[:, None], self.discount * conts[:, :-1]], 1), 1).detach()

    if self.training:
        low, high = torch.quantile(rets.detach().flatten().float(), rets.new_tensor([0.05, 0.95]))
        self.ret_low.lerp_(low, 1 - self.retnorm_decay)
        self.ret_high.lerp_(high, 1 - self.retnorm_decay)
    scale = (self.ret_high - self.ret_low).clamp(min=1.0)
    adv = (rets - values[:, :-1].detach()) / scale
    policy = self.policy(states[:, :-1].detach())
    entropy = policy.entropy().sum(-1)
    if self.actor_grad == "dynamics":
        actor = -adv
    else:
        actor = -policy.log_prob(actions[:, :-1].detach()).sum(-1) * adv.detach()
    actor = (weight * (actor - self.entropy_coef * entropy)).mean()

    traj = states[:, :-1].detach()
    logits = self.critic(traj).log_softmax(-1)
    with torch.no_grad():
        slow = self.value(traj, slow=True)
    critic = -(two_hot(rets.detach(), self.bins) * logits).sum(-1)
    critic = critic - self.slow_reg * (two_hot(slow, self.bins) * logits).sum(-1)
    critic = (weight * critic).mean()
    return {"critic_loss": critic, "actor_loss": actor, "entropy": entropy.mean().detach()}

method forward ​

torch_world.models.DreamerV3.forward GitHub

python
forward(
    obs: Tensor,
    actions: Tensor,
    rewards: Tensor | None = None,
    terminated: Tensor | None = None,
) -> dict[str, Tensor]

obs (B, T + 1, C, H, W) in [0, 1], actions (B, T, action_dim) and optionally rewards and terminated (B, T): actions[:, t] is applied at obs[:, t], earns rewards[:, t] and leads to obs[:, t + 1], which terminated[:, t] marks as terminal. Without rewards only the world model learns.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def forward(
    self, obs: Tensor, actions: Tensor, rewards: Tensor | None = None, terminated: Tensor | None = None
) -> dict[str, Tensor]:
    """``obs`` ``(B, T + 1, C, H, W)`` in ``[0, 1]``, ``actions`` ``(B, T, action_dim)`` and optionally ``rewards``
    and ``terminated`` ``(B, T)``: ``actions[:, t]`` is applied at ``obs[:, t]``, earns ``rewards[:, t]`` and leads
    to ``obs[:, t + 1]``, which ``terminated[:, t]`` marks as terminal. Without rewards only the world model learns.
    """
    posts, post_logp, prior_logp = self.observe(obs, actions, sample=True)
    target = obs.float() / 255 if obs.dtype == torch.uint8 else obs
    image = (self.decode(posts) - target).square().flatten(2).sum(-1).mean()
    dyn = _kl(post_logp.detach(), prior_logp)
    rep = _kl(post_logp, prior_logp.detach())
    out = {
        "image_loss": image,
        "dyn_loss": dyn.clamp(min=self.free_nats).mean(),
        "rep_loss": rep.clamp(min=self.free_nats).mean(),
        "kl": dyn.mean().detach(),
    }
    loss = image + self.dyn_coef * out["dyn_loss"] + self.rep_coef * out["rep_loss"]
    if rewards is None:
        return {"loss": loss, **out}

    terminated = torch.zeros_like(rewards) if terminated is None else terminated.to(rewards.dtype)
    out["reward_loss"] = -(two_hot(rewards, self.bins) * self.reward(posts[:, 1:]).log_softmax(-1)).sum(-1).mean()
    out["continue_loss"] = F.binary_cross_entropy_with_logits(self.cont(posts[:, 1:]).squeeze(-1), 1 - terminated)
    loss = loss + out["reward_loss"] + out["continue_loss"]
    cont = torch.cat([torch.ones_like(terminated[:, :1]), 1 - terminated], 1)
    out.update(self.actor_critic_loss(posts.flatten(0, 1), cont.flatten()))
    return {"loss": loss + out["critic_loss"] + out["actor_loss"], **out}

method param_groups ​

torch_world.models.DreamerV3.param_groups GitHub

python
param_groups(
    lr: float = 0.0001, actor_lr: float = 3e-05, critic_lr: float = 3e-05
) -> list[dict]

Adam groups with the paper's rates: the world model at 1e-4 (eps=1e-8), the actor and the critic at 3e-5 (eps=1e-5).

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def param_groups(self, lr: float = 1e-4, actor_lr: float = 3e-5, critic_lr: float = 3e-5) -> list[dict]:
    """Adam groups with the paper's rates: the world model at ``1e-4`` (``eps=1e-8``), the actor and the critic at
    ``3e-5`` (``eps=1e-5``)."""
    actor, critic = list(self.actor.parameters()), list(self.critic.parameters())
    skip = {id(p) for p in actor + critic}
    world = [p for p in self.parameters() if p.requires_grad and id(p) not in skip]
    return [
        {"params": world, "lr": lr, "eps": 1e-8},
        {"params": actor, "lr": actor_lr, "eps": 1e-5},
        {"params": critic, "lr": critic_lr, "eps": 1e-5},
    ]

method clip_grad_norm ​

torch_world.models.DreamerV3.clip_grad_norm GitHub

python
clip_grad_norm(
    world: float = 1000.0, actor: float = 100.0, critic: float = 100.0
) -> list[Tensor]

Clip the world model's, the actor's and the critic's gradients separately (the paper's norms); returns the three norms.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def clip_grad_norm(self, world: float = 1000.0, actor: float = 100.0, critic: float = 100.0) -> list[Tensor]:
    """Clip the world model's, the actor's and the critic's gradients separately (the paper's norms); returns
    the three norms."""
    return [nn.utils.clip_grad_norm_(g["params"], m) for g, m in zip(self.param_groups(), (world, actor, critic))]

method update_target ​

torch_world.models.DreamerV3.update_target GitHub

python
update_target(momentum: float = 0.98)

EMA update of the slow critic that regularizes the critic.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def update_target(self, momentum: float = 0.98):
    """EMA update of the slow critic that regularizes the critic."""
    ema_update(self.slow_critic, self.critic, momentum)

function conv_encoder ​

torch_world.models.dreamer.conv_encoder GitHub

python
conv_encoder(
    in_channels: int = 3, depth: int = 32, img_size: int = 64
) -> nn.Sequential

DreamerV3's image encoder: stride-2 convolutions (kernel 4) of doubling depth, each with LayerNorm and SiLU, down to 4x4, then flattened. Maps (N, C, img_size, img_size) in [0, 1] to (N, 16 * depth * 2^(L-1)) with L = log2(img_size / 4) stages.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def conv_encoder(in_channels: int = 3, depth: int = 32, img_size: int = 64) -> nn.Sequential:
    """DreamerV3's image encoder: stride-2 convolutions (kernel 4) of doubling depth, each with LayerNorm and SiLU,
    down to 4x4, then flattened. Maps ``(N, C, img_size, img_size)`` in ``[0, 1]`` to ``(N, 16 * depth * 2^(L-1))``
    with ``L = log2(img_size / 4)`` stages."""
    layers, c = [_Shift(-0.5)], in_channels
    for i in range(int(math.log2(img_size // 4))):
        layers += [nn.Conv2d(c, depth * 2**i, 4, 2, 1), ChannelNorm(depth * 2**i), nn.SiLU()]
        c = depth * 2**i
    return nn.Sequential(*layers, nn.Flatten())

function conv_decoder ​

torch_world.models.dreamer.conv_decoder GitHub

python
conv_decoder(
    feat_dim: int, out_channels: int = 3, depth: int = 32, img_size: int = 64
) -> nn.Sequential

DreamerV3's image decoder: a linear layer to 4x4 maps, then transposed convolutions that invert conv_encoder. Maps features (N, feat_dim) to images (N, C, img_size, img_size) centred on 0.5.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def conv_decoder(feat_dim: int, out_channels: int = 3, depth: int = 32, img_size: int = 64) -> nn.Sequential:
    """DreamerV3's image decoder: a linear layer to ``4x4`` maps, then transposed convolutions that invert
    ``conv_encoder``. Maps features ``(N, feat_dim)`` to images ``(N, C, img_size, img_size)`` centred on 0.5."""
    stages = int(math.log2(img_size // 4))
    c = depth * 2 ** (stages - 1)
    layers = [nn.Linear(feat_dim, 16 * c), nn.Unflatten(1, (c, 4, 4))]
    for i in reversed(range(stages - 1)):
        layers += [nn.ConvTranspose2d(c, depth * 2**i, 4, 2, 1), ChannelNorm(depth * 2**i), nn.SiLU()]
        c = depth * 2**i
    return nn.Sequential(*layers, nn.ConvTranspose2d(c, out_channels, 4, 2, 1), _Shift(0.5))

function two_hot ​

torch_world.models.dreamer.two_hot GitHub

python
two_hot(x: Tensor, bins: Tensor) -> Tensor

Scalars (...) to two-hot targets (..., K) over bins (K,), evenly spaced in symlog space.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def two_hot(x: Tensor, bins: Tensor) -> Tensor:
    """Scalars ``(...)`` to two-hot targets ``(..., K)`` over ``bins`` ``(K,)``, evenly spaced in symlog space."""
    lo, hi, k = bins[0], bins[-1], bins.numel()
    pos = (symlog(x).clamp(lo, hi) - lo) / (hi - lo) * (k - 1)
    idx = pos.floor().clamp(max=k - 2)
    offset = (pos - idx)[..., None]
    idx = idx.long()[..., None]
    out = x.new_zeros(*x.shape, k).scatter(-1, idx, 1 - offset)
    return out.scatter_add(-1, idx + 1, offset)

function two_hot_inv ​

torch_world.models.dreamer.two_hot_inv GitHub

python
two_hot_inv(logits: Tensor, bins: Tensor) -> Tensor

Logits (..., K) to the scalars (...): symexp of the expected bin.

Source code in torch_world/models/dreamer/_dreamerv3.py
python
def two_hot_inv(logits: Tensor, bins: Tensor) -> Tensor:
    """Logits ``(..., K)`` to the scalars ``(...)``: ``symexp`` of the expected bin."""
    return symexp((logits.softmax(-1) * bins).sum(-1))

function state_encoder ​

torch_world.models.tdmpc.state_encoder GitHub

python
state_encoder(
    obs_dim: int,
    latent_dim: int = 512,
    hidden_dim: int = 256,
    num_layers: int = 2,
    simnorm_dim: int = 8,
) -> nn.Sequential

TD-MPC2's encoder for state vectors (N, obs_dim): an MLP to (N, latent_dim) ending in SimNorm.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def state_encoder(
    obs_dim: int, latent_dim: int = 512, hidden_dim: int = 256, num_layers: int = 2, simnorm_dim: int = 8
) -> nn.Sequential:
    """TD-MPC2's encoder for state vectors ``(N, obs_dim)``: an MLP to ``(N, latent_dim)`` ending in ``SimNorm``."""
    return _init(mlp([obs_dim, *[hidden_dim] * max(num_layers - 1, 1), latent_dim], act=SimNorm(simnorm_dim)))

function pixel_encoder ​

torch_world.models.tdmpc.pixel_encoder GitHub

python
pixel_encoder(
    in_channels: int = 3, num_channels: int = 32, simnorm_dim: int = 8
) -> nn.Sequential

TD-MPC2's encoder for 64x64 images (N, C, 64, 64) in [0, 1] or uint8: random shift, four convolutions and SimNorm. The latent has num_channels * 16 features, 512 by default.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def pixel_encoder(in_channels: int = 3, num_channels: int = 32, simnorm_dim: int = 8) -> nn.Sequential:
    """TD-MPC2's encoder for 64x64 images ``(N, C, 64, 64)`` in ``[0, 1]`` or uint8: random shift, four convolutions
    and ``SimNorm``. The latent has ``num_channels * 16`` features, 512 by default."""
    return nn.Sequential(
        ShiftAug(),
        _Center(),
        nn.Conv2d(in_channels, num_channels, 7, stride=2),
        nn.ReLU(),
        nn.Conv2d(num_channels, num_channels, 5, stride=2),
        nn.ReLU(),
        nn.Conv2d(num_channels, num_channels, 3, stride=2),
        nn.ReLU(),
        nn.Conv2d(num_channels, num_channels, 3, stride=1),
        nn.Flatten(),
        SimNorm(simnorm_dim),
    )

class SimNorm ​

torch_world.models.tdmpc.SimNorm GitHub

python
SimNorm(dim: int = 8)

Simplicial normalization: a softmax over each group of dim features.

Lavoie et al., "Simplicial Embeddings in Self-Supervised Learning and Downstream Classification", ICLR 2023. Paper: https://arxiv.org/abs/2204.00616

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
class SimNorm(nn.Module):
    """Simplicial normalization: a softmax over each group of ``dim`` features.

    Lavoie et al., "Simplicial Embeddings in Self-Supervised Learning and Downstream Classification", ICLR 2023.
    Paper: https://arxiv.org/abs/2204.00616
    """

    def __init__(self, dim: int = 8):
        super().__init__()
        self.dim = dim

    def forward(self, x: Tensor) -> Tensor:
        return x.unflatten(-1, (-1, self.dim)).softmax(-1).flatten(-2)

class ShiftAug ​

torch_world.models.tdmpc.ShiftAug GitHub

python
ShiftAug(pad: int = 3)

Random shift of square images by up to pad pixels, with replicated borders (DrQ-v2).

As in TD-MPC2's reference code, the shift is applied in eval mode too.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
class ShiftAug(nn.Module):
    """Random shift of square images by up to ``pad`` pixels, with replicated borders (DrQ-v2).

    As in TD-MPC2's reference code, the shift is applied in eval mode too.
    """

    def __init__(self, pad: int = 3):
        super().__init__()
        self.pad = pad

    def forward(self, x: Tensor) -> Tensor:
        n, _, h, w = x.shape
        if h != w:
            raise ValueError(f"ShiftAug expects square images, got {h}x{w}")
        x = F.pad(x, (self.pad,) * 4, mode="replicate")
        eps = 1.0 / (h + 2 * self.pad)
        arange = torch.linspace(-1.0 + eps, 1.0 - eps, h + 2 * self.pad, device=x.device, dtype=x.dtype)[:h]
        arange = arange[None].expand(h, -1)
        base = torch.stack([arange, arange.T], dim=-1)[None].expand(n, -1, -1, -1)
        shift = torch.randint(0, 2 * self.pad + 1, (n, 1, 1, 2), device=x.device).to(x.dtype)
        return F.grid_sample(x, base + shift * 2.0 / (h + 2 * self.pad), padding_mode="zeros", align_corners=False)

function mlp ​

torch_world.models.tdmpc.mlp GitHub

python
mlp(
    dims: list[int], act: nn.Module | None = None, dropout: float = 0.0
) -> nn.Sequential

TD-MPC2's MLP through dims: Linear, LayerNorm and Mish per hidden layer, with dropout after the first linear only. The output layer is a plain Linear, or Linear, LayerNorm and act when act is given.

Source code in torch_world/models/tdmpc/_tdmpc2.py
python
def mlp(dims: list[int], act: nn.Module | None = None, dropout: float = 0.0) -> nn.Sequential:
    """TD-MPC2's MLP through ``dims``: Linear, LayerNorm and Mish per hidden layer, with dropout after the first
    linear only. The output layer is a plain Linear, or Linear, LayerNorm and ``act`` when ``act`` is given."""

    def normed(a: int, b: int, fn: nn.Module, p: float) -> nn.Sequential:
        return nn.Sequential(nn.Linear(a, b), *([nn.Dropout(p)] if p else []), nn.LayerNorm(b), fn)

    layers = [normed(a, b, nn.Mish(), dropout if i == 0 else 0.0) for i, (a, b) in enumerate(pairwise(dims[:-1]))]
    layers.append(normed(dims[-2], dims[-1], act, 0.0) if act else nn.Linear(dims[-2], dims[-1]))
    return nn.Sequential(*layers)