"""Quick script to sanity-check RLDS actions vs OpenVLA predictions. Usage (example): python scripts/debug_openvla_vs_rlds.py \ --tfrecord /path/to/sem_pour_water_electronics.tfrecord \ --model-ckpt /home/zhao.bai/arena/openvla-oft/runs/arena_single/sem_pour_water_electronics_rlds/openvla-7b-oft-finetuned-libero-spatial+sem_pour_water_electronics+b1+lr-3e-05+lora-r32+dropout-0.0--image_aug--10000_chkpt \ --lora-ckpt /home/zhao.bai/arena/openvla-oft/runs/arena_single/sem_pour_water_electronics_rlds/openvla-7b-oft-finetuned-libero-spatial+sem_pour_water_electronics+b1+lr-3e-05+lora-r32+dropout-0.0--image_aug--10000_chkpt/lora_adapter \ --norm-config /home/zhao.bai/arena/openvla-oft/runs/arena_single/sem_pour_water_electronics_rlds/openvla-7b-oft-finetuned-libero-spatial+sem_pour_water_electronics+b1+lr-3e-05+lora-r32+dropout-0.0--image_aug/config.norm_merge.json \ --unnorm-key sem_pour_water_electronics """ import argparse import json import sys from pathlib import Path import numpy as np import tensorflow as tf # Ensure openvla-oft/prismatic code is importable without pip install. OPENVLA_SRC_DEFAULT = Path("/home/zhao.bai/arena/openvla-oft") if OPENVLA_SRC_DEFAULT.exists(): sys.path.append(str(OPENVLA_SRC_DEFAULT)) sys.path.append(str(Path(__file__).resolve().parents[1])) from VLABench.evaluation.model.policy.openvla import OpenVLA # noqa: E402 def _auto_pick_feature(feature_dict, candidates): for key in candidates: if key in feature_dict: return key return None def _load_example( raw_record, image_key=None, action_key=None, instruction_key=None, ee_key=None, cam_index=2, step_index=0, ): """Parse a single RLDS Example; default assumes fields under `steps/...` and picks a specific step.""" example = tf.train.Example() example.ParseFromString(raw_record.numpy()) feats = example.features.feature feature_names = feats.keys() # Auto-pick keys (prefer RLDS-style names with prefix) image_key = image_key or _auto_pick_feature( feature_names, ["steps/observation/front", "steps/observation/image_0", "steps/observation/image_1", "steps/observation/wrist"], ) action_key = action_key or _auto_pick_feature(feature_names, ["steps/action", "action", "actions"]) instruction_key = instruction_key or _auto_pick_feature( feature_names, ["steps/language_instruction", "language_instruction", "steps/observation/language_instruction"], ) ee_key = ee_key or _auto_pick_feature( feature_names, ["steps/observation/ee_state", "steps/observation/EEF_state", "steps/observation/state_eef", "ee_state"], ) if image_key is None or action_key is None or instruction_key is None: raise ValueError(f"Cannot find required keys. Available: {sorted(feature_names)}") def _get_at(feature, idx): f = feats[feature] if f.bytes_list.value: seq = f.bytes_list.value idx = min(idx, len(seq) - 1) return seq[idx] if f.float_list.value: seq = f.float_list.value return seq if f.int64_list.value: seq = f.int64_list.value return seq return None # Image: use specific timestep if list exists image_raw = _get_at(image_key, step_index) if image_raw is None: raise ValueError(f"No bytes found for image key {image_key}") image = tf.image.decode_image(image_raw).numpy() # Action: may be flattened [T*7]; reshape and pick timestep action_list = _get_at(action_key, step_index) action_arr = np.array(action_list, dtype=np.float32) if action_arr.size % 7 == 0 and action_arr.size >= 7: actions = action_arr.reshape(-1, 7) step_idx = min(step_index, actions.shape[0] - 1) action = actions[step_idx] else: action = action_arr # Instruction: pick step if sequence, else first instr_raw = _get_at(instruction_key, step_index) instruction = instr_raw.decode("utf-8") if isinstance(instr_raw, (bytes, bytearray)) else str(instr_raw) # EE state: may be flattened [T*7/8]; reshape if possible ee_state_list = _get_at(ee_key, step_index) if ee_key else None ee_state_arr = np.array(ee_state_list, dtype=np.float32) if ee_state_list is not None else np.array([]) if ee_state_arr.size in (7, 8): ee_state = ee_state_arr elif ee_state_arr.size % 8 == 0 and ee_state_arr.size > 0: ee_states = ee_state_arr.reshape(-1, 8) step_idx = min(step_index, ee_states.shape[0] - 1) ee_state = ee_states[step_idx] elif ee_state_arr.size % 7 == 0 and ee_state_arr.size > 0: ee_states = ee_state_arr.reshape(-1, 7) step_idx = min(step_index, ee_states.shape[0] - 1) ee_state = ee_states[step_idx] else: ee_state = np.zeros(8, dtype=np.float32) rgb_list = [image] * max(cam_index + 1, 3) obs = {"instruction": instruction, "rgb": rgb_list, "ee_state": ee_state} return obs, action def _first_step(vec, step_dim): """If vec length is multiple of step_dim, reshape to [-1, step_dim] and take first row.""" if vec.size % step_dim == 0 and vec.size >= step_dim: return vec.reshape(-1, step_dim)[0] return vec def main(): parser = argparse.ArgumentParser() parser.add_argument("--tfrecord", required=True, help="Path to RLDS TFRecord file") parser.add_argument("--sample-index", type=int, default=0, help="Which example to test") parser.add_argument("--model-ckpt", required=True, help="OpenVLA base checkpoint") parser.add_argument("--lora-ckpt", required=True, help="OpenVLA LoRA checkpoint") parser.add_argument("--norm-config", required=True, help="Normalization config (config.norm_merge.json)") parser.add_argument("--unnorm-key", default="sem_pour_water_electronics", help="Normalization key") parser.add_argument("--device", default="cuda:0", help="Device for inference") parser.add_argument("--image-key", default=None, help="Override image feature key") parser.add_argument("--action-key", default=None, help="Override action feature key") parser.add_argument("--instruction-key", default=None, help="Override instruction feature key") parser.add_argument("--ee-key", default=None, help="Override ee_state feature key") parser.add_argument("--cam-index", type=int, default=2, help="Camera index used by OpenVLA") parser.add_argument("--save-dir", default=None, help="Optional dir to save decoded image/video") parser.add_argument("--step-index", type=int, default=0, help="Which step within the trajectory to inspect") parser.add_argument("--max-video-frames", type=int, default=10, help="How many frames to dump if saving video") args = parser.parse_args() # Load one example ds = tf.data.TFRecordDataset([args.tfrecord]) raw = None for i, r in enumerate(ds): if i == args.sample_index: raw = r break if raw is None: raise IndexError(f"sample_index {args.sample_index} out of range") obs, gt_action = _load_example( raw, image_key=args.image_key, action_key=args.action_key, instruction_key=args.instruction_key, ee_key=args.ee_key, cam_index=args.cam_index, step_index=args.step_index, ) print(f"[info] Using keys -> image:{args.image_key} action:{args.action_key} instr:{args.instruction_key} ee:{args.ee_key}") print(f"[info] Step index: {args.step_index}") print(f"[info] Ground-truth action shape {gt_action.shape}: {gt_action}") print(f"[info] Instruction: {obs['instruction']}") # Init policy policy = OpenVLA( model_ckpt=args.model_ckpt, lora_ckpt=args.lora_ckpt, norm_config_file=args.norm_config, device=args.device, ) pred_pos, pred_euler, pred_grip = policy.predict(obs, unnorm_key=args.unnorm_key) pred = np.concatenate([pred_pos, pred_euler, [pred_grip[-1]]]) print(f"[info] Predicted action (pos+euler+grip): {pred}") if args.save_dir: out_dir = Path(args.save_dir) out_dir.mkdir(parents=True, exist_ok=True) img_path = out_dir / "sample.jpg" import imageio imageio.imwrite(img_path, obs["rgb"][0]) try: import mediapy # If there are multiple frames in the feature, dump frames starting at step_index. example = tf.train.Example() example.ParseFromString(raw.numpy()) feats = example.features.feature frames = [] img_feat = None for cand in [ "steps/observation/front", "steps/observation/image_0", "steps/observation/image_1", "steps/observation/wrist", args.image_key, ]: if cand and cand in feats: img_feat = feats[cand].bytes_list.value break if img_feat: start = min(args.step_index, len(img_feat) - 1) for b in img_feat[start : start + args.max_video_frames]: frames.append(tf.image.decode_image(b).numpy()) if not frames: frames = [obs["rgb"][0]] * args.max_video_frames mediapy.write_video(out_dir / "sample.mp4", frames, fps=5) except Exception as e: # pragma: no cover - optional print(f"[warn] Failed to write video with mediapy: {e}") print(f"[info] Saved image to {img_path} and video (if available) under {out_dir}") if __name__ == "__main__": main()