# SPDX-License-Identifier: Apache-2.0 """Camera count and flow-matching step count of a served RDT2-FM configuration. Camera count: FIXED at 2 (round 5). The RDT2 model cards define the observation as "Two wrist-camera RGB images (right/left), 384x384" (RDT2-FM README.md:66, RDT2-VQ README.md:58); the paper deploys "a stereo setup using two cameras" (App. D.3); every training sample is one binocular image of the two wrist cameras glued side by side, with no per-camera slot or mask, so another count changes the image geometry the model never saw. ``RDT2_NUM_CAMERAS`` / ``num_cameras`` stay accepted only as 2 (existing launch commands keep working); any other value is refused with :data:`CAMERA_COUNT_REFUSAL`. For a single arm, send a placeholder image for the missing camera (the authors' untested suggestion, thu-ml/RDT2 GitHub Discussion #13). Round 4 also served 1 / 3 / 4 cameras; they were withdrawn in round 5. Step count: ``RDT2_NUM_STEPS`` 1..16, default 5 (``num_inference_timesteps`` of the official config; the authors validated 5), read once at start (or the Python API's ``num_steps``); per request only the prompt bucket changes. The geometry, derived exactly as the official preprocessing does it (thu-ml/RDT2 ``models/rdt_inferencer.py``: ``np.concatenate([obs[cam] for cam in camera_names], axis=1)``, then the Qwen2.5-VL processor's ``smart_resize(factor=28)``): 2 cameras of 384 x 384 are one 384 x 768 image, resized to 392 x 756; the ViT sees 28 x 54 = 1512 patches (window attention over 4 x 4 merged-token windows; 1536 device rows), the LM 378 image tokens. The prompt holds 400 fixed tokens (15 head tokens + 378 image tokens + 7 tail tokens) plus the instruction; the resident buckets 416 / 448 / 512 hold instructions of up to 16 / 48 / 112 tokens. """ from __future__ import annotations import os from dataclasses import dataclass from functools import lru_cache from typing import Mapping, Optional, Tuple import torch from .config import CONFIG V = CONFIG.vision NUM_CAMERAS_RANGE = (2, 2) # fixed: the model card's two wrist cameras (round 5) NUM_STEPS_RANGE = (1, 16) DEFAULT_NUM_CAMERAS = len(CONFIG.proc.camera_names) # 2 CAMERA_COUNT_REFUSAL = ( "RDT2 takes exactly 2 cameras: the model card defines the observation as 'Two wrist-camera RGB images " "(right/left), 384x384', concatenated side by side into one image ([left_stereo, right_stereo]); other camera " "counts change the image the model was trained on and are not supported. For a single arm, send a placeholder " "image for the missing camera (the authors' untested suggestion)") DEFAULT_NUM_STEPS = CONFIG.expert.num_steps # 5 PROMPT_HEAD_TOKENS = 15 # system turn + user header + <|vision_start|> PROMPT_TAIL_TOKENS = 7 # <|vision_end|> ... <|im_end|>\n<|im_start|>assistant\n<|quad_start|> (without instruction) INSTRUCTION_CAPS = (16, 48, 112) CAMERA_HW = (384, 384) # the official per-camera image (deploy / dataset) def _round_up(x: int, m: int) -> int: return -(-int(x) // m) * m def camera_names(n: int = DEFAULT_NUM_CAMERAS) -> Tuple[str, ...]: """The checkpoint's camera order (configs/rdt/post_train.yaml): ``left_stereo``, ``right_stereo``.""" return tuple(CONFIG.proc.camera_names)[:check_num_cameras(n)] @dataclass(frozen=True) class Geometry: """Static image / prompt geometry of the 2-camera input (every number derived from the official preprocessing).""" num_cameras: int camera_names: Tuple[str, ...] camera_hw: Tuple[int, int] image_hw: Tuple[int, int] # smart-resized concatenation (rows, cols) grid: Tuple[int, int] # patch grid (gh, gw) n_patch: int # ViT rows (patches) n_rows: int # padded ViT rows on the device (multiple of 128: the merged rows are whole tiles) n_img: int # image tokens (merged patches) n_merged: int # padded merged rows (n_rows / 4) prompt_fixed_tokens: int # every token of the prompt except the instruction buckets: Tuple[int, ...] # resident prompt buckets @property def grid_thw(self) -> torch.Tensor: return torch.tensor([[1, self.grid[0], self.grid[1]]]) @property def image_start(self) -> int: return PROMPT_HEAD_TOKENS @property def min_valid_keys(self) -> int: """Keys valid in every prompt (head tokens + image tokens): the EXPERT megakernel's chunk bound.""" return PROMPT_HEAD_TOKENS + self.n_img @property def is_default(self) -> bool: return self.num_cameras == DEFAULT_NUM_CAMERAS def max_instruction_tokens(self) -> dict: return {int(L): int(L) - self.prompt_fixed_tokens for L in self.buckets} def as_dict(self) -> dict: return {"num_cameras": self.num_cameras, "camera_names": list(self.camera_names), "camera_hw": list(self.camera_hw), "concatenated_hw": [self.camera_hw[0], self.camera_hw[1] * self.num_cameras], "resized_hw": list(self.image_hw), "patch_grid": list(self.grid), "patches": self.n_patch, "image_tokens": self.n_img, "prompt_fixed_tokens": self.prompt_fixed_tokens, "prompt_buckets": list(self.buckets), "max_instruction_tokens": {str(k): v for k, v in self.max_instruction_tokens().items()}} def check_num_cameras(n) -> int: """2 (or "2") -> 2; anything else raises ValueError with :data:`CAMERA_COUNT_REFUSAL` (fixed camera count).""" if isinstance(n, bool) or not isinstance(n, (int, str)) or not str(n).strip().isdigit(): raise ValueError(f"num_cameras must be 2, got {n!r}. {CAMERA_COUNT_REFUSAL}") n = int(str(n).strip()) if not NUM_CAMERAS_RANGE[0] <= n <= NUM_CAMERAS_RANGE[1]: raise ValueError(f"num_cameras must be 2, got {n}. {CAMERA_COUNT_REFUSAL}") return n def check_num_steps(n) -> int: if isinstance(n, bool) or not isinstance(n, (int, str)) or not str(n).strip().isdigit(): raise ValueError(f"num_steps must be an integer in {NUM_STEPS_RANGE[0]}..{NUM_STEPS_RANGE[1]}, got {n!r}") n = int(str(n).strip()) if not NUM_STEPS_RANGE[0] <= n <= NUM_STEPS_RANGE[1]: raise ValueError(f"num_steps must be in {NUM_STEPS_RANGE[0]}..{NUM_STEPS_RANGE[1]}, got {n}") return n @lru_cache(maxsize=8) def geometry(num_cameras: int = DEFAULT_NUM_CAMERAS) -> Geometry: from .preprocess import smart_resize n = check_num_cameras(num_cameras) ch, cw = CAMERA_HW rh, rw = smart_resize(ch, cw * n, factor=V.patch * V.merge) gh, gw = rh // V.patch, rw // V.patch n_patch = gh * gw n_rows = _round_up(n_patch, 128) n_img = n_patch // (V.merge ** 2) fixed = PROMPT_HEAD_TOKENS + n_img + PROMPT_TAIL_TOKENS buckets = tuple(_round_up(fixed + c, 32) for c in INSTRUCTION_CAPS) return Geometry(num_cameras=n, camera_names=camera_names(n), camera_hw=CAMERA_HW, image_hw=(rh, rw), grid=(gh, gw), n_patch=n_patch, n_rows=n_rows, n_img=n_img, n_merged=n_rows // 4, prompt_fixed_tokens=fixed, buckets=tuple(buckets)) GEOM2 = geometry(DEFAULT_NUM_CAMERAS) # the only geometry (FM and VQ profiles) def config_from_env(env: Optional[Mapping[str, str]] = None) -> Tuple[int, int]: """(num_cameras, num_steps) from RDT2_NUM_CAMERAS / RDT2_NUM_STEPS (unset or empty = the defaults 2 / 5; RDT2_NUM_CAMERAS may only restate 2). Raises ValueError for an unsupported value (never silently replaced).""" env = os.environ if env is None else env nc = (env.get("RDT2_NUM_CAMERAS") or "").strip() or DEFAULT_NUM_CAMERAS ns = (env.get("RDT2_NUM_STEPS") or "").strip() or DEFAULT_NUM_STEPS try: nc = check_num_cameras(nc) except ValueError as e: raise ValueError(f"RDT2_NUM_CAMERAS: {e}") from None try: ns = check_num_steps(ns) except ValueError as e: raise ValueError(f"RDT2_NUM_STEPS: {e}") from None return nc, ns