"""The three baseline policies behind one contract, ported from DextraVerse's imitation-learning core: - `fm_dit`, `FMDiTPolicy` (reference: dextraverse/algorithms/il/models/fm_dit.py + fm_base.py): flow matching, MSE on the velocity `a - noise`; sampled with 10 midpoint steps from noise (20 DiT calls); - `dp`, `DPPolicy` (ddpm_dit.py + ddpm_base.py: Diffusion Policy with a DiT backbone): DDPM epsilon MSE over 100 steps; sampled with the 100 DDPM steps; - `act`, `ACTPolicy` (act.py + nets/act/): L1 + `kl_weight` x KL of the CVAE; decoded from the zero latent in one pass. Contract (every policy): `compute_loss(images, state, action) -> (loss, metrics)` and `predict(images, state, generator) -> (action, normalized action)`; images (B, n_cameras, 3, H, W) float in [0, 1], state (B, state_dim) and action (B, horizon, action_dim) in physical units. Each policy owns its `Normalizer` (DextraVerse's LinearNormalizer 'limits' mode: state and action to [-1, 1] per dimension, constant dimensions shifted to 0), saved in its state dict. One observation frame (n_obs_steps 1: the current images and state); the chunk's row 0 is the action of the observation's own frame (the LeRobot rows t..t+horizon-1). The configuration that builds a policy is a plain dict (`PolicyConfig` fields), stored in the checkpoint. The ResNet18 starts from torchvision's ImageNet-1k weights (`backbone_weights` 'IMAGENET1K_V1', the default since 2026-11-16) and is fine-tuned with the policy, its BatchNorm frozen at the pretrained statistics (`backbone_norm` 'frozen_bn', as ACT always does); `backbone_weights` None trains from scratch with DextraVerse's GroupNorm encoder (FM-DiT, DP) or ACT's frozen-BatchNorm one. A checkpoint load builds the structure without fetching any weights. """ from __future__ import annotations from dataclasses import asdict, dataclass, field, replace import torch import torch.nn as nn import torch.nn.functional as F from .act_nets import DETRVAE, Transformer, build_backbone, build_style_encoder, kl_divergence from .nets import IMAGENET_MEAN, IMAGENET_STD, FlowTransformer, ImageStateEncoder @dataclass class PolicyConfig: """Everything that builds a policy (stored in the checkpoint's config.json). Model defaults are DextraVerse's configs/algorithm/il/model/{fm_dit,ddpm_dit,act}.yaml.""" policy: str n_cameras: int state_dim: int action_dim: int horizon: int = 16 backbone: str = 'resnet18' backbone_weights: str | None = 'IMAGENET1K_V1' # torchvision weights to initialize from; None = from scratch backbone_norm: str | None = None # 'frozen_bn' or 'group'; None: frozen_bn when pretrained or ACT, else group # FM-DiT / DP (DiT backbone) hidden_dim: int = 384 num_layers: int = 4 num_heads: int = 8 mlp_ratio: float = 4.0 dropout: float = 0.1 time_embed_dim: int = 128 num_inference_steps: int | None = None # None: FM-DiT 10 midpoint steps, DP every training timestep (100) # DP noise schedule (diffusers DDPMScheduler) num_train_timesteps: int = 100 beta_schedule: str = 'squaredcos_cap_v2' prediction_type: str = 'epsilon' clip_sample: bool = True # ACT act_hidden_dim: int = 512 dim_feedforward: int = 3200 enc_layers: int = 4 dec_layers: int = 7 nheads: int = 8 latent_dim: int = 32 kl_weight: float = 10.0 extra: dict = field(default_factory=dict) def __post_init__(self): if self.backbone_norm is None: self.backbone_norm = 'frozen_bn' if self.backbone_weights or self.policy == 'act' else 'group' if self.policy == 'act' and self.backbone_norm != 'frozen_bn': raise ValueError("ACT's backbone keeps frozen BatchNorm (backbone_norm 'frozen_bn')") @classmethod def from_dict(cls, data: dict) -> PolicyConfig: known = {k: v for k, v in data.items() if k in cls.__dataclass_fields__} return cls(**known) def to_dict(self) -> dict: return asdict(self) class Normalizer(nn.Module): """Per-dimension affine map to [-1, 1] from the training data's min/max (DextraVerse LinearNormalizer, mode 'limits', fit_offset, range_eps 1e-4): x_n = x * scale + offset; a dimension whose range is below range_eps gets scale 1 and maps its value to 0.""" def __init__(self, dim: int): super().__init__() self.register_buffer('scale', torch.ones(dim)) self.register_buffer('offset', torch.zeros(dim)) @torch.no_grad() def fit(self, minimum, maximum, range_eps=1e-4): lo = torch.as_tensor(minimum, dtype=torch.float32) hi = torch.as_tensor(maximum, dtype=torch.float32) span = hi - lo ignore = span < range_eps span[ignore] = 2.0 scale = 2.0 / span offset = -1.0 - scale * lo offset[ignore] = -lo[ignore] self.scale.copy_(scale) self.offset.copy_(offset) def normalize(self, x): return x * self.scale + self.offset def unnormalize(self, x): return (x - self.offset) / self.scale class BasePolicy(nn.Module): name = '' backbone_prefix = '' # state-dict prefix of the image backbone (its own learning rate in training) def __init__(self, cfg: PolicyConfig, init_weights=None): super().__init__() self.cfg = cfg self.state_norm = Normalizer(cfg.state_dim) self.action_norm = Normalizer(cfg.action_dim) def fit_normalizers(self, stats: dict): self.state_norm.fit(stats['state']['min'], stats['state']['max']) self.action_norm.fit(stats['action']['min'], stats['action']['max']) @property def sampling_steps(self) -> int: return 1 def compute_loss(self, images, state, action): raise NotImplementedError def predict(self, images, state, generator=None): raise NotImplementedError class DiTPolicy(BasePolicy): """Shared by FM-DiT and DP: the shared-ResNet image + state encoder and the AdaLN DiT over the action chunk (global observation conditioning, DextraVerse obs_as_global_cond).""" backbone_prefix = 'obs_encoder.rgb.' def __init__(self, cfg: PolicyConfig, init_weights=None): super().__init__(cfg) self.obs_encoder = ImageStateEncoder(cfg.n_cameras, cfg.state_dim, backbone=cfg.backbone, weights=init_weights, norm=cfg.backbone_norm) self.model = FlowTransformer(input_dim=cfg.action_dim, condition_dim=self.obs_encoder.feature_dim, hidden_dim=cfg.hidden_dim, output_dim=cfg.action_dim, num_layers=cfg.num_layers, num_heads=cfg.num_heads, mlp_ratio=cfg.mlp_ratio, dropout=cfg.dropout, time_embed_dim=cfg.time_embed_dim) def condition(self, images, state): return self.obs_encoder(images, self.state_norm.normalize(state)) class FMDiTPolicy(DiTPolicy): """Flow-matching DiT (DextraVerse FlowMatchingDiTImagePolicy): x_t = (1 - t) noise + t a, t ~ U(0, 1), the DiT regresses the velocity a - noise; sampling integrates t = 0 -> 1 with the midpoint rule.""" name = 'fm_dit' @property def sampling_steps(self) -> int: return int(self.cfg.num_inference_steps or 10) def compute_loss(self, images, state, action): cond = self.condition(images, state) target = self.action_norm.normalize(action) noise = torch.randn_like(target) t = torch.rand(target.shape[0], device=target.device) te = t.view(-1, 1, 1) x_t = (1 - te) * noise + te * target loss = F.mse_loss(self.model(x_t, t, cond), target - noise) return loss, dict(fm=float(loss.detach())) @torch.no_grad() def predict(self, images, state, generator=None): cond = self.condition(images, state) B, steps = images.shape[0], self.sampling_steps x = torch.randn((B, self.cfg.horizon, self.cfg.action_dim), device=cond.device, dtype=cond.dtype, generator=generator) times = torch.linspace(0, 1.0, steps + 1, device=cond.device) for i in range(steps): t0 = times[i].view(1).expand(B) t1 = times[i + 1].view(1).expand(B) dt = (t1 - t0).view(-1, 1, 1) x_mid = x + self.model(x, t0, cond) * dt / 2 x = x + dt * self.model(x_mid, t0 + (t1 - t0) / 2, cond) return self.action_norm.unnormalize(x), x class DPPolicy(DiTPolicy): """Diffusion Policy with the DiT backbone (DextraVerse DiffusionDiTImagePolicy, ddpm_dit.yaml): DDPM with 100 training steps, squaredcos_cap_v2 betas, fixed_small variance, clipped samples, epsilon prediction; sampled with every training step (100 DiT calls).""" name = 'dp' def __init__(self, cfg: PolicyConfig, init_weights=None): super().__init__(cfg, init_weights) from diffusers.schedulers.scheduling_ddpm import DDPMScheduler self.noise_scheduler = DDPMScheduler(num_train_timesteps=cfg.num_train_timesteps, beta_start=0.0001, beta_end=0.02, beta_schedule=cfg.beta_schedule, variance_type='fixed_small', clip_sample=cfg.clip_sample, prediction_type=cfg.prediction_type) @property def sampling_steps(self) -> int: return int(self.cfg.num_inference_steps or self.cfg.num_train_timesteps) def compute_loss(self, images, state, action): cond = self.condition(images, state) target = self.action_norm.normalize(action) noise = torch.randn_like(target) t = torch.randint(0, self.noise_scheduler.config.num_train_timesteps, (target.shape[0],), device=target.device).long() noisy = self.noise_scheduler.add_noise(target, noise, t) pred = self.model(noisy, t, cond) goal = noise if self.cfg.prediction_type == 'epsilon' else target loss = F.mse_loss(pred, goal) return loss, dict(ddpm=float(loss.detach())) @torch.no_grad() def predict(self, images, state, generator=None): cond = self.condition(images, state) scheduler = self.noise_scheduler x = torch.randn((images.shape[0], self.cfg.horizon, self.cfg.action_dim), device=cond.device, dtype=cond.dtype, generator=generator) scheduler.set_timesteps(self.sampling_steps, device=cond.device) for t in scheduler.timesteps: x = scheduler.step(self.model(x, t.to(cond.device), cond), t, x, generator=generator).prev_sample return self.action_norm.unnormalize(x), x class ACTPolicy(BasePolicy): """ACT (DextraVerse ACTImagePolicy, act.yaml): ImageNet-normalized cameras through one ResNet with frozen BatchNorm (spatial tokens, no pooling), the normalized state as qpos, a CVAE style encoder over the action chunk in training, the DETR decoder with `horizon` queries; loss L1 + kl_weight x KL; inference decodes from the zero latent (deterministic).""" name = 'act' backbone_prefix = 'model.backbone.' def __init__(self, cfg: PolicyConfig, init_weights=None): super().__init__(cfg) transformer = Transformer(d_model=cfg.act_hidden_dim, nhead=cfg.nheads, num_encoder_layers=cfg.enc_layers, num_decoder_layers=cfg.dec_layers, dim_feedforward=cfg.dim_feedforward, dropout=cfg.dropout, return_intermediate_dec=False) self.model = DETRVAE(build_backbone(cfg.backbone, hidden_dim=cfg.act_hidden_dim, weights=init_weights), transformer, build_style_encoder(cfg.act_hidden_dim, cfg.nheads, cfg.dim_feedforward, cfg.enc_layers, cfg.dropout), qpos_dim=cfg.state_dim, action_dim=cfg.action_dim, num_queries=cfg.horizon, latent_dim=cfg.latent_dim) self.register_buffer('mean', torch.tensor(IMAGENET_MEAN).view(1, 1, 3, 1, 1), persistent=False) self.register_buffer('std', torch.tensor(IMAGENET_STD).view(1, 1, 3, 1, 1), persistent=False) def compute_loss(self, images, state, action): target = self.action_norm.normalize(action) a_hat, (mu, logvar) = self.model(self.state_norm.normalize(state), (images - self.mean) / self.std, actions=target) l1 = F.l1_loss(a_hat, target) kl = kl_divergence(mu, logvar) return l1 + self.cfg.kl_weight * kl, dict(l1=float(l1.detach()), kl=float(kl.detach())) @torch.no_grad() def predict(self, images, state, generator=None): # noqa: ARG002 - deterministic (zero latent) a_hat, _ = self.model(self.state_norm.normalize(state), (images - self.mean) / self.std) return self.action_norm.unnormalize(a_hat), a_hat POLICIES = {cls.name: cls for cls in (FMDiTPolicy, DPPolicy, ACTPolicy)} LABELS = {'fm_dit': 'FM-DiT', 'dp': 'DP (DDPM-DiT)', 'act': 'ACT'} def build_policy(cfg: PolicyConfig | dict, pretrained: bool = True) -> BasePolicy: """The policy of `cfg`; pretrained=True initializes the backbone from cfg.backbone_weights (training), False builds the same structure with random weights (a checkpoint load, which must not download anything).""" cfg = cfg if isinstance(cfg, PolicyConfig) else PolicyConfig.from_dict(cfg) if cfg.policy not in POLICIES: raise KeyError(f'unknown baseline {cfg.policy!r}; one of {sorted(POLICIES)}') cfg = replace(cfg) # a copy (resolved backbone_norm) return POLICIES[cfg.policy](cfg, init_weights=cfg.backbone_weights if pretrained else None)