# SPDX-License-Identifier: Apache-2.0 """Python API of the RDT2-VQ serve profile (``RDT2_MODEL=vq``): the full Qwen2.5-VL-7B of RDT2-VQ emits 27 action tokens autoregressively; the RVQ action tokenizer decodes them to a (24, 20) action chunk. from tt_rdt2.vq.api import RDT2VQ from tt_rdt2.api import load_sample with RDT2VQ.from_pretrained() as model: # weights resolved first, then the device, then warm-up s = load_sample() out = model(s["images"], s["instruction"]) # images (left_stereo, right_stereo), instruction print(out.actions.shape, out.action_tokens, out.valid, out.timing_ms) Same request contract as RDT2-FM (``tt_rdt2.api.RDT2FM``): the same image / instruction validation; ``state`` and ``seed`` are accepted and validated but do not influence the VQ output (the official VQ path takes no proprio state and decodes greedily); ``num_steps`` may only be None or 5 (a flow-matching option, ignored); SERVING.md "RDT2-VQ". Weights (resolved BEFORE the device opens; pinned revisions; local snapshots work offline): * VLM ``robotics-diffusion-transformer/RDT2-VQ`` (ALL 4 shards: vision tower, 28 LM layers, final norm, lm_head), * RVQ tokenizer ``robotics-diffusion-transformer/RVQActionTokenizer`` (``config.json``, ``model.safetensors``), * action normalizer (same file as FM), tokenizer ``Qwen/Qwen2.5-VL-7B-Instruct`` (``tokenizer.json`` only). """ from __future__ import annotations import logging import os import threading import time from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, List, Mapping, Optional import numpy as np from .. import __version__ from ..api import (ACTION_LAYOUT, ACTION_RATE_HZ, ACTION_UNITS, CAMERA_ORDER, CHUNK_SHAPE, COMPONENTS, IMAGE_GRID, NUM_CAMERAS, NUM_STEPS, PROMPT_BUCKETS, PROMPT_FIXED_TOKENS, InputError, _hub_file, check_instruction, check_seed, check_state, decode_images) from ..reference.config import OFFICIAL_CODE, VLM_REPO, VLM_REVISION from ..reference.vq import RVQ_FILES, RVQ_REPO, RVQ_REVISION, VALID_ACTION_LEN log = logging.getLogger("tt_rdt2.vq") # component -> (repo, pinned revision, env override); the VLM file list is the whole index (all shards) VQ_COMPONENTS: Dict[str, Dict[str, Any]] = { "vlm": dict(COMPONENTS["vlm"], files=("config.json", "generation_config.json", "model.safetensors.index.json"), use="Qwen2.5-VL-7B: vision tower, all 28 language-model layers, final norm and lm_head"), "rvq": dict(repo=RVQ_REPO, revision=RVQ_REVISION, env="RDT2_RVQ_DIR", license="apache-2.0", files=RVQ_FILES, use="RVQ action tokenizer (MultiVQVAE decoder: 27 action tokens -> 24 x 20)"), "normalizer": COMPONENTS["normalizer"], "processor": COMPONENTS["processor"], } def vlm_all_files(index_path) -> List[str]: import json with open(index_path) as f: return sorted(set(json.load(f)["weight_map"].values())) def resolve_vq_weights(model_id: Optional[str] = None, revision: Optional[str] = None, *, weights_dirs: Optional[Mapping[str, str]] = None, local_files_only: bool = False, env: Optional[Mapping[str, str]] = None, log_fn=None) -> Dict[str, Dict[str, Any]]: """Every VQ component -> a local directory (no device). Same resolution rules as ``tt_rdt2.api.resolve_weights``.""" env = os.environ if env is None else env weights_dirs = dict(weights_dirs or {}) say = log_fn or log.info out: Dict[str, Dict[str, Any]] = {} for role, c in VQ_COMPONENTS.items(): repo, rev = c["repo"], c["revision"] if role == "vlm": repo = model_id or repo rev = revision or (VLM_REVISION if repo == VLM_REPO else None) or "main" local = weights_dirs.get(role) or env.get(c["env"]) or None if role == "vlm" and not local and model_id and os.path.isdir(model_id): local = model_id files = list(c["files"]) if local: path = Path(local) if role == "vlm": files += vlm_all_files(path / "model.safetensors.index.json") missing = [f for f in files if not (path / f).is_file()] if missing: raise FileNotFoundError(f"{role} weights directory {path} lacks {missing}") source = "local" else: first = _hub_file(repo, files[0], rev, local_files_only) path = Path(first).parent if role == "vlm": files += vlm_all_files(_hub_file(repo, "model.safetensors.index.json", rev, local_files_only)) for f in files[1:]: _hub_file(repo, f, rev, local_files_only) source = "hf-cache" out[role] = dict(repo=repo, revision=rev, path=str(path), files=files, source=source, license=c["license"], use=c["use"]) say(f"Loading weights: {role} {repo}@{str(rev)[:12]} ({source}: {path})") return out @dataclass class VQActionChunk: """One RDT2-VQ action chunk: ``actions`` (24, 20) float32 (UMI-unnormalized, right arm in columns 0..9), the 27 action ids the LM generated, their RVQ codebook tokens, ``valid`` (the official extraction found <|quad_end|> at index 27; otherwise the official fallback of 27 zero ids is decoded, as the official code does).""" actions: np.ndarray actions_normalized: np.ndarray generated: List[int] action_ids: List[int] action_tokens: List[int] valid: bool prompt_bucket: int num_tokens: int timing_ms: Dict[str, float] = field(default_factory=dict) @property def shape(self): return tuple(self.actions.shape) def to_dict(self, include_normalized: bool = False) -> Dict[str, Any]: d: Dict[str, Any] = { "actions": self.actions.astype(np.float32).tolist(), "shape": list(self.actions.shape), "normalized": False, "units": dict(ACTION_UNITS), "action_layout": ACTION_LAYOUT, "chunk": {"horizon": CHUNK_SHAPE[0], "action_dim": CHUNK_SHAPE[1], "rate_hz": ACTION_RATE_HZ}, "prompt_bucket": int(self.prompt_bucket), "num_tokens": int(self.num_tokens), "model_variant": "vq", "tokens": {"generated": [int(t) for t in self.generated], "action_ids": [int(t) for t in self.action_ids], "action_tokens": [int(t) for t in self.action_tokens], "valid": bool(self.valid)}, "timing_ms": {k: round(float(v), 3) for k, v in self.timing_ms.items()}, } if include_normalized: d["actions_normalized"] = self.actions_normalized.astype(np.float32).tolist() return d class RDT2VQ: """RDT2-VQ on one p150. ``model(images, instruction, state=None, seed=None, prompt_bucket=None, num_steps=None)`` -> :class:`VQActionChunk`. Thread-safe (one lock), batch 1.""" MODEL_NAME = "rdt2-base-p150" VARIANT = "vq" DEFAULT_REPO = VLM_REPO DEFAULT_REVISION = VLM_REVISION CAMERA_ORDER = CAMERA_ORDER PROMPT_BUCKETS = PROMPT_BUCKETS CHUNK_SHAPE = CHUNK_SHAPE def __init__(self, tt_model, device, *, weights, owns_device: bool, device_id: Optional[int], log_fn=None): self._m = tt_model self.device = device self.weights = weights self._owns_device = owns_device self.device_id = device_id self._log = log_fn or log.info self._lock = threading.RLock() self._closed = False self.warmup_ms: Dict[int, float] = {} self.capture_s: Optional[float] = None self.processor_dir = weights["processor"]["path"] @classmethod def from_pretrained(cls, model_id: Optional[str] = None, revision: Optional[str] = None, *, device_id: int = 0, device=None, dispatch: str = "eth", engine=None, precision: str = "baseline", weights_dirs: Optional[Mapping[str, str]] = None, local_files_only: bool = False, warmup: bool = True, allow_fallback: bool = False, log_fn=None) -> "RDT2VQ": """Resolve the pinned weights (no device), open the chip (ETH dispatch unless ``dispatch="worker"``), load the programs with every prompt bucket resident and (``warmup``) capture the traces + one call per bucket. ``engine``: only the VISION engine applies (``"vision=ttnn"`` / ``"vision=mk"``, default mk); the PREFIX of the VQ profile is the "fused" engine (prefix=mk is refused).""" from ..tt.model import resolve_engine from ..ttaw.device import close_device, open_device from .model import TRACE_REGION_SIZE, RDT2VQTT say = log_fn or log.info eng = resolve_engine(engine) if eng["prefix"] != "fused": raise ValueError(f"the VQ profile runs the fused PREFIX engine (got prefix={eng['prefix']})") weights = resolve_vq_weights(model_id, revision, weights_dirs=weights_dirs, local_files_only=local_files_only, log_fn=say) owns = device is None if owns: say(f"Opening device {device_id} ({dispatch} dispatch) ...") device = open_device(int(device_id), dispatch=dispatch, num_command_queues=1, trace_region_size=TRACE_REGION_SIZE, allow_fallback=allow_fallback) try: g = device.compute_with_storage_grid_size() say(f"Device open: grid {g.x}x{g.y}; loading RDT2-VQ (vision={eng['vision']}, precision {precision}) ...") tt = RDT2VQTT(device, buckets=PROMPT_BUCKETS, precision=precision, vlm_dir=weights["vlm"]["path"], rvq_dir=weights["rvq"]["path"], normalizer_dir=weights["normalizer"]["path"], processor_dir=weights["processor"]["path"], vision_engine=eng["vision"], rvq_engine=os.environ.get("RDT2_VQ_RVQ", "host"), log=lambda s: say(s)) model = cls(tt, device, weights=weights, owns_device=owns, device_id=int(device_id) if owns else None, log_fn=say) model.precision = precision model.engine = {"vision": eng["vision"], "prefix": "fused", "decode": "ttnn", "rvq": tt.rvq_engine} except BaseException: if owns: close_device(device) raise if warmup: try: model.warmup() except BaseException: model.close() raise return model def warmup(self) -> Dict[int, float]: with self._lock: self._check_open() if self._m.traces.get("decode") is not None and self.warmup_ms: return dict(self.warmup_ms) self._log(f"Warming up: capturing the prefill traces of buckets {list(PROMPT_BUCKETS)} and the decode " "step ...") t0 = time.perf_counter() self._m.capture() self.capture_s = time.perf_counter() - t0 dummy = [np.zeros((384, 384, 3), np.uint8)] * NUM_CAMERAS for L in PROMPT_BUCKETS: self._m(dummy, "warm up", bucket=L) t1 = time.perf_counter() self._m(dummy, "warm up", bucket=L) self.warmup_ms[L] = (time.perf_counter() - t1) * 1e3 self._log(f"Warmup complete in {time.perf_counter() - t0:.1f} s (one call per bucket, ms: " + ", ".join(f"{L}: {v:.1f}" for L, v in self.warmup_ms.items()) + ")") return dict(self.warmup_ms) def tokens_for(self, instruction: str) -> int: from ..reference.preprocess import tokenize return int(tokenize(instruction, 378, self.processor_dir).shape[1]) def validate(self, images: Any, instruction: Any, state: Any = None, seed: Any = None, prompt_bucket: Any = None, num_steps: Any = None) -> Dict[str, Any]: if num_steps is not None and (isinstance(num_steps, bool) or num_steps != NUM_STEPS): raise InputError(f"num_steps is a flow-matching option (RDT2-FM, {NUM_STEPS}); the VQ profile decodes " f"{VALID_ACTION_LEN} action tokens: omit it (got {num_steps!r})") imgs = decode_images(images) instr = check_instruction(instruction) check_state(state) # validated for contract parity; the VQ path takes no proprio state check_seed(seed) # greedy decoding: the seed does not change the output n = self.tokens_for(instr) if n > max(PROMPT_BUCKETS): raise InputError(f"prompt of {n} tokens ({n - PROMPT_FIXED_TOKENS} instruction tokens) exceeds the largest " f"prompt bucket {max(PROMPT_BUCKETS)}; instructions are never truncated") if prompt_bucket is None: L = min(b for b in PROMPT_BUCKETS if b >= n) else: if isinstance(prompt_bucket, bool) or not isinstance(prompt_bucket, (int, np.integer)) \ or int(prompt_bucket) not in PROMPT_BUCKETS: raise InputError(f"prompt_bucket must be one of {list(PROMPT_BUCKETS)}, got {prompt_bucket!r}") L = int(prompt_bucket) if n > L: raise InputError(f"prompt of {n} tokens does not fit prompt_bucket {L}") return {"images": imgs, "instruction": instr, "bucket": L, "n_tokens": n} def __call__(self, images: Any, instruction: Optional[str] = None, state: Any = None, seed: Optional[int] = None, prompt_bucket: Optional[int] = None, num_steps: Optional[int] = None, *, prompt: Optional[str] = None) -> VQActionChunk: t0 = time.perf_counter() if instruction is None: instruction = prompt elif prompt is not None: raise InputError("give either instruction or prompt, not both") if instruction is None: raise InputError("instruction is required") req = self.validate(images, instruction, state, seed, prompt_bucket, num_steps) t1 = time.perf_counter() with self._lock: self._check_open() out = self._m(req["images"], req["instruction"], bucket=req["bucket"]) tm = dict(self._m.timings) t2 = time.perf_counter() timing = {"preprocess": (t1 - t0) * 1e3 + tm.get("host_pre_ms", 0.0), "generate": tm.get("generate_ms", 0.0), "rvq_decode": tm.get("rvq_ms", 0.0), "inference": (t2 - t1) * 1e3 - tm.get("host_pre_ms", 0.0), "total": (time.perf_counter() - t0) * 1e3} return VQActionChunk(actions=out["action"].float().numpy().astype(np.float32).reshape(CHUNK_SHAPE), actions_normalized=out["nsample"].float().numpy().astype(np.float32).reshape(CHUNK_SHAPE), generated=list(out["generated"]), action_ids=out["action_ids"].tolist(), action_tokens=out["action_tokens"].tolist(), valid=bool(out["valid"]), prompt_bucket=req["bucket"], num_tokens=req["n_tokens"], timing_ms=timing) # -------------------------------------------------------------------------------------------- lifetime / info def _check_open(self) -> None: if self._closed: raise RuntimeError("the model is closed") @property def closed(self) -> bool: return self._closed def close(self) -> None: with self._lock: if self._closed: return self._closed = True try: self._m.release() finally: if self._owns_device and self.device is not None: from ..ttaw.device import close_device close_device(self.device) self.device = None def __enter__(self) -> "RDT2VQ": return self def __exit__(self, *exc) -> None: self.close() @property def device_info(self) -> Optional[Dict[str, Any]]: if self.device is None: return None from ..ttaw.device import describe_device return describe_device(self.device, self.device_id) @property def info(self) -> Dict[str, Any]: w = self.weights return { "model": self.MODEL_NAME, "model_variant": "vq", "variant_description": "RDT2-VQ: Qwen2.5-VL-7B emits 27 RVQ action tokens autoregressively (greedy on the " "repetition-penalized logits), decoded by the RVQ action tokenizer", "version": __version__, "weights": {"repo": w["vlm"]["repo"], "revision": w["vlm"]["revision"], "components": {r: {k: v[k] for k in ("repo", "revision", "files", "source", "license", "use")} for r, v in w.items()}}, "engine": dict(getattr(self, "engine", {})), "precision": getattr(self, "precision", "baseline"), "device": self.device_info, "cameras": list(CAMERA_ORDER), "num_cameras": NUM_CAMERAS, "image_geometry": {"layout": "cameras concatenated side by side, left_stereo | right_stereo, then the " "README's JPEG q95 round trip and the slow image processor (PIL bicubic)", "resized_to": list(IMAGE_GRID), "image_tokens": 378}, "decoding": {"strategy": "greedy on the repetition-penalized logits (penalty 1.05, the checkpoint's " "generation_config at temperature 1e-6; ties -> lowest token id)", "action_tokens": VALID_ACTION_LEN, "max_new_tokens": VALID_ACTION_LEN + 1, "jpeg_round_trip": bool(self._m.jpeg)}, "chunk_shape": list(CHUNK_SHAPE), "action_rate_hz": ACTION_RATE_HZ, "action_layout": ACTION_LAYOUT, "units": dict(ACTION_UNITS), "normalized": False, "prompt_buckets": list(PROMPT_BUCKETS), "max_instruction_tokens": {str(L): L - PROMPT_FIXED_TOKENS for L in PROMPT_BUCKETS}, "warmup_ms": {str(k): round(v, 2) for k, v in self.warmup_ms.items()}, "capture_s": None if self.capture_s is None else round(self.capture_s, 2), "load_s": round(float(self._m.timings.get("load_s", 0.0)), 2), "ignored_request_fields": ["state", "seed", "num_steps"], "official_code": {"repo": OFFICIAL_CODE[0], "commit": OFFICIAL_CODE[1], "entry": "utils.batch_predict_action (README RDT2-VQ example)"}, }