ConsDrive / models /world_predictor.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
9.6 kB
"""Block-causal latent-action world predictor (ported from SimLingo-J1).
Each temporal block contains 64 V-JEPA2 state tokens and 8 student latent
action tokens. Tokens within a block attend bidirectionally; a block can only
attend to itself and earlier blocks. The predictor is supervised to map
teacher-forced ``S[t]`` plus latent ``A[t]`` to ``S[t+1]``.
"""
from __future__ import annotations
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor, nn
def build_block_causal_mask(
num_blocks: int, state_tokens: int, action_tokens: int
) -> Tensor:
if min(num_blocks, state_tokens, action_tokens) <= 0:
raise ValueError("block mask dimensions must be positive")
block_size = state_tokens + action_tokens
block_ids = torch.arange(num_blocks).repeat_interleave(block_size)
# PyTorch boolean attention masks use True for forbidden pairs.
return block_ids.unsqueeze(0) > block_ids.unsqueeze(1)
def linear_world_weight(global_step: int, weight: float, warmup_steps: int) -> float:
"""Weight for the optimizer update about to run (steps are zero-indexed)."""
if warmup_steps <= 0:
return float(weight)
return float(weight) * min((int(global_step) + 1) / int(warmup_steps), 1.0)
class BlockCausalWorldPredictor(nn.Module):
"""Predict ``S[t+1]`` from teacher-forced ``S[t]`` and latent ``A[t]``."""
def __init__(
self,
*,
action_dim: int,
predictor_dim: int = 1024,
target_dim: int = 1024,
depth: int = 12,
heads: int = 8,
mlp_ratio: float = 4.0,
dropout: float = 0.0,
num_blocks: int = 3,
state_tokens: int = 64,
action_tokens: int = 8,
) -> None:
super().__init__()
if predictor_dim % heads:
raise ValueError("predictor_dim must be divisible by predictor_heads")
self.num_blocks = int(num_blocks)
self.state_tokens = int(state_tokens)
self.action_tokens = int(action_tokens)
self.state_projection = nn.Linear(target_dim, predictor_dim)
self.action_projection = nn.Linear(action_dim, predictor_dim)
self.state_type_embed = nn.Parameter(torch.zeros(1, 1, predictor_dim))
self.action_type_embed = nn.Parameter(torch.zeros(1, 1, predictor_dim))
self.spatial_embed = nn.Parameter(
0.02 * torch.randn(1, state_tokens, predictor_dim)
)
self.action_slot_embed = nn.Parameter(
0.02 * torch.randn(1, action_tokens, predictor_dim)
)
self.time_embed = nn.Parameter(
torch.zeros(1, num_blocks, 1, predictor_dim)
)
layer = nn.TransformerEncoderLayer(
d_model=predictor_dim,
nhead=heads,
dim_feedforward=int(predictor_dim * mlp_ratio),
dropout=dropout,
activation="gelu",
batch_first=True,
norm_first=True,
)
self.transformer = nn.TransformerEncoder(
layer, num_layers=depth, norm=nn.LayerNorm(predictor_dim)
)
self.output_projection = nn.Linear(predictor_dim, target_dim)
self.register_buffer(
"attention_mask",
build_block_causal_mask(num_blocks, state_tokens, action_tokens),
persistent=False,
)
def forward(self, states: Tensor, actions: Tensor) -> Tensor:
expected_states = (self.num_blocks, self.state_tokens)
expected_actions = (self.num_blocks, self.action_tokens)
if states.ndim != 4 or tuple(states.shape[1:3]) != expected_states:
raise ValueError(
f"states must be [B,{self.num_blocks},{self.state_tokens},D], "
f"got {tuple(states.shape)}"
)
if actions.ndim != 4 or tuple(actions.shape[1:3]) != expected_actions:
raise ValueError(
f"actions must be [B,{self.num_blocks},{self.action_tokens},D], "
f"got {tuple(actions.shape)}"
)
param_dtype = self.state_projection.weight.dtype
state_tokens = self.state_projection(states.to(param_dtype))
state_tokens = (
state_tokens
+ self.spatial_embed.unsqueeze(1)
+ self.state_type_embed.unsqueeze(1)
+ self.time_embed
)
action_tokens = self.action_projection(actions.to(param_dtype))
action_tokens = (
action_tokens
+ self.action_slot_embed.unsqueeze(1)
+ self.action_type_embed.unsqueeze(1)
+ self.time_embed
)
blocks = torch.cat((state_tokens, action_tokens), dim=2)
encoded = self.transformer(
blocks.flatten(1, 2), mask=self.attention_mask, is_causal=False
)
encoded = encoded.view(
states.size(0), self.num_blocks, self.state_tokens + self.action_tokens, -1
)
return self.output_projection(encoded[:, :, : self.state_tokens])
def masked_world_l1(
predictor: BlockCausalWorldPredictor,
actions: Tensor,
future_states: Optional[Tensor],
valid: Optional[Tensor],
) -> Tuple[Tensor, int]:
"""Globally-normalized L1 over valid samples only.
Different distributed ranks may receive different numbers of valid targets
(shift-augmented samples are masked out). If at least one rank has a valid
future target, every rank must include the predictor in its autograd graph,
so ranks without a valid target execute a zero-weight dummy forward. This
keeps DeepSpeed/DDP gradient collectives aligned across ranks. When the
global batch contains no valid target the predictor is skipped entirely.
"""
local_count = (
int(valid.to(dtype=torch.long).sum().item())
if future_states is not None and valid is not None
else 0
)
distributed = torch.distributed.is_available() and torch.distributed.is_initialized()
global_count_tensor = actions.new_tensor(local_count, dtype=torch.long)
if distributed:
torch.distributed.all_reduce(
global_count_tensor, op=torch.distributed.ReduceOp.SUM
)
global_count = int(global_count_tensor.item())
if global_count == 0:
return actions.new_zeros(()), 0
world_size = torch.distributed.get_world_size() if distributed else 1
num_blocks = predictor.num_blocks
state_tokens = predictor.state_tokens
target_dim = predictor.state_projection.in_features
if future_states is not None and (
future_states.ndim != 4
or tuple(future_states.shape[1:])
!= (num_blocks + 1, state_tokens, target_dim)
):
raise ValueError(
f"future_states must have shape [B,{num_blocks + 1},{state_tokens},{target_dim}], "
f"got {tuple(future_states.shape)}"
)
if future_states is None:
predictor_states = actions.new_zeros(
(actions.size(0), num_blocks + 1, state_tokens, target_dim)
)
local_valid = torch.zeros(actions.size(0), dtype=torch.bool, device=actions.device)
else:
predictor_states = future_states.detach()
local_valid = (
valid.to(device=actions.device, dtype=torch.bool)
if valid is not None
else torch.zeros(actions.size(0), dtype=torch.bool, device=actions.device)
)
# Always use the full local microbatch. A rank-local selected subset gives
# DeepSpeed Stage 2 a different predictor execution shape on each rank and
# can stall reduction even when the same parameters are present.
predictions = predictor(predictor_states[:, :num_blocks], actions)
targets = predictor_states[:, 1:]
selected_predictions = predictions[local_valid]
selected_targets = targets[local_valid]
# DDP averages gradients across ranks. This scale makes that result equal
# to a mean over every valid element in the global batch, even when the
# rank-local valid counts differ.
error_sum = (selected_predictions - selected_targets.to(selected_predictions.dtype)).abs().float().sum()
elements_per_sample = targets[0].numel()
loss = error_sum * (float(world_size) / (global_count * elements_per_sample))
return loss, global_count
def masked_world_l1_diagnostics(
predictor: BlockCausalWorldPredictor,
actions: Tensor,
future_states: Optional[Tensor],
valid: Optional[Tensor],
) -> Tuple[dict, int]:
"""Validation-only correct/shuffled/reversed target comparison."""
if future_states is None or valid is None or not bool(valid.any()):
zero = actions.new_zeros(())
return {"correct": zero, "shuffled": zero, "reversed": zero}, 0
selected_actions = actions[valid]
selected_states = future_states[valid].detach()
predictions = predictor(selected_states[:, : predictor.num_blocks], selected_actions)
targets = selected_states[:, 1:].to(predictions.dtype)
if targets.size(0) > 1:
shuffled = targets.roll(1, dims=0)
else:
shuffled = targets.roll(1, dims=2)
losses = {
"correct": F.l1_loss(predictions, targets, reduction="mean"),
"shuffled": F.l1_loss(predictions, shuffled, reduction="mean"),
"reversed": F.l1_loss(predictions, targets.flip(1), reduction="mean"),
}
return losses, int(valid.sum().item())