torch_world.nn
INFO
このページはまだ翻訳されていません。 英語版を読む
Encoders
class CLSEncoder
CLSEncoder(
img_size: int,
patch_size: int,
embed_dim: int = 192,
depth: int = 6,
num_heads: int = 3,
resize: bool = False,
**kwargs,
)A ViT whose CLS token embeds each image: (N, C, H, W) to (N, embed_dim).
With resize, inputs of any size are resized to img_size first, as for the local crops of multi-crop training. Other keyword arguments go to VisionTransformer.
Source code in torch_world/nn/encoders.py
class CLSEncoder(nn.Module):
"""A ViT whose CLS token embeds each image: ``(N, C, H, W)`` to ``(N, embed_dim)``.
With ``resize``, inputs of any size are resized to ``img_size`` first, as for the local crops of multi-crop
training. Other keyword arguments go to ``VisionTransformer``.
"""
def __init__(
self,
img_size: int,
patch_size: int,
embed_dim: int = 192,
depth: int = 6,
num_heads: int = 3,
resize: bool = False,
**kwargs,
):
super().__init__()
self.img_size, self.resize, self.embed_dim = img_size, resize, embed_dim
self.vit = VisionTransformer(
img_size, patch_size, embed_dim=embed_dim, depth=depth, num_heads=num_heads, cls_token=True, **kwargs
)
def forward(self, x: Tensor) -> Tensor:
if self.resize and x.shape[-1] != self.img_size:
x = F.interpolate(x, size=self.img_size, mode="bilinear")
return self.vit(x)[:, 0]class PixelPatches
PixelPatches(patch_size: int, channels: int = 3)Raw pixel patches as tokens: (N, C, H, W) to (N, H/p * W/p, C * p * p), with no parameters.
A fast, self-contained stand-in for a frozen pre-trained encoder such as DINOv2 or V-JEPA. Because the features are pixels, unpatchify turns predicted tokens back into images.
Source code in torch_world/nn/encoders.py
class PixelPatches(nn.Module):
"""Raw pixel patches as tokens: ``(N, C, H, W)`` to ``(N, H/p * W/p, C * p * p)``, with no parameters.
A fast, self-contained stand-in for a frozen pre-trained encoder such as DINOv2 or V-JEPA. Because the features
are pixels, ``unpatchify`` turns predicted tokens back into images.
"""
def __init__(self, patch_size: int, channels: int = 3):
super().__init__()
self.patch_size, self.dim = patch_size, channels * patch_size**2
def forward(self, x: Tensor) -> Tensor:
return F.pixel_unshuffle(x, self.patch_size).flatten(2).transpose(1, 2)
def unpatchify(self, tokens: Tensor, grid: tuple[int, int]) -> Tensor:
"""Tokens ``(..., P, C * p * p)`` on a ``grid`` of patches back to images ``(..., C, H, W)``."""
x = tokens[..., : self.dim].transpose(-1, -2).unflatten(-1, grid)
return F.pixel_shuffle(x.flatten(0, -4), self.patch_size).unflatten(0, tokens.shape[:-2])method unpatchify
unpatchify(tokens: Tensor, grid: tuple[int, int]) -> TensorTokens (..., P, C * p * p) on a grid of patches back to images (..., C, H, W).
Source code in torch_world/nn/encoders.py
def unpatchify(self, tokens: Tensor, grid: tuple[int, int]) -> Tensor:
"""Tokens ``(..., P, C * p * p)`` on a ``grid`` of patches back to images ``(..., C, H, W)``."""
x = tokens[..., : self.dim].transpose(-1, -2).unflatten(-1, grid)
return F.pixel_shuffle(x.flatten(0, -4), self.patch_size).unflatten(0, tokens.shape[:-2])class PatchTokens
PatchTokens(
model: nn.Module, size: int | None = None, normalize: bool = False
)Wraps a DINOv2 model to return its normalized patch tokens (N, P, D).
Inputs are float images in [0, 1] or uint8 images. size resizes them first, and normalize applies the ImageNet mean and standard deviation that DINOv2 expects. PatchTokens.from_hub loads a released model.
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
Source code in torch_world/nn/encoders.py
class PatchTokens(nn.Module):
"""Wraps a DINOv2 model to return its normalized patch tokens ``(N, P, D)``.
Inputs are float images in ``[0, 1]`` or uint8 images. ``size`` resizes them first, and ``normalize`` applies the
ImageNet mean and standard deviation that DINOv2 expects. ``PatchTokens.from_hub`` loads a released model.
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
"""
def __init__(self, model: nn.Module, size: int | None = None, normalize: bool = False):
super().__init__()
self.model = model
self.size, self.normalize = size, normalize
self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406])[:, None, None], persistent=False)
self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225])[:, None, None], persistent=False)
@classmethod
def from_hub(cls, name: str = "dinov2_vits14", size: int | None = 224) -> "PatchTokens":
"""A frozen, normalized released DINOv2 (``dinov2_vits14``, ``_vitb14``, ``_vitl14`` or ``_vitg14``)."""
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="xFormers")
model = torch.hub.load("facebookresearch/dinov2", name, verbose=False)
return cls(model, size=size, normalize=True).requires_grad_(False).eval()
@property
def dim(self) -> int:
return self.model.embed_dim
def forward(self, x: Tensor) -> Tensor:
x = x.float() / 255 if x.dtype == torch.uint8 else x
if self.size is not None:
x = F.interpolate(x, size=self.size, mode="bilinear", antialias=True)
if self.normalize:
x = (x - self.mean) / self.std
return self.model.forward_features(x)["x_norm_patchtokens"]method from_hub
from_hub(
name: str = "dinov2_vits14", size: int | None = 224
) -> PatchTokensA frozen, normalized released DINOv2 (dinov2_vits14, _vitb14, _vitl14 or _vitg14).
Source code in torch_world/nn/encoders.py
@classmethod
def from_hub(cls, name: str = "dinov2_vits14", size: int | None = 224) -> "PatchTokens":
"""A frozen, normalized released DINOv2 (``dinov2_vits14``, ``_vitb14``, ``_vitl14`` or ``_vitg14``)."""
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="xFormers")
model = torch.hub.load("facebookresearch/dinov2", name, verbose=False)
return cls(model, size=size, normalize=True).requires_grad_(False).eval()class VideoTokens
VideoTokens(
model: nn.Module,
size: int | None = None,
normalize: bool = False,
frames: int = 2,
)Wraps a V-JEPA 2 or 2.1 video encoder to return the patch tokens (N, P, D) of single images.
Each image is repeated over one tubelet (frames frames) so that the video encoder sees a still clip. Inputs and size and normalize are as in PatchTokens. VideoTokens.from_hub loads a released model.
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/nn/encoders.py
class VideoTokens(PatchTokens):
"""Wraps a V-JEPA 2 or 2.1 video encoder to return the patch tokens ``(N, P, D)`` of single images.
Each image is repeated over one tubelet (``frames`` frames) so that the video encoder sees a still clip. Inputs and
``size`` and ``normalize`` are as in ``PatchTokens``. ``VideoTokens.from_hub`` loads a released model.
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, model: nn.Module, size: int | None = None, normalize: bool = False, frames: int = 2):
super().__init__(model, size, normalize)
self.frames = frames
@classmethod
def from_hub(cls, name: str = "vjepa2_1_vit_base_384", size: int | None = 384) -> "VideoTokens":
"""A frozen, normalized released encoder: ``vjepa2_vit_large`` and up, or ``vjepa2_1_vit_base_384`` and up.
Needs ``timm`` and ``einops``, which the hub code imports.
"""
encoder = torch.hub.load("facebookresearch/vjepa2", name, verbose=False)[0]
return cls(encoder, size=size, normalize=True).requires_grad_(False).eval()
def forward(self, x: Tensor) -> Tensor:
x = x.float() / 255 if x.dtype == torch.uint8 else x
if self.size is not None:
x = F.interpolate(x, size=self.size, mode="bilinear", antialias=True)
if self.normalize:
x = (x - self.mean) / self.std
return self.model(x[:, :, None].expand(-1, -1, self.frames, -1, -1))method from_hub
from_hub(
name: str = "vjepa2_1_vit_base_384", size: int | None = 384
) -> VideoTokensA frozen, normalized released encoder: vjepa2_vit_large and up, or vjepa2_1_vit_base_384 and up.
Needs timm and einops, which the hub code imports.
Source code in torch_world/nn/encoders.py
@classmethod
def from_hub(cls, name: str = "vjepa2_1_vit_base_384", size: int | None = 384) -> "VideoTokens":
"""A frozen, normalized released encoder: ``vjepa2_vit_large`` and up, or ``vjepa2_1_vit_base_384`` and up.
Needs ``timm`` and ``einops``, which the hub code imports.
"""
encoder = torch.hub.load("facebookresearch/vjepa2", name, verbose=False)[0]
return cls(encoder, size=size, normalize=True).requires_grad_(False).eval()class TextEncoder
TextEncoder(
vocab_size: int, dim: int = 128, depth: int = 2, num_heads: int = 4
)Token embedding, a bidirectional transformer and mean pooling over non-padding tokens: (B, dim).
A small stand-in for a pretrained text encoder such as the EmbeddingGemma Y-encoder of VL-JEPA.
Source code in torch_world/nn/text.py
class TextEncoder(nn.Module):
"""Token embedding, a bidirectional transformer and mean pooling over non-padding tokens: ``(B, dim)``.
A small stand-in for a pretrained text encoder such as the EmbeddingGemma Y-encoder of VL-JEPA.
"""
def __init__(self, vocab_size: int, dim: int = 128, depth: int = 2, num_heads: int = 4):
super().__init__()
self.embed = nn.Embedding(vocab_size, dim)
self.transformer = Transformer(dim, depth, num_heads)
def forward(self, ids: Tensor, mask: Tensor) -> Tensor:
h = self.transformer(self.embed(ids), attn_mask=mask[:, None, None, :])
return (h * mask[..., None]).sum(1) / mask.sum(1, keepdim=True)class WordTokenizer
WordTokenizer(texts: list[str], device=None)Whitespace tokenizer over a fixed vocabulary, for small closed-vocabulary text such as templated QA.
Id 0 is padding. tokenizer(texts) returns (ids, mask) of shape (B, L), padded to the longest text. With a pretrained text model, use its own tokenizer instead.
Source code in torch_world/nn/text.py
class WordTokenizer:
"""Whitespace tokenizer over a fixed vocabulary, for small closed-vocabulary text such as templated QA.
Id 0 is padding. ``tokenizer(texts)`` returns ``(ids, mask)`` of shape ``(B, L)``, padded to the longest text.
With a pretrained text model, use its own tokenizer instead.
"""
def __init__(self, texts: list[str], device=None):
self.vocabulary = ["<pad>"] + sorted({w for t in texts for w in t.split()})
self.index = {w: i for i, w in enumerate(self.vocabulary)}
self.device = device
def __len__(self) -> int:
return len(self.vocabulary)
def __call__(self, texts: list[str]) -> tuple[Tensor, Tensor]:
ids = [[self.index[w] for w in t.split()] for t in texts]
n = max(map(len, ids))
ids = torch.tensor([t + [0] * (n - len(t)) for t in ids], device=self.device)
return ids, ids != 0
def to(self, device) -> "WordTokenizer":
self.device = device
return selfVideo autoencoders
class VideoVAE
VideoVAE(
vae: nn.Module, mean, std, spatial_ratio: int, temporal_ratio: int
)Frozen pre-trained causal video VAE from diffusers, with latents normalized per channel.
VideoVAE.from_pretrained() loads the Wan 2.1 VAE that DreamZero builds on (spatial_ratio = 8, temporal_ratio = 4, 16 channels). Clips need 1 + 4 n frames. Requires pip install torch-world[wam].
Source code in torch_world/nn/video_vae.py
class VideoVAE(nn.Module):
"""Frozen pre-trained causal video VAE from ``diffusers``, with latents normalized per channel.
``VideoVAE.from_pretrained()`` loads the Wan 2.1 VAE that DreamZero builds on (``spatial_ratio = 8``,
``temporal_ratio = 4``, 16 channels). Clips need ``1 + 4 n`` frames. Requires ``pip install torch-world[wam]``.
"""
def __init__(self, vae: nn.Module, mean, std, spatial_ratio: int, temporal_ratio: int):
super().__init__()
self.vae = vae.eval().requires_grad_(False)
self.latent_channels = len(mean)
self.spatial_ratio, self.temporal_ratio = spatial_ratio, temporal_ratio
self.register_buffer("mean", torch.as_tensor(mean, dtype=torch.float32)[:, None, None])
self.register_buffer("std", torch.as_tensor(std, dtype=torch.float32)[:, None, None])
@classmethod
def from_pretrained(
cls, name: str = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", subfolder: str = "vae", **kwargs
) -> "VideoVAE":
from diffusers import AutoencoderKLWan
vae = AutoencoderKLWan.from_pretrained(name, subfolder=subfolder, **kwargs)
config = vae.config
return cls(
vae,
config.latents_mean,
config.latents_std,
2 ** len(config.temperal_downsample),
2 ** sum(config.temperal_downsample),
)
def train(self, mode: bool = True):
super().train(mode)
self.vae.eval()
return self
@torch.no_grad()
def encode(self, pixels: Tensor) -> Tensor:
if (pixels.size(1) - 1) % self.temporal_ratio:
raise ValueError(f"Clips need 1 + {self.temporal_ratio} n frames")
x = (pixels * 2 - 1).transpose(1, 2).to(self.vae.dtype)
latents = self.vae.encode(x).latent_dist.mode().transpose(1, 2).float()
return (latents - self.mean) / self.std
@torch.no_grad()
def decode(self, latents: Tensor) -> Tensor:
x = (latents * self.std + self.mean).transpose(1, 2).to(self.vae.dtype)
return ((self.vae.decode(x).sample.transpose(1, 2).float() + 1) / 2).clamp(0, 1)class ConvVideoAE
ConvVideoAE(latent_channels: int = 8, width: int = 32, depth: int = 2)Small trainable per-frame convolutional autoencoder, a download-free stand-in for VideoVAE.
Each of depth stages halves the resolution, so spatial_ratio = 2 ** depth and temporal_ratio = 1. forward(pixels) returns the reconstruction loss.
Source code in torch_world/nn/video_vae.py
class ConvVideoAE(nn.Module):
"""Small trainable per-frame convolutional autoencoder, a download-free stand-in for ``VideoVAE``.
Each of ``depth`` stages halves the resolution, so ``spatial_ratio = 2 ** depth`` and ``temporal_ratio = 1``.
``forward(pixels)`` returns the reconstruction loss.
"""
temporal_ratio = 1
def __init__(self, latent_channels: int = 8, width: int = 32, depth: int = 2):
super().__init__()
self.latent_channels, self.spatial_ratio = latent_channels, 2**depth
down, up, c = [], [], 3
for i in range(depth):
out = width * 2**i
down += [nn.Conv2d(c, out, 4, stride=2, padding=1), nn.GroupNorm(8, out), nn.SiLU()]
c = out
down.append(nn.Conv2d(c, latent_channels, 3, padding=1))
up.append(nn.Conv2d(latent_channels, c, 3, padding=1))
for i in reversed(range(depth)):
out = width * 2 ** max(i - 1, 0)
up += [nn.GroupNorm(8, c), nn.SiLU(), nn.ConvTranspose2d(c, out, 4, stride=2, padding=1)]
c = out
up.append(nn.Conv2d(c, 3, 3, padding=1))
self.encoder, self.decoder = nn.Sequential(*down), nn.Sequential(*up)
def encode(self, pixels: Tensor) -> Tensor:
return self.encoder(pixels.flatten(0, 1) * 2 - 1).unflatten(0, pixels.shape[:2])
def decode(self, latents: Tensor) -> Tensor:
return (self.decoder(latents.flatten(0, 1)).unflatten(0, latents.shape[:2]) + 1) / 2
def forward(self, pixels: Tensor) -> dict[str, Tensor]:
loss = F.mse_loss(self.decode(self.encode(pixels)), pixels)
return {"loss": loss, "reconstruction_loss": loss}Transformers
class VisionTransformer
VisionTransformer(
img_size: int | tuple[int, int] = 224,
patch_size: int = 16,
in_chans: int = 3,
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
mlp_ratio: float = 4.0,
qkv_bias: bool = True,
drop_path: float = 0.0,
num_frames: int = 1,
tubelet_size: int = 2,
cls_token: bool = False,
use_rope: bool = False,
init_std: float = 0.02,
)ViT for images or videos (num_frames > 1 uses tubelet_size frames per token).
Positions are fixed sin-cos embeddings, or 2D/3D RoPE when use_rope. With RoPE, positions come from the input's own grid, so the encoder reads frames of any size. forward takes optional index masks and then encodes only the kept tokens, as JEPA context encoders do.
Members
| Member | Description |
|---|---|
from_size | Build a standard ViT: tiny, small, base, large, huge or giant. |
embed | Patch tokens (B, N, D) of x with their positions added, and their grid coordinates (N, A). |
Source code in torch_world/nn/vision_transformer.py
class VisionTransformer(nn.Module):
"""ViT for images or videos (``num_frames > 1`` uses ``tubelet_size`` frames per token).
Positions are fixed sin-cos embeddings, or 2D/3D RoPE when ``use_rope``. With RoPE, positions come from the
input's own grid, so the encoder reads frames of any size. ``forward`` takes optional index masks and then encodes
only the kept tokens, as JEPA context encoders do.
"""
def __init__(
self,
img_size: int | tuple[int, int] = 224,
patch_size: int = 16,
in_chans: int = 3,
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
mlp_ratio: float = 4.0,
qkv_bias: bool = True,
drop_path: float = 0.0,
num_frames: int = 1,
tubelet_size: int = 2,
cls_token: bool = False,
use_rope: bool = False,
init_std: float = 0.02,
):
super().__init__()
h, w = (s // patch_size for s in _pair(img_size))
video = num_frames > 1
self.grid = (num_frames // tubelet_size, h, w) if video else (h, w)
self.embed_dim = embed_dim
self.use_rope = use_rope
self.patch_embed = PatchEmbed(patch_size, in_chans, embed_dim, tubelet_size if video else None)
pos_embed = torch.zeros(len(grid_coords(self.grid)), embed_dim) if use_rope else sincos(embed_dim, self.grid)
self.register_buffer("pos_embed", pos_embed[None], persistent=False)
self.register_buffer("coords", grid_coords(self.grid), persistent=False)
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if cls_token else None
self.transformer = Transformer(
embed_dim,
depth,
num_heads,
drop_path,
mlp_dim=int(embed_dim * mlp_ratio),
qkv_bias=qkv_bias,
use_rope=use_rope,
)
init_weights(self, init_std)
rescale_blocks(self.transformer.blocks)
@classmethod
def from_size(cls, size: str, **kwargs) -> "VisionTransformer":
"""Build a standard ViT: ``tiny``, ``small``, ``base``, ``large``, ``huge`` or ``giant``."""
embed_dim, depth, num_heads = VIT_SIZES[size]
return cls(embed_dim=embed_dim, depth=depth, num_heads=num_heads, **kwargs)
@property
def num_patches(self) -> int:
return self.pos_embed.size(1)
def embed(self, x: Tensor) -> tuple[Tensor, Tensor]:
"""Patch tokens ``(B, N, D)`` of ``x`` with their positions added, and their grid coordinates ``(N, A)``."""
grid = tuple(s // k for s, k in zip(x.shape[2:], self.patch_embed.proj.kernel_size))
x = self.patch_embed(x)
if self.use_rope and grid != self.grid:
return x, grid_coords(grid).to(x.device)
return x + self.pos_embed[:, : x.size(1)], self.coords[: x.size(1)]
def forward(self, x: Tensor, masks: list[Tensor] | None = None) -> Tensor:
x, coords = self.embed(x)
B, pos = x.size(0), 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(B, -1, -1), masks)
if self.cls_token is not None:
x = torch.cat([self.cls_token.expand(x.size(0), -1, -1), x], dim=1)
if pos is not None:
pos = torch.cat([pos.new_zeros(pos.shape[:-2] + (1, pos.size(-1))), pos], dim=-2)
return self.transformer(x, pos=pos)method from_size
from_size(size: str, **kwargs) -> VisionTransformerBuild a standard ViT: tiny, small, base, large, huge or giant.
Source code in torch_world/nn/vision_transformer.py
@classmethod
def from_size(cls, size: str, **kwargs) -> "VisionTransformer":
"""Build a standard ViT: ``tiny``, ``small``, ``base``, ``large``, ``huge`` or ``giant``."""
embed_dim, depth, num_heads = VIT_SIZES[size]
return cls(embed_dim=embed_dim, depth=depth, num_heads=num_heads, **kwargs)method embed
embed(x: Tensor) -> tuple[Tensor, Tensor]Patch tokens (B, N, D) of x with their positions added, and their grid coordinates (N, A).
Source code in torch_world/nn/vision_transformer.py
def embed(self, x: Tensor) -> tuple[Tensor, Tensor]:
"""Patch tokens ``(B, N, D)`` of ``x`` with their positions added, and their grid coordinates ``(N, A)``."""
grid = tuple(s // k for s, k in zip(x.shape[2:], self.patch_embed.proj.kernel_size))
x = self.patch_embed(x)
if self.use_rope and grid != self.grid:
return x, grid_coords(grid).to(x.device)
return x + self.pos_embed[:, : x.size(1)], self.coords[: x.size(1)]class PatchEmbed
PatchEmbed(
patch_size: int = 16,
in_chans: int = 3,
embed_dim: int = 768,
tubelet_size: int | None = None,
)Images (B, C, H, W) or videos (B, C, T, H, W) to patch tokens (B, N, D).
Source code in torch_world/nn/vision_transformer.py
class PatchEmbed(nn.Module):
"""Images ``(B, C, H, W)`` or videos ``(B, C, T, H, W)`` to patch tokens ``(B, N, D)``."""
def __init__(self, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, tubelet_size: int | None = None):
super().__init__()
if tubelet_size is None:
self.proj = nn.Conv2d(in_chans, embed_dim, patch_size, patch_size)
else:
kernel = (tubelet_size, patch_size, patch_size)
self.proj = nn.Conv3d(in_chans, embed_dim, kernel, kernel)
def forward(self, x: Tensor) -> Tensor:
return self.proj(x).flatten(2).transpose(1, 2)class MaskedPredictor
MaskedPredictor(
grid: tuple[int, ...],
embed_dim: int,
predictor_dim: int = 384,
depth: int = 6,
num_heads: int = 12,
mlp_ratio: float = 4.0,
qkv_bias: bool = True,
drop_path: float = 0.0,
num_mask_tokens: int = 1,
zero_init_mask_tokens: bool = False,
use_rope: bool = False,
init_std: float = 0.02,
)JEPA predictor: from context tokens, predict target tokens at masked positions of a patch grid.
Each target position is a learnable mask token plus its position. num_mask_tokens holds one token per masking strategy, as in V-JEPA.
Source code in torch_world/nn/predictor.py
class MaskedPredictor(nn.Module):
"""JEPA predictor: from context tokens, predict target tokens at masked positions of a patch grid.
Each target position is a learnable mask token plus its position. ``num_mask_tokens`` holds one token
per masking strategy, as in V-JEPA.
"""
def __init__(
self,
grid: tuple[int, ...],
embed_dim: int,
predictor_dim: int = 384,
depth: int = 6,
num_heads: int = 12,
mlp_ratio: float = 4.0,
qkv_bias: bool = True,
drop_path: float = 0.0,
num_mask_tokens: int = 1,
zero_init_mask_tokens: bool = False,
use_rope: bool = False,
init_std: float = 0.02,
):
super().__init__()
self.use_rope = use_rope
self.embed = nn.Linear(embed_dim, predictor_dim)
self.mask_tokens = nn.Parameter(torch.zeros(num_mask_tokens, 1, 1, predictor_dim))
pos_embed = torch.zeros(len(grid_coords(grid)), predictor_dim) if use_rope else sincos(predictor_dim, grid)
self.register_buffer("pos_embed", pos_embed[None], persistent=False)
self.register_buffer("coords", grid_coords(grid), persistent=False)
self.transformer = Transformer(
predictor_dim,
depth,
num_heads,
drop_path,
mlp_dim=int(predictor_dim * mlp_ratio),
qkv_bias=qkv_bias,
use_rope=use_rope,
)
self.proj = nn.Linear(predictor_dim, embed_dim)
init_weights(self, init_std)
rescale_blocks(self.transformer.blocks)
if not zero_init_mask_tokens:
nn.init.trunc_normal_(self.mask_tokens, std=init_std)
def forward(self, x: Tensor, masks_x: list[Tensor], masks_y: list[Tensor], mask_index: int = 0) -> Tensor:
"""``x`` is ``(len(masks_x) * B, Nx, D)``; returns ``(len(masks_y) * len(masks_x) * B, Ny, D)``."""
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)
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)
return self.proj(self.transformer(x, pos=pos)[:, n:])method forward
forward(
x: Tensor, masks_x: list[Tensor], masks_y: list[Tensor], mask_index: int = 0
) -> Tensorx is (len(masks_x) * B, Nx, D); returns (len(masks_y) * len(masks_x) * B, Ny, D).
Source code in torch_world/nn/predictor.py
def forward(self, x: Tensor, masks_x: list[Tensor], masks_y: list[Tensor], mask_index: int = 0) -> Tensor:
"""``x`` is ``(len(masks_x) * B, Nx, D)``; returns ``(len(masks_y) * len(masks_x) * B, Ny, D)``."""
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)
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)
return self.proj(self.transformer(x, pos=pos)[:, n:])class Transformer
Transformer(
dim: int,
depth: int,
num_heads: int,
drop_path: float = 0.0,
conditional: bool = False,
**kwargs,
)Stack of Block (or AdaLNBlock when conditional) followed by a final layer norm.
Source code in torch_world/nn/transformer.py
class Transformer(nn.Module):
"""Stack of ``Block`` (or ``AdaLNBlock`` when ``conditional``) followed by a final layer norm."""
def __init__(
self, dim: int, depth: int, num_heads: int, drop_path: float = 0.0, conditional: bool = False, **kwargs
):
super().__init__()
block = AdaLNBlock if conditional else Block
rates = torch.linspace(0, drop_path, depth).tolist()
self.blocks = nn.ModuleList(block(dim, num_heads, drop_path=r, **kwargs) for r in rates)
self.norm = LayerNorm(dim)
def forward(self, x: Tensor, c: Tensor | None = None, **kwargs) -> Tensor:
for block in self.blocks:
x = block(x, **kwargs) if c is None else block(x, c, **kwargs)
return self.norm(x)class Block
Block(
dim: int,
num_heads: int,
mlp_dim: int | None = None,
head_dim: int | None = None,
qkv_bias: bool = True,
dropout: float = 0.0,
drop_path: float = 0.0,
use_rope: bool = False,
act: Callable[[], nn.Module] = nn.GELU,
)Pre-norm transformer block.
Source code in torch_world/nn/transformer.py
class Block(nn.Module):
"""Pre-norm transformer block."""
def __init__(
self,
dim: int,
num_heads: int,
mlp_dim: int | None = None,
head_dim: int | None = None,
qkv_bias: bool = True,
dropout: float = 0.0,
drop_path: float = 0.0,
use_rope: bool = False,
act: Callable[[], nn.Module] = nn.GELU,
):
super().__init__()
self.norm1 = LayerNorm(dim)
self.attn = Attention(dim, num_heads, head_dim, qkv_bias, dropout, use_rope)
self.norm2 = LayerNorm(dim)
self.mlp = MLP([dim, mlp_dim or 4 * dim, dim], act=act, dropout=dropout)
self.drop_path = DropPath(drop_path)
def forward(self, x: Tensor, attn_mask: Tensor | None = None, pos: Tensor | None = None, is_causal: bool = False):
x = x + self.drop_path(self.attn(self.norm1(x), attn_mask, pos, is_causal))
return x + self.drop_path(self.mlp(self.norm2(x)))class AdaLNBlock
AdaLNBlock(dim: int, num_heads: int, **kwargs)Transformer block conditioned by adaptive layer norm with zero-initialized gates.
Peebles & Xie, "Scalable Diffusion Models with Transformers", ICCV 2023. Paper: https://arxiv.org/abs/2212.09748
Source code in torch_world/nn/transformer.py
class AdaLNBlock(Block):
"""Transformer block conditioned by adaptive layer norm with zero-initialized gates.
Peebles & Xie, "Scalable Diffusion Models with Transformers", ICCV 2023.
Paper: https://arxiv.org/abs/2212.09748
"""
def __init__(self, dim: int, num_heads: int, **kwargs):
super().__init__(dim, num_heads, **kwargs)
self.norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
self.modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim))
nn.init.zeros_(self.modulation[-1].weight)
nn.init.zeros_(self.modulation[-1].bias)
def forward(
self, x: Tensor, c: Tensor, attn_mask: Tensor | None = None, pos: Tensor | None = None, is_causal: bool = False
):
shift1, scale1, gate1, shift2, scale2, gate2 = self.modulation(c).chunk(6, dim=-1)
x = x + gate1 * self.drop_path(self.attn(self.norm1(x) * (1 + scale1) + shift1, attn_mask, pos, is_causal))
return x + gate2 * self.drop_path(self.mlp(self.norm2(x) * (1 + scale2) + shift2))class Attention
Attention(
dim: int,
num_heads: int = 8,
head_dim: int | None = None,
qkv_bias: bool = True,
dropout: float = 0.0,
use_rope: bool = False,
)Multi-head self-attention on F.scaled_dot_product_attention with optional rotary positions.
Source code in torch_world/nn/attention.py
class Attention(nn.Module):
"""Multi-head self-attention on ``F.scaled_dot_product_attention`` with optional rotary positions."""
def __init__(
self,
dim: int,
num_heads: int = 8,
head_dim: int | None = None,
qkv_bias: bool = True,
dropout: float = 0.0,
use_rope: bool = False,
):
super().__init__()
self.num_heads = num_heads
self.head_dim = head_dim or dim // num_heads
self.dropout = dropout
self.use_rope = use_rope
inner = self.num_heads * self.head_dim
self.qkv = nn.Linear(dim, 3 * inner, bias=qkv_bias)
self.proj = nn.Linear(inner, dim)
def forward(
self,
x: Tensor,
attn_mask: Tensor | None = None,
pos: Tensor | None = None,
is_causal: bool = False,
) -> Tensor:
"""``attn_mask`` is boolean (``True`` attends), additive, or a FlexAttention ``BlockMask``.
``pos`` holds RoPE coordinates ``(N, A)`` or ``(B, N, A)``.
"""
B, N, _ = x.shape
q, k, v = self.qkv(x).view(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
if self.use_rope:
pos = pos[:, None] if pos.dim() == 3 else pos
q, k = rope(q, pos), rope(k, pos)
if attn_mask is not None and not isinstance(attn_mask, Tensor):
x = flex_attention(q, k, v, attn_mask)
else:
x = F.scaled_dot_product_attention(
q, k, v, attn_mask=attn_mask, dropout_p=self.dropout if self.training else 0.0, is_causal=is_causal
)
return self.proj(x.transpose(1, 2).reshape(B, N, -1))method forward
forward(
x: Tensor,
attn_mask: Tensor | None = None,
pos: Tensor | None = None,
is_causal: bool = False,
) -> Tensorattn_mask is boolean (True attends), additive, or a FlexAttention BlockMask.
pos holds RoPE coordinates (N, A) or (B, N, A).
Source code in torch_world/nn/attention.py
def forward(
self,
x: Tensor,
attn_mask: Tensor | None = None,
pos: Tensor | None = None,
is_causal: bool = False,
) -> Tensor:
"""``attn_mask`` is boolean (``True`` attends), additive, or a FlexAttention ``BlockMask``.
``pos`` holds RoPE coordinates ``(N, A)`` or ``(B, N, A)``.
"""
B, N, _ = x.shape
q, k, v = self.qkv(x).view(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
if self.use_rope:
pos = pos[:, None] if pos.dim() == 3 else pos
q, k = rope(q, pos), rope(k, pos)
if attn_mask is not None and not isinstance(attn_mask, Tensor):
x = flex_attention(q, k, v, attn_mask)
else:
x = F.scaled_dot_product_attention(
q, k, v, attn_mask=attn_mask, dropout_p=self.dropout if self.training else 0.0, is_causal=is_causal
)
return self.proj(x.transpose(1, 2).reshape(B, N, -1))class MLP
MLP(
dims: list[int],
norm: Callable[[int], nn.Module] | None = None,
act: Callable[[], nn.Module] = nn.GELU,
dropout: float = 0.0,
)Linear layers through dims with norm, act and dropout between them.
Source code in torch_world/nn/transformer.py
class MLP(nn.Sequential):
"""Linear layers through ``dims`` with ``norm``, ``act`` and dropout between them."""
def __init__(
self,
dims: list[int],
norm: Callable[[int], nn.Module] | None = None,
act: Callable[[], nn.Module] = nn.GELU,
dropout: float = 0.0,
):
layers = []
for i, (a, b) in enumerate(pairwise(dims)):
layers.append(nn.Linear(a, b))
if i < len(dims) - 2:
layers += [norm(b)] if norm else []
layers += [act(), nn.Dropout(dropout)] if dropout else [act()]
super().__init__(*layers)class DropPath
DropPath(p: float = 0.0)Source code in torch_world/nn/transformer.py
class DropPath(nn.Module):
def __init__(self, p: float = 0.0):
super().__init__()
self.p = p
def forward(self, x: Tensor) -> Tensor:
if not self.training or self.p == 0.0:
return x
keep = x.new_empty((x.size(0),) + (1,) * (x.dim() - 1)).bernoulli_(1 - self.p)
return x * keep / (1 - self.p)Positions
function sincos
sincos(dim: int, grid: tuple[int, ...]) -> TensorSource code in torch_world/nn/positional.py
def sincos(dim: int, grid: tuple[int, ...]) -> Tensor:
if len(grid) == 1:
return sincos_1d(dim, torch.arange(grid[0]))
return sincos_2d(dim, grid) if len(grid) == 2 else sincos_3d(dim, grid)function sincos_1d
sincos_1d(dim: int, pos: Tensor) -> TensorSource code in torch_world/nn/positional.py
def sincos_1d(dim: int, pos: Tensor) -> Tensor:
omega = 1.0 / 10000 ** (torch.arange(dim // 2, dtype=torch.float64) / (dim / 2))
out = pos.double()[..., None] * omega
return torch.cat([out.sin(), out.cos()], dim=-1).float()function sincos_2d
sincos_2d(dim: int, grid: tuple[int, int]) -> TensorFixed 2D sin-cos embedding of shape (H * W, dim), as in V-JEPA.
Source code in torch_world/nn/positional.py
def sincos_2d(dim: int, grid: tuple[int, int]) -> Tensor:
"""Fixed 2D sin-cos embedding of shape ``(H * W, dim)``, as in V-JEPA."""
rows, cols = torch.meshgrid(torch.arange(grid[0]), torch.arange(grid[1]), indexing="ij")
return torch.cat([sincos_1d(dim // 2, rows.flatten()), sincos_1d(dim // 2, cols.flatten())], dim=-1)function sincos_3d
sincos_3d(dim: int, grid: tuple[int, int, int]) -> TensorFixed 3D sin-cos embedding of shape (T * H * W, dim) with uniform power per axis, as in V-JEPA.
Source code in torch_world/nn/positional.py
def sincos_3d(dim: int, grid: tuple[int, int, int]) -> Tensor:
"""Fixed 3D sin-cos embedding of shape ``(T * H * W, dim)`` with uniform power per axis, as in V-JEPA."""
sub = 2 * math.ceil(dim / 6)
coords = torch.meshgrid(*(torch.arange(n) for n in grid), indexing="ij")
return torch.cat([sincos_1d(sub, c.flatten()) for c in coords], dim=-1)[:, :dim]function grid_coords
grid_coords(grid: tuple[int, ...]) -> TensorInteger coordinates of every cell of grid in row-major order, shape (prod(grid), len(grid)).
Source code in torch_world/nn/positional.py
def grid_coords(grid: tuple[int, ...]) -> Tensor:
"""Integer coordinates of every cell of ``grid`` in row-major order, shape ``(prod(grid), len(grid))``."""
coords = torch.meshgrid(*(torch.arange(n) for n in grid), indexing="ij")
return torch.stack([c.flatten() for c in coords], dim=-1).float()function rope
rope(x: Tensor, pos: Tensor) -> TensorRotary embedding over pos.size(-1) axes, each rotating an equal even slice of the last dim of x.
x is (..., N, D) and pos is (N, A) or broadcastable to (..., N, A). Dimensions left after A equal slices are not rotated.
Source code in torch_world/nn/positional.py
def rope(x: Tensor, pos: Tensor) -> Tensor:
"""Rotary embedding over ``pos.size(-1)`` axes, each rotating an equal even slice of the last dim of ``x``.
``x`` is ``(..., N, D)`` and ``pos`` is ``(N, A)`` or broadcastable to ``(..., N, A)``.
Dimensions left after ``A`` equal slices are not rotated.
"""
axes = pos.size(-1)
d = 2 * (x.size(-1) // axes // 2)
omega = 1.0 / 10000 ** (torch.arange(d // 2, device=x.device, dtype=torch.float32) / (d / 2))
parts = []
for i in range(axes):
xi = x[..., i * d : (i + 1) * d]
angle = (pos[..., i, None].float() * omega).repeat_interleave(2, dim=-1).to(x.dtype)
x1, x2 = xi.unflatten(-1, (-1, 2)).unbind(-1)
rotated = torch.stack((-x2, x1), dim=-1).flatten(-2)
parts.append(xi * angle.cos() + rotated * angle.sin())
return torch.cat(parts + [x[..., axes * d :]], dim=-1)Flow matching
function time_embedding
time_embedding(time: Tensor, dim: int) -> TensorSinusoidal embedding (B, dim) of flow times (B,).
Source code in torch_world/nn/flow.py
def time_embedding(time: Tensor, dim: int) -> Tensor:
"""Sinusoidal embedding ``(B, dim)`` of flow times ``(B,)``."""
frequency = torch.exp(-math.log(10000) * torch.arange(dim // 2, device=time.device) / (dim // 2))
phase = time[..., None] * frequency
return torch.cat((phase.sin(), phase.cos()), dim=-1)function interpolate
interpolate(noise: Tensor, target: Tensor, time: Tensor) -> TensorPoint at time on the straight path from noise to target; time broadcasts from the left.
Source code in torch_world/nn/flow.py
def interpolate(noise: Tensor, target: Tensor, time: Tensor) -> Tensor:
"""Point at ``time`` on the straight path from ``noise`` to ``target``; ``time`` broadcasts from the left."""
return torch.lerp(noise, target, time.reshape(time.shape + (1,) * (target.dim() - time.dim())))function velocity_target
velocity_target(noise: Tensor, target: Tensor) -> TensorConstant velocity of the straight path, the regression target of flow matching.
Source code in torch_world/nn/flow.py
def velocity_target(noise: Tensor, target: Tensor) -> Tensor:
"""Constant velocity of the straight path, the regression target of flow matching."""
return target - noisefunction sample_time
sample_time(
shape: tuple[int, ...] | int,
*,
device=None,
dtype=None,
generator: torch.Generator | None = None,
alpha: float | None = None,
logit_normal: tuple[float, float] | None = None,
) -> TensorTraining flow times in [0, 1]: U(0, 1) by default.
alpha draws 1 - Beta(alpha, 1); alpha > 1 concentrates times near noise, as DreamZero-Flash does for video (alpha = 7, mean 0.125). Beta(alpha, 1) is drawn by inverse CDF, U ** (1 / alpha), so it follows generator. logit_normal=(mean, std) draws sigmoid(N(mean, std)), which spends more training on intermediate times, as Stable Diffusion 3 does (Esser et al., 2024, https://arxiv.org/abs/2403.03206).
Source code in torch_world/nn/flow.py
def sample_time(
shape: tuple[int, ...] | int,
*,
device=None,
dtype=None,
generator: torch.Generator | None = None,
alpha: float | None = None,
logit_normal: tuple[float, float] | None = None,
) -> Tensor:
"""Training flow times in ``[0, 1]``: ``U(0, 1)`` by default.
``alpha`` draws ``1 - Beta(alpha, 1)``; ``alpha > 1`` concentrates times near noise, as DreamZero-Flash does for
video (``alpha = 7``, mean ``0.125``). ``Beta(alpha, 1)`` is drawn by inverse CDF, ``U ** (1 / alpha)``, so it
follows ``generator``. ``logit_normal=(mean, std)`` draws ``sigmoid(N(mean, std))``, which spends more training on
intermediate times, as Stable Diffusion 3 does (Esser et al., 2024, https://arxiv.org/abs/2403.03206).
"""
if logit_normal is not None:
if alpha is not None:
raise ValueError("Pass alpha or logit_normal, not both")
mean, std = logit_normal
return torch.sigmoid(mean + std * torch.randn(shape, device=device, dtype=dtype, generator=generator))
u = torch.rand(shape, device=device, dtype=dtype, generator=generator)
if alpha is None:
return u
if alpha <= 0:
raise ValueError("alpha must be positive")
return 1 - u ** (1 / alpha)function euler_sample
euler_sample(
velocity: Callable[[Tensor, Tensor], Tensor], noise: Tensor, steps: int
) -> TensorIntegrate dx/dt = velocity(x, t) from t = 0 to 1 in steps Euler steps; t is (B,).
Source code in torch_world/nn/flow.py
def euler_sample(velocity: Callable[[Tensor, Tensor], Tensor], noise: Tensor, steps: int) -> Tensor:
"""Integrate ``dx/dt = velocity(x, t)`` from ``t = 0`` to ``1`` in ``steps`` Euler steps; ``t`` is ``(B,)``."""
if steps < 1:
raise ValueError("steps must be positive")
x = noise
for i in range(steps):
x = x + velocity(x, x.new_full((x.size(0),), i / steps)) / steps
return xInitialization
function init_weights
init_weights(module: nn.Module, std: float = 0.02)Truncated-normal linear weights, zero biases and unit norms, as in the JEPA reference code.
Source code in torch_world/nn/transformer.py
def init_weights(module: nn.Module, std: float = 0.02):
"""Truncated-normal linear weights, zero biases and unit norms, as in the JEPA reference code."""
for m in module.modules():
if isinstance(m, nn.Linear):
nn.init.trunc_normal_(m.weight, std=std)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.LayerNorm) and m.elementwise_affine:
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)function rescale_blocks
rescale_blocks(blocks: nn.ModuleList)Divide residual output projections of layer i by sqrt(2 i).
Source code in torch_world/nn/transformer.py
def rescale_blocks(blocks: nn.ModuleList):
"""Divide residual output projections of layer ``i`` by ``sqrt(2 i)``."""
with torch.no_grad():
for i, block in enumerate(blocks, start=1):
block.attn.proj.weight.div_((2.0 * i) ** 0.5)
block.mlp[-1].weight.div_((2.0 * i) ** 0.5)