hyper88's picture
Research preview
ca6a1ef verified
Raw History Blame Contribute Delete
29.7 kB
#!/usr/bin/env python3
"""LingBot-World v2 1.3B (causal-fast) with an explicit context interface, for retrieval training.
LingBot's own code keeps a rolling KV cache inside the attention layers and writes it in
place, which is fine for inference but cannot be trained against. Here one call processes
one chunk of latent frames and receives the keys and values of its context frames as
arguments, so the context can be any set of frames: the sink, the most recent ones, and
frames retrieved by frustum overlap from anywhere in the past.
Weights and architecture are LingBot-World v2 (Robbyant, CC BY-NC-SA 4.0): anything trained
from them carries that licence. Parameter names match the released state dict.
What is new and trainable (`RetrievalAdapter`), all of it a no-op at initialisation:
* geometry-aware attention: every token gets an embedding of its viewing ray, expressed in
the camera frame of the chunk being generated; a per-layer projection adds it to the
queries and to the keys (after RoPE). Context frames are stored without it, so nothing
is recomputed when the camera moves: the offsets are added when a frame is loaded.
* LoRA on the self-attention projections.
"""
from __future__ import annotations
import math
import os
import sys
from dataclasses import dataclass
from typing import Dict, List, Optional, Sequence, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import infer_realtime as ir # noqa: E402
LB_CFG = dict(dim=1536, ffn_dim=8960, freq_dim=256, in_dim=36, out_dim=16, num_heads=12, num_layers=30, text_dim=4096, text_len=512)
# The four steps of the distilled sampler, read from LingBot's own scheduler (FlowUniPC, 1000 steps, shift 5,
# positions 0, 179, 358 and 679): the integer timestep the model is given and the noise level sigma,
# with x_t = (1 - sigma) x0 + sigma noise.
STEPS = ((999.0, 0.9997998476028442), (957.0, 0.9579927921295166), (899.0, 0.8994113802909851), (702.0, 0.7024067044258118))
def student_steps() -> List[Tuple[float, float]]:
return list(STEPS)
class LBBlock(ir.Block):
def __init__(self, cfg: ir.DiTConfig):
super().__init__(cfg)
d = cfg.dim
self.cam_injector_layer1, self.cam_injector_layer2 = nn.Linear(d, d), nn.Linear(d, d)
self.cam_scale_layer, self.cam_shift_layer = nn.Linear(d, d), nn.Linear(d, d)
@dataclass
class Geo:
"""Per-layer geometry terms of one chunk call (None = no geometry).
mode "offset": vectors added to queries and keys of every token (changes all attention, also within the chunk).
mode "bias": extra channels appended to the queries and to the context keys only, i.e. an additive attention
bias between a token of the chunk and a context token; attention within the chunk is left as it was.
"""
dq: torch.Tensor # [layers, B, H, L, d or r] for the chunk's queries
dk: Optional[torch.Tensor] # offset mode: [layers, B, H, L, d] added to the chunk's own keys
dk_ctx: Optional[torch.Tensor] # [layers, B, H, Lc, d or r] for the context keys
mode: str = "offset"
class LBDiT(nn.Module):
"""LingBot causal DiT: image-to-video input (16 latent + 4 mask + 16 conditioning channels) and camera injection."""
def __init__(self, cfg: Optional[ir.DiTConfig] = None):
super().__init__()
self.cfg = cfg = cfg or ir.DiTConfig(**LB_CFG)
d = cfg.dim
self.patch_embedding = nn.Conv3d(cfg.in_dim, d, kernel_size=cfg.patch, stride=cfg.patch)
self.patch_embedding_wancamctrl = nn.Linear(6 * 64 * math.prod(cfg.patch), d)
self.c2ws_hidden_states_layer1, self.c2ws_hidden_states_layer2 = nn.Linear(d, d), nn.Linear(d, d)
self.text_embedding = nn.Sequential(nn.Linear(cfg.text_dim, d), nn.GELU(approximate="tanh"), nn.Linear(d, d))
self.time_embedding = nn.Sequential(nn.Linear(cfg.freq_dim, d), nn.SiLU(), nn.Linear(d, d))
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(d, d * 6))
self.blocks = nn.ModuleList([LBBlock(cfg) for _ in range(cfg.num_layers)])
self.head = ir.Head(cfg)
# ---- conditioning --------------------------------------------------------
@torch.no_grad()
def text_cond(self, prompt_embeds: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""[B, n <= text_len, text_dim] -> cross-attention keys and values [layers, B, H, text_len, d]."""
b, n, _ = prompt_embeds.shape
ctx = F.pad(prompt_embeds, (0, 0, 0, self.cfg.text_len - n))
ctx = self.text_embedding(ctx.to(self.patch_embedding.weight.dtype))
ks, vs = zip(*(blk.cross_attn.kv(ctx) for blk in self.blocks))
return torch.stack(ks), torch.stack(vs)
def cam_embed(self, rays: torch.Tensor) -> torch.Tensor:
"""Per-pixel (origin, direction) maps [B, F, 8 h, 8 w, 6] of LingBot's frame-to-frame poses -> camera tokens [B, L, dim]."""
b, f, hh, ww, _ = rays.shape
h, w = hh // 16, ww // 16 # token grid: 8x (VAE) then 2x (patch)
x = rays.view(b, f, h, 2, 8, w, 2, 8, 6) # [b f h c2 c1 w c3 c1' c]: rows = h, patch row, pixel row
# LingBot packs pixels into the latent grid as (c, c1, c2) and patches as (.., ph, pw): token vector order (c, c1, c2, ph, pw)
x = x.permute(0, 1, 2, 5, 8, 4, 7, 3, 6).reshape(b, f * h * w, 6 * 64 * 4)
e = self.patch_embedding_wancamctrl(x.to(self.patch_embedding_wancamctrl.weight.dtype))
return e + self.c2ws_hidden_states_layer2(F.silu(self.c2ws_hidden_states_layer1(e)))
# ---- one chunk -----------------------------------------------------------
def forward(self, x: torch.Tensor, t: float, text_kv: Tuple[torch.Tensor, torch.Tensor], cam: Optional[torch.Tensor],
rope: Tuple[torch.Tensor, torch.Tensor], ctx: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
geo: Optional[Geo] = None, lora: Optional["RetrievalAdapter"] = None, want_kv: bool = False):
"""Flow prediction for one chunk.
x: [B, 36, F, h, w] (noisy latents, mask, conditioning latents); t: timestep in [0, 1000];
cam: camera tokens [B, L, dim] from `cam_embed` (None = no camera input);
rope: cos/sin [L, d/2] of the chunk's tokens; ctx: keys and values of the context frames,
each [layers, B, H, Lc, d], keys already rotated. Returns the flow [B, 16, F, h, w] and,
with `want_kv`, the chunk's own rotated keys and values [layers, B, H, L, d].
"""
cfg = self.cfg
b, _, f, h, w = x.shape
p = self.patch_embedding.weight
x = self.patch_embedding(x.to(p.dtype)).flatten(2).transpose(1, 2) # [B, L, dim]
emb = ir.sinusoidal_embedding(cfg.freq_dim, torch.tensor([float(t)], device=p.device)).to(p.dtype)
e_t = self.time_embedding(emb) # [1, dim]
e0 = self.time_projection(e_t).unflatten(1, (6, cfg.dim))[0] # [6, dim]
cos, sin = rope
tk, tv = text_kv
ks, vs = [], []
for i, blk in enumerate(self.blocks):
e = blk.modulation[0] + e0
y = blk.norm1(x) * (1 + e[1]) + e[0]
sa = blk.self_attn
ql, kl, vl = sa.q(y), sa.k(y), sa.v(y)
if lora is not None:
dq_, dk_, dv_ = lora.delta(i, "q", y), lora.delta(i, "k", y), lora.delta(i, "v", y)
ql, kl, vl = ql + dq_, kl + dk_, vl + dv_
q, k_raw, v = sa.heads(sa.norm_q(ql)), sa.heads(sa.norm_k(kl)), sa.heads(vl)
q, k = ir.rope_rotate(q, cos, sin), ir.rope_rotate(k_raw, cos, sin)
if want_kv: # "raw": keys before the positional rotation (what the KV refiner works on)
ks.append(k_raw if want_kv == "raw" else k)
vs.append(v)
scale = None
if geo is not None and geo.mode == "offset":
q, k = q + geo.dq[i], k + geo.dk[i]
if ctx is not None:
ck = ctx[0][i].to(k.dtype)
if geo is not None and geo.mode == "offset":
ck = ck + geo.dk_ctx[i]
if geo is not None and geo.mode == "bias" and geo.dk_ctx is not None:
scale = 1.0 / math.sqrt(cfg.head_dim) # keep the model's own logits as they were
q = torch.cat([q, geo.dq[i].to(q.dtype)], dim=-1)
ck = torch.cat([ck, geo.dk_ctx[i].to(k.dtype)], dim=-1)
k = F.pad(k, (0, geo.dq.shape[-1])) # the chunk's own keys get no bias
k, v = torch.cat([ck, k], dim=2), torch.cat([ctx[1][i].to(v.dtype), v], dim=2)
a = F.scaled_dot_product_attention(q, k, v, scale=scale).transpose(1, 2).flatten(2)
o = sa.o(a)
if lora is not None:
o = o + lora.delta(i, "o", a)
x = x + o * e[2]
if cam is not None:
c = blk.cam_injector_layer2(F.silu(blk.cam_injector_layer1(cam))) + cam
x = (1.0 + blk.cam_scale_layer(c)) * x + blk.cam_shift_layer(c)
ca = blk.cross_attn
qc = ca.heads(ca.norm_q(ca.q(blk.norm3(x))))
x = x + ca.o(F.scaled_dot_product_attention(qc, tk[i], tv[i]).transpose(1, 2).flatten(2))
x = x + blk.ffn(blk.norm2(x) * (1 + e[4]) + e[3]) * e[5]
e = self.head.modulation[0] + e_t[0]
x = self.head.head(self.head.norm(x) * (1 + e[1]) + e[0])
pt, ph, pw = cfg.patch
x = x.view(b, f, h // ph, w // pw, ph, pw, cfg.out_dim).permute(0, 6, 1, 2, 4, 3, 5).reshape(b, cfg.out_dim, f, h, w)
if want_kv:
return x, (torch.stack(ks), torch.stack(vs))
return x
def load_lingbot(path: str, device, dtype) -> LBDiT:
"""Load the released DiT weights (a folder of .safetensors shards or one file)."""
from safetensors.torch import load_file
files = [os.path.join(path, f) for f in sorted(os.listdir(path)) if f.endswith(".safetensors")] if os.path.isdir(path) else [path]
sd: Dict[str, torch.Tensor] = {}
for f in files:
sd.update(load_file(f))
dit = LBDiT()
missing, unexpected = dit.load_state_dict(sd, strict=False)
if missing or unexpected:
raise RuntimeError(f"checkpoint mismatch: missing={missing[:6]} unexpected={unexpected[:6]}")
return dit.to(device=device, dtype=dtype).eval().requires_grad_(False)
# =============================================================================
# Camera inputs
# =============================================================================
def framewise_poses(c2w: torch.Tensor) -> Tuple[torch.Tensor, float]:
"""LingBot's camera convention: pose of every frame relative to the previous one, translations
divided by the largest step. c2w: [F, 4, 4] (OpenCV). Returns ([F, 4, 4], largest step)."""
c2w = c2w.to(torch.float64)
rel = torch.linalg.inv(c2w[0:1]) @ c2w
rel[0] = torch.eye(4, dtype=rel.dtype)
out = rel.clone()
out[1:] = torch.linalg.inv(rel[:-1]) @ rel[1:]
step = float(out[:, :3, 3].norm(dim=-1).max())
if step > 0:
out[:, :3, 3] = out[:, :3, 3] / step
return out, step
def lingbot_rays(poses: torch.Tensor, K: torch.Tensor, height: int = 480, width: int = 832) -> torch.Tensor:
"""(origin, direction) of every pixel for LingBot's camera pathway: [F, H, W, 6]. K: (fx, fy, cx, cy) in pixels."""
dt, dev = poses.dtype, poses.device
K = K.to(device=dev, dtype=dt)
gy, gx = torch.meshgrid(torch.arange(height, dtype=dt, device=dev) + 0.5, torch.arange(width, dtype=dt, device=dev) + 0.5, indexing="ij")
d = torch.stack([(gx - K[2]) / K[0], (gy - K[3]) / K[1], torch.ones_like(gx)], dim=-1)
d = d / d.norm(dim=-1, keepdim=True)
rd = torch.einsum("fij,hwj->fhwi", poses[:, :3, :3], d)
ro = poses[:, None, None, :3, 3].expand_as(rd)
return torch.cat([ro, rd], dim=-1)
def ray_features(c2w: torch.Tensor, K_norm: torch.Tensor, ref: torch.Tensor, scale: float, gh: int, gw: int) -> torch.Tensor:
"""Viewing ray of every token of every frame in the camera frame of `ref`: [F, gh * gw, 9] = (direction, moment, origin).
c2w: [F, 4, 4]; K_norm: (fx, fy, cx, cy) divided by the image size; translations are divided by `scale`.
"""
rel = ir.relative_poses(c2w.to(torch.float64), ref.to(torch.float64), scale if scale > 0 else 1.0)
o, d = ir.camera_rays(K_norm.to(torch.float64), rel, gh, gw) # [F, gh, gw, 3]
return torch.cat([d, torch.cross(o, d, dim=-1), o], dim=-1).flatten(1, 2)
class RetrievalAdapter(nn.Module):
"""Geometry-aware attention offsets and LoRA for the self-attention of every block. Starts as a no-op."""
def __init__(self, cfg: ir.DiTConfig, feat: int = 256, rank: int = 32, geometry: bool = True, lora_on: Sequence[str] = ("q", "k", "v", "o"),
geo_mode: str = "offset", bias_dim: int = 32):
super().__init__()
self.cfg, self.rank, self.geometry, self.lora_on = cfg, rank, geometry, tuple(lora_on)
self.geo_mode, self.bias_dim = geo_mode, bias_dim
self.register_buffer("f_dir", (2.0 ** torch.arange(0, 6)).float() * math.pi / 2, persistent=False)
self.register_buffer("f_pos", (2.0 ** torch.arange(-4, 4)).float(), persistent=False)
n_in = 9 + 2 * (3 * 6 + 6 * 8)
if geometry:
self.enc = nn.Sequential(nn.Linear(n_in, feat), nn.SiLU(), nn.Linear(feat, feat), nn.SiLU(), nn.Linear(feat, feat))
n_out = cfg.dim if geo_mode == "offset" else cfg.num_heads * bias_dim
self.wq = nn.Parameter(torch.zeros(cfg.num_layers, n_out, feat)) # zero: no effect at the start
self.wk = nn.Parameter(torch.zeros(cfg.num_layers, n_out, feat) if geo_mode == "offset" else torch.randn(cfg.num_layers, n_out, feat) / math.sqrt(feat))
if rank > 0:
self.lora_a = nn.ParameterDict({n: nn.Parameter(torch.randn(cfg.num_layers, rank, cfg.dim) / math.sqrt(cfg.dim)) for n in self.lora_on})
self.lora_b = nn.ParameterDict({n: nn.Parameter(torch.zeros(cfg.num_layers, cfg.dim, rank)) for n in self.lora_on})
def delta(self, layer: int, name: str, x: torch.Tensor) -> torch.Tensor:
if self.rank <= 0 or name not in self.lora_on:
return torch.zeros((), dtype=x.dtype, device=x.device)
a, b = self.lora_a[name][layer].to(x.dtype), self.lora_b[name][layer].to(x.dtype)
return F.linear(F.linear(x, a), b)
def embed(self, rays: torch.Tensor) -> torch.Tensor:
"""[..., 9] (direction, moment, origin) -> [..., feat]."""
d, mo = rays[..., :3], rays[..., 3:]
fd = (d[..., None] * self.f_dir.to(d.dtype)).flatten(-2)
fp = (mo[..., None] * self.f_pos.to(d.dtype)).flatten(-2)
x = torch.cat([rays, fd.sin(), fd.cos(), fp.sin(), fp.cos()], dim=-1)
return self.enc(x.to(self.enc[0].weight.dtype))
def offsets(self, rays_chunk: torch.Tensor, rays_ctx: Optional[torch.Tensor], dtype, mask: Optional[torch.Tensor] = None) -> Optional[Geo]:
"""rays_chunk: [L, 9]; rays_ctx: [Lc, 9] or None -> per-layer offsets for one chunk call (batch 1).
mask [Lc]: 1 for the context tokens that get the term, 0 for the rest."""
if not self.geometry:
return None
cfg = self.cfg
hd = (cfg.num_heads, cfg.head_dim if self.geo_mode == "offset" else self.bias_dim)
def proj(w, g): # [layers, dim, feat] x [L, feat] -> [layers, 1, H, L, d]
return torch.einsum("lcf,nf->lnc", w, g).unflatten(-1, hd).transpose(1, 2)[:, None].to(dtype)
gc = self.embed(rays_chunk)
dk_ctx = proj(self.wk, self.embed(rays_ctx)) if rays_ctx is not None else None
if mask is not None and dk_ctx is not None:
dk_ctx = dk_ctx * mask.to(dk_ctx.dtype)[None, None, None, :, None]
if self.geo_mode == "bias":
return Geo(proj(self.wq, gc), None, dk_ctx, "bias")
return Geo(proj(self.wq, gc), proj(self.wk, gc), dk_ctx)
class ChunkRefiner(ir.KVRefiner):
"""The KV refiner of infer_realtime.py on a chunk: each latent frame of the chunk is one batch item.
It repairs the cache entry left by the last denoising pass (noisy input), so the extra clean pass
over the chunk is not needed. Same parameters as ir.KVRefiner: its checkpoints load here.
"""
def features(self, tok, t, dit=None, cam=None, feats=None):
x = self.stem(tok.to(self.stem.weight.dtype))
temb = self.time(ir.sinusoidal_embedding(256, torch.full((x.shape[0],), float(t), device=x.device)).to(x.dtype))
for blk in self.blocks:
x = blk(x, temb)
return x
def refine(self, k_raw: torch.Tensor, v: torch.Tensor, tok: torch.Tensor, t: float, n_frames: int, frames: Optional[Sequence[int]] = None):
"""k_raw, v: [layers, 1, H, F L, d] of the last denoising pass (keys before rotation); tok: [1, F L, dim] patch
tokens of the clean chunk input. Returns refined (k_raw, v) for the frames asked for: [layers, 1, H, n L, d]."""
n, _, hh, FL, d = k_raw.shape
L = FL // n_frames
sel = list(range(n_frames)) if frames is None else list(frames)
split = lambda x: x[:, 0].reshape(n, hh, n_frames, L, d).permute(0, 2, 1, 3, 4)[:, sel] # [layers, n, H, L, d]
k2, v2 = self(split(k_raw), split(v), tok.reshape(n_frames, L, -1)[sel], t, None)
join = lambda x: x.permute(0, 2, 1, 3, 4).reshape(n, 1, hh, len(sel) * L, d)
return join(k2), join(v2)
def load_chunk_refiner(path: str, cfg: ir.DiTConfig, device, dtype) -> ChunkRefiner:
r = ir.load_refiner(path, cfg, device, dtype)
r.__class__ = ChunkRefiner
return r
# =============================================================================
# Chunk-wise rollout with a slot cache: sink + retrieved + recent
# =============================================================================
@dataclass
class StreamConfig:
slots: int = 9 # latent frames attention can see, including the chunk being generated
sink: int = 1 # first frames, always kept
retrieved: int = 3 # slots filled by frustum retrieval (0 = plain sliding window)
chunk: int = 4
retime: str = "native" # temporal index of retrieved frames: native | clamp
clamp: int = 16 # with retime=clamp: retrieved frames sit at most this many frames before the chunk
min_gap: int = 1 # a frame can be retrieved once it is this many frames older than the recent window
min_cover: float = 0.0 # > 0: load a frame only if it covers the view of the chunk at least this well; free slots go back to the recent window
bias_on: str = "retrieved" # context frames that get the attention bias (bias mode): retrieved | all
steps: Tuple[Tuple[float, float], ...] = tuple(student_steps())
class Stream:
"""Generates (or, with `teacher`, re-encodes) a clip chunk by chunk and keeps every frame's keys/values in a pool."""
def __init__(self, dit: LBDiT, cfg: StreamConfig, adapter: Optional[RetrievalAdapter] = None, hw: Tuple[int, int] = (60, 104),
refiner: Optional[ChunkRefiner] = None):
self.dit, self.cfg, self.adapter, self.refiner = dit, cfg, adapter, refiner
self.h, self.w = hw
self.gh, self.gw = hw[0] // 2, hw[1] // 2
self.tokens = self.gh * self.gw
self.rope = ir.RoPE3D(dit.cfg.head_dim, self.gh, self.gw)
p = dit.patch_embedding.weight
self.device, self.dtype = p.device, p.dtype
# ---- bookkeeping ---------------------------------------------------------
def setup(self, c2w: torch.Tensor, K: torch.Tensor, cond: torch.Tensor, text: torch.Tensor, cond_tail: Optional[torch.Tensor] = None) -> None:
"""c2w: [T, 4, 4] one pose per latent frame; K: (fx, fy, cx, cy) in pixels at 8h x 8w; cond: [16, n, h, w]
image-to-video conditioning latents (the VAE encoding of the image followed by empty frames; frame 0 = the image);
cond_tail: the same encoding for any image and more frames, used past frame n (it stops depending on the
image after about 8 frames); the last frame repeats. text: [n, text_dim]."""
if cond_tail is not None and cond_tail.shape[1] > cond.shape[1]:
cond = torch.cat([cond.float(), cond_tail[:, cond.shape[1]:].float().to(cond.device)], dim=1)
self.c2w, self.K = c2w.to(torch.float64).cpu(), K.to(torch.float64).cpu()
T = c2w.shape[0]
self.fw, self.step = framewise_poses(self.c2w) # the per-pixel ray maps are built on the GPU, one chunk at a time
self.K_norm = self.K / torch.tensor([8 * self.w, 8 * self.h, 8 * self.w, 8 * self.h], dtype=torch.float64)
n = cond.shape[1]
idx = torch.arange(T).clamp_max(n - 1)
y = cond[:, idx].to(device=self.device, dtype=self.dtype)
msk = torch.zeros(4, T, self.h, self.w, device=self.device, dtype=self.dtype)
msk[:, 0] = 1
self.y = torch.cat([msk, y], dim=0) # [20, T, h, w]
self.text_kv = self.dit.text_cond(text[None].to(self.device))
self.pool: Dict[int, Tuple[torch.Tensor, torch.Tensor]] = {}
self.index = ir.FrustumIndex(min_gain=-1.0)
self.log: List[dict] = []
def rope_table(self, frames: Sequence[int]) -> Tuple[torch.Tensor, torch.Tensor]:
cs = [self.rope.table(int(f), self.device, self.dtype) for f in frames]
return torch.cat([c for c, _ in cs]), torch.cat([s for _, s in cs])
def context(self, f0: int) -> Tuple[List[int], List[int], List[int]]:
"""Frames attention sees while generating the chunk that starts at f0: (sink, retrieved, recent)."""
c = self.cfg
have = sorted(self.pool)
sink = [f for f in have if f < c.sink]
n_recent = c.slots - c.chunk - len(sink) - c.retrieved
recent = [f for f in have if f >= c.sink][-n_recent:] if n_recent > 0 else []
picks: List[int] = []
if c.retrieved > 0 and len(self.index):
oldest = min(recent) if recent else f0
cand = [f for f in have if f >= c.sink and f <= oldest - c.min_gap and f not in recent]
banned = [f for f in self.index.ids if f not in cand]
if cand and c.min_cover > 0: # the best-covering stored frame for each pose of the chunk, if it covers it well enough
pos = {f: i for i, f in enumerate(self.index.ids)}
best: Dict[int, float] = {}
for j in range(c.chunk):
if f0 + j >= self.c2w.shape[0]:
break
sim = self.index.similarity(self.K_norm, self.c2w[f0 + j]).mean(1)
f = max(cand, key=lambda g: float(sim[pos[g]]))
if float(sim[pos[f]]) >= c.min_cover:
best[f] = max(best.get(f, 0.0), float(sim[pos[f]]))
picks = sorted(best, key=lambda g: -best[g])[:c.retrieved]
n_recent = c.slots - c.chunk - len(sink) - len(picks) # unused retrieval slots go back to the recent window
recent = [f for f in have if f >= c.sink and f not in picks][-n_recent:] if n_recent > 0 else []
elif cand: # greedy cover of the views of the chunk: best frame for each target pose in turn, then fill by overall gain
for j in range(c.chunk):
if len(picks) >= c.retrieved or f0 + j >= self.c2w.shape[0]:
break
got = self.index.query(self.K_norm, self.c2w[f0 + j], 1, exclude=banned + picks)
picks += got
if len(picks) < c.retrieved:
mid = min(f0 + c.chunk // 2, self.c2w.shape[0] - 1)
picks += self.index.query(self.K_norm, self.c2w[mid], c.retrieved - len(picks), exclude=banned + picks)
return sink, sorted(picks), recent
def gather(self, f0: int, frames: Sequence[int], retrieved: Sequence[int]) -> Optional[Tuple[torch.Tensor, torch.Tensor]]:
"""Keys and values of the context frames, [layers, 1, H, Lc, d]; retrieved frames re-timed if asked."""
if not frames:
return None
ks, vs = [], []
for f in frames:
k, v = self.pool[f]
if f in retrieved and self.cfg.retime == "clamp" and f0 - f > self.cfg.clamp:
cos, sin = self.rope.shift_table((f0 - self.cfg.clamp) - f, self.device, k.dtype)
k = ir.rope_rotate(k, cos, sin)
ks.append(k)
vs.append(v)
return torch.cat(ks, dim=3), torch.cat(vs, dim=3)
def geometry(self, f0: int, frames: Sequence[int], ctx_frames: Sequence[int], retrieved: Sequence[int] = ()) -> Optional[Geo]:
if self.adapter is None or not self.adapter.geometry:
return None
only_retrieved = self.adapter.geo_mode == "bias" and self.cfg.bias_on == "retrieved"
if only_retrieved and not retrieved:
return None # nothing was retrieved: the pass is exactly the base model's
ref = self.c2w[f0]
rc = ray_features(self.c2w[list(frames)], self.K_norm, ref, self.step, self.gh, self.gw).flatten(0, 1).to(self.device).float()
rx = ray_features(self.c2w[list(ctx_frames)], self.K_norm, ref, self.step, self.gh, self.gw).flatten(0, 1).to(self.device).float() if ctx_frames else None
mask = None
if only_retrieved:
mask = torch.tensor([float(f in retrieved) for f in ctx_frames], device=self.device).repeat_interleave(self.tokens)
return self.adapter.offsets(rc, rx, self.dtype, mask)
def chunk_inputs(self, f0: int):
"""Everything one chunk call needs except the latents: frames, context, camera tokens, RoPE, geometry."""
frames = list(range(f0, min(f0 + self.cfg.chunk, self.c2w.shape[0])))
sink, picks, recent = self.context(f0)
order = sink + picks + recent
ctx = self.gather(f0, order, picks)
cam = self.dit.cam_embed(lingbot_rays(self.fw[frames].to(device=self.device, dtype=torch.float32), self.K, 8 * self.h, 8 * self.w)[None])
rope = self.rope_table(frames)
geo = self.geometry(f0, frames, order, picks)
return frames, (sink, picks, recent), ctx, cam, rope, geo
def patch_tokens(self, x0: torch.Tensor, frames: Sequence[int]) -> torch.Tensor:
"""Patch embedding of the clean chunk input (latents + image-to-video conditioning): [1, F L, dim]."""
x = torch.cat([x0, self.y[:, frames][None]], dim=1)
return self.dit.patch_embedding(x.to(self.dit.patch_embedding.weight.dtype)).flatten(2).transpose(1, 2)
def call(self, z: torch.Tensor, t: float, frames, ctx, cam, rope, geo, want_kv=False):
x = torch.cat([z, self.y[:, frames][None]], dim=1)
return self.dit(x, t, self.text_kv, cam, rope, ctx, geo, self.adapter, want_kv)
def store(self, frames: Sequence[int], kv: Tuple[torch.Tensor, torch.Tensor]) -> None:
k, v = kv
for j, f in enumerate(frames):
s = slice(j * self.tokens, (j + 1) * self.tokens)
self.pool[f] = (k[:, :, :, s].detach(), v[:, :, :, s].detach())
self.index.add(f, self.K_norm, self.c2w[f], t=float(f))
# ---- rollouts ------------------------------------------------------------
@torch.no_grad()
def run(self, n_frames: int, noise: Optional[torch.Generator] = None, teacher: Optional[torch.Tensor] = None,
upto: Optional[int] = None) -> torch.Tensor:
"""Generate n_frames latent frames ([16, n, h, w]), or with `teacher` ([16, T, h, w] clean latents) only
compute every frame's keys/values as inference would, with the clean latents standing in for the samples."""
c = self.cfg
out = []
for f0 in range(0, n_frames, c.chunk):
if upto is not None and f0 >= upto:
break
frames, (sink, picks, recent), ctx, cam, rope, geo = self.chunk_inputs(f0)
self.log.append(dict(chunk=f0, sink=sink, retrieved=picks, recent=recent))
use_refiner = self.refiner is not None and teacher is None and f0 > 0 # the first chunk holds the sink: always a real clean pass
last = None
if teacher is None:
z = torch.randn(1, 16, len(frames), self.h, self.w, generator=noise).to(device=self.device, dtype=self.dtype)
x0 = z
for i, (t, s) in enumerate(c.steps):
final = i == len(c.steps) - 1
if final and use_refiner:
flow, last = self.call(z, t, frames, ctx, cam, rope, geo, want_kv="raw")
else:
flow = self.call(z, t, frames, ctx, cam, rope, geo)
x0 = (z.float() - s * flow.float()).to(self.dtype)
if not final:
sn = c.steps[i + 1][1]
eps = torch.randn(z.shape, generator=noise).to(device=self.device, dtype=self.dtype)
z = (1 - sn) * x0 + sn * eps
else:
x0 = teacher[:, frames][None].to(device=self.device, dtype=self.dtype)
if use_refiner: # repair the entry of the last (noisy) pass instead of running a clean pass
k, v = self.refiner.refine(last[0], last[1], self.patch_tokens(x0, frames), c.steps[-1][0], len(frames))
kv = (ir.rope_rotate(k.to(self.dtype), *rope), v.to(self.dtype))
else:
_, kv = self.call(x0, 0.0, frames, ctx, cam, rope, geo, want_kv=True)
self.store(frames, kv)
out.append(x0[0].float())
return torch.cat(out, dim=1)