# SPDX-License-Identifier: Apache-2.0 """End-to-end RDT2-FM reference (CPU, fp32 by default), staged exactly like the TT port: host preprocess: cameras -> (392, 756) -> pixel_values (1512, 1176); prompt -> input_ids (L); mRoPE cos/sin VISION : pixel_values -> image embeds (378, 3584) PREFIX (VLM) : embed + scatter image embeds -> layers 0..12 + layer-13 K/V -> K, V (14, 1, 4, L, 128) EXPERT : 5 x RDT forward (14 blocks) with the Euler update -> normalized action (1, 24, 20) host postproc : UMI unnormalize -> action (24, 20) """ from __future__ import annotations from typing import Dict, Optional, Sequence import numpy as np import torch from .config import CONFIG, DEFAULT_DIRS from .expert import ActionExpert, unnormalize_action from .preprocess import mrope_cos_sin, preprocess, vision_geometry from .vision import VisionTower from .vlm import PrefixLM from .weights import load_action_normalizer, load_expert_state_dict, load_vlm_index class RDT2FMReference: def __init__(self, vlm_dir: Optional[str] = None, expert_dir: Optional[str] = None, normalizer_dir: Optional[str] = None, processor_dir: Optional[str] = None, dtype: torch.dtype = torch.float32, load_vision: bool = True, load_lm: bool = True): self.dtype = dtype self.processor_dir = processor_dir or DEFAULT_DIRS["processor"] self.index = load_vlm_index(vlm_dir) self.vision = VisionTower(self.index.load_prefix("visual."), dtype) if load_vision else None if load_vision: self.index.drop("visual.") self.lm = PrefixLM(self.index, CONFIG.lm.selected_layers, dtype=dtype) if load_lm else None self.expert = ActionExpert(load_expert_state_dict(expert_dir), dtype) self.norm = load_action_normalizer(normalizer_dir) def condition(self, inputs: Dict[str, torch.Tensor], taps: Optional[Dict[str, torch.Tensor]] = None): geom = vision_geometry(inputs["image_grid_thw"]) img = self.vision.forward(inputs["pixel_values"], geom, taps) if taps is not None: taps["vis.image_embeds"] = img x = self.lm.embed(inputs["input_ids"], img) if taps is not None: taps["llm.inputs_embeds"] = x cos, sin = mrope_cos_sin(inputs["position_ids"]) K, V = self.lm.forward(x, cos, sin, taps) return K, V @torch.no_grad() def __call__(self, images: Sequence[np.ndarray], instruction: str, state: np.ndarray, noise: torch.Tensor, taps: Optional[Dict[str, torch.Tensor]] = None) -> Dict[str, torch.Tensor]: """images in model order (left_stereo, right_stereo), (384, 384, 3) uint8 each; state (20,); noise (1, 24, 20).""" inputs = preprocess(images, instruction, self.processor_dir) K, V = self.condition(inputs, taps) mask = inputs["attention_mask"].to(torch.bool) a = self.expert.sample(noise, torch.as_tensor(state, dtype=torch.float32), K, V, mask, taps) return dict(inputs=inputs, K=K, V=V, nsample=a, action=unnormalize_action(a, self.norm)[0])