| """第6回演習 rollout 補助(robosuite 直接起動、robomimic 不使用)。 |
| |
| 配布 checkpoint(ACT)を robosuite で実行して成功率と動画を返します。 |
| 方策の入力解像度(240×320 の本編 / 96×96 のミニ実験)は checkpoint から自動判別します。 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import os |
|
|
| |
| |
| if "MUJOCO_GL" not in os.environ: |
| try: |
| import torch |
|
|
| os.environ["MUJOCO_GL"] = "egl" if torch.cuda.is_available() else "osmesa" |
| except ImportError: |
| os.environ["MUJOCO_GL"] = "osmesa" |
|
|
| from pathlib import Path |
|
|
| import numpy as np |
|
|
| ENV_NAME = {"lift": "Lift", "can": "PickPlaceCan"} |
| HORIZON = {"lift": 150, "can": 400} |
|
|
| |
| _CONTROLLER = { |
| "type": "BASIC", |
| "body_parts": { |
| "right": { |
| "type": "OSC_POSE", |
| "input_max": 1, "input_min": -1, |
| "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], |
| "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], |
| "kp": 150, "damping": 1, "impedance_mode": "fixed", |
| "kp_limits": [0, 300], "damping_limits": [0, 10], |
| "position_limits": None, "orientation_limits": None, |
| "uncouple_pos_ori": True, "control_delta": True, |
| "interpolation": None, "ramp_ratio": 0.2, |
| "input_ref_frame": "world", |
| "gripper": {"type": "GRIP"}, |
| } |
| }, |
| } |
|
|
|
|
| def _make_env(task: str): |
| import robosuite as suite |
|
|
| return suite.make( |
| ENV_NAME[task], |
| robots=["Panda"], |
| controller_configs=_CONTROLLER, |
| control_freq=20, |
| has_renderer=False, |
| has_offscreen_renderer=True, |
| use_camera_obs=True, |
| camera_names=["agentview", "robot0_eye_in_hand"], |
| camera_heights=240, |
| camera_widths=320, |
| ignore_done=True, |
| reward_shaping=False, |
| use_object_obs=False, |
| ) |
|
|
|
|
| def rollout(ckpt_dir, task: str = "lift", n: int = 10, seed: int = 0, show_video: bool = True): |
| """checkpoint を n エピソード実行して成功率を返します(最初の 1 本は動画表示)。""" |
| import torch |
| from PIL import Image |
| from lerobot.configs.policies import PreTrainedConfig |
| from lerobot.policies.act.modeling_act import ACTPolicy |
| from lerobot.policies.factory import make_pre_post_processors |
|
|
| ckpt_dir = Path(ckpt_dir) |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| policy = ACTPolicy.from_pretrained(ckpt_dir) |
| policy.eval().to(device) |
| cfg = PreTrainedConfig.from_pretrained(ckpt_dir) |
| |
| pre, post = make_pre_post_processors(cfg, pretrained_path=str(ckpt_dir)) |
| |
| |
| policy.config.n_action_steps = min(20, policy.config.n_action_steps) |
| img_hw = tuple(cfg.input_features["observation.images.agentview"].shape[1:3]) |
|
|
| def to_batch(obs): |
| frames = { |
| "agentview": np.flipud(obs["agentview_image"]).copy(), |
| "wrist": np.flipud(obs["robot0_eye_in_hand_image"]).copy(), |
| } |
| if img_hw != (240, 320): |
| frames = { |
| k: np.asarray(Image.fromarray(v).resize(img_hw[::-1], Image.BILINEAR)) |
| for k, v in frames.items() |
| } |
| return { |
| "observation.images.agentview": torch.from_numpy(frames["agentview"]).permute(2, 0, 1).unsqueeze(0).float().to(device) / 255.0, |
| "observation.images.wrist": torch.from_numpy(frames["wrist"]).permute(2, 0, 1).unsqueeze(0).float().to(device) / 255.0, |
| "observation.state": torch.from_numpy(obs["robot0_joint_pos"].astype(np.float32)).unsqueeze(0).to(device), |
| } |
|
|
| env = _make_env(task) |
| rng = np.random.default_rng(seed) |
| results = [] |
| video_frames = [] |
| for k in range(n): |
| np.random.seed(int(rng.integers(0, 2**31 - 1))) |
| env.reset() |
| policy.reset() |
| obs = env._get_observations(force_update=True) |
| success = False |
| for _ in range(HORIZON[task]): |
| with torch.no_grad(): |
| action = post(policy.select_action(pre(to_batch(obs)))) |
| obs, _, _, _ = env.step(action.squeeze(0).cpu().numpy()) |
| if k == 0: |
| video_frames.append(np.flipud(obs["agentview_image"]).copy()) |
| success = success or env._check_success() |
| if success: |
| break |
| results.append(bool(success)) |
| print(f"rollout {k + 1}/{n}: {'成功' if success else '失敗'}") |
| env.close() |
|
|
| rate = float(np.mean(results)) |
| print(f"\n成功率: {sum(results)}/{n} = {rate:.0%}") |
| if show_video and video_frames: |
| from IPython.display import Video, display |
|
|
| import utils |
|
|
| utils.save_mp4(video_frames, "rollout_first.mp4", fps=20) |
| display(Video("rollout_first.mp4", embed=True, width=400)) |
| return rate |
|
|
|
|
| def rollout_once(ckpt_dir, horizon: int = 400, seed: int = 0): |
| """後方互換: can で 1 エピソードだけ実行します。""" |
| return rollout(ckpt_dir, task="can", n=1, seed=seed) |
|
|