Download deploy_package_bottle_v2/deploy.py from EndeavourDD/ditar_re: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/datasets/EndeavourDD/ditar_re/resolve/main/deploy_package_bottle_v2/deploy.py
- Command line
-
hf download hf://datasets/EndeavourDD/ditar_re/deploy_package_bottle_v2/deploy.py
-
curl -L -o deploy.py https://huggingface.co/datasets/EndeavourDD/ditar_re/resolve/main/deploy_package_bottle_v2/deploy.py
14.6 kB
| """Self-contained Franka FR3 deploy script for offline RL knife policy. | |
| This file is part of a portable package — only depends on: | |
| - PyTorch (>= 2.0) | |
| - numpy, Pillow | |
| - The ./agent/ subfolder (sibling) and ./checkpoints/*.pt | |
| - ./smoke_fixtures/knife_ep0_first5.npz (for offline sanity check) | |
| NOT depended on: any code outside this folder, training data, slurm, etc. | |
| === Usage === | |
| 1) One-time setup on the deploy machine: | |
| cd <wherever-you-put-this-folder> | |
| pip install -r requirements.txt | |
| 2) Verify the package works WITHOUT a robot: | |
| python deploy.py --ckpt checkpoints/wantc_best.pt --mode smoke | |
| 3) Real robot run (you wire your Franka SDK into robot_loop_template): | |
| python deploy.py --ckpt checkpoints/wantc_best.pt --mode robot --episodes 20 | |
| === Policy I/O contract === | |
| step(image, state) -> action | |
| image: HxWx3 uint8 (camera frame; will be resized to 84x84 internally; | |
| intended camera = the base/side view, NOT wrist) | |
| state: [8] float32 (Franka FR3: 7 joint angles in rad + 1 gripper width in m) | |
| action: [8] float64 (target joint angles[:7] in rad + target gripper width[7] in m) | |
| - Action is ABSOLUTE joint position target (NOT delta). Franka joint position | |
| controller will track it internally during the 100ms inter-step interval. | |
| - Control loop runs at 10 Hz (data collection frequency). Don't speed up. | |
| """ | |
| from __future__ import annotations | |
| import argparse, sys, time | |
| from pathlib import Path | |
| from typing import Optional | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| # Local imports (agent/ is a sibling folder). | |
| THIS_DIR = Path(__file__).resolve().parent | |
| if str(THIS_DIR) not in sys.path: | |
| sys.path.insert(0, str(THIS_DIR)) | |
| from agent import OfflineDrQV2BCAgent # noqa: E402 | |
| # ===================================================================== | |
| class TemporalEnsembler: | |
| """ACT-style temporal ensembling for action chunks. | |
| At each timestep, the policy predicts a chunk of `chunk_len` future actions. | |
| For the CURRENT timestep we average the predictions made by the current chunk | |
| and the overlapping chunks from previous steps, weighted by recency | |
| w = exp(-m * age) (age 0 = freshest). This smooths motion and cuts compounding | |
| drift. chunk_len=1 => returns the single action unchanged (no ensembling). | |
| NOTE: this exact logic is mirrored in screen_iql.py so the offline self-rollout | |
| drift predicts this deploy behavior. Keep the two in sync. | |
| """ | |
| def __init__(self, chunk_len: int, action_dim: int, m: float = 0.01): | |
| self.K = int(chunk_len); self.A = int(action_dim); self.m = float(m) | |
| self.reset() | |
| def reset(self) -> None: | |
| self.t = 0 | |
| self.chunks = [] # list of (start_t, chunk[K, A]) | |
| def step(self, new_chunk: np.ndarray) -> np.ndarray: | |
| """new_chunk [K, A] predicted at the current timestep -> ensembled action [A].""" | |
| self.chunks.append((self.t, np.asarray(new_chunk))) | |
| self.chunks = [(s, c) for (s, c) in self.chunks if s > self.t - self.K] | |
| acts, ages = [], [] | |
| for s, c in self.chunks: | |
| k = self.t - s | |
| if 0 <= k < self.K: | |
| acts.append(c[k]); ages.append(self.t - s) | |
| acts = np.stack(acts, 0) | |
| w = np.exp(-self.m * np.asarray(ages, dtype=np.float64)); w /= w.sum() | |
| out = (w[:, None] * acts).sum(0) | |
| self.t += 1 | |
| return out | |
| # ===================================================================== | |
| class DeployAgent: | |
| """Real-time inference wrapper for a trained DrQ-v2 + TD3+BC / IQL policy.""" | |
| def __init__(self, ckpt_path: str, device: Optional[str] = None, | |
| frame_stack: int = 3, image_size: int = 84, | |
| deterministic: bool = True): | |
| if device is None: | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| self.device = device | |
| self.frame_stack = frame_stack | |
| self.image_size = image_size | |
| self.deterministic = deterministic | |
| print(f"[deploy] loading ckpt: {ckpt_path}") | |
| ckpt = torch.load(ckpt_path, map_location=device, weights_only=False) | |
| sd = ckpt["state_dict"] | |
| # Action de-normalization stats (per-dim min/max in physical units). | |
| self.action_min = np.asarray(ckpt["action_min"], dtype=np.float32) | |
| self.action_max = np.asarray(ckpt["action_max"], dtype=np.float32) | |
| rng = (self.action_max - self.action_min).copy() | |
| rng[rng < 1e-6] = 1.0 | |
| self.action_range = rng | |
| action_dim = len(self.action_min) | |
| # State normalization stats (baked into ckpt as cpu tensors). | |
| def _to_np(x): | |
| if isinstance(x, torch.Tensor): | |
| return x.detach().cpu().numpy().astype(np.float32) | |
| return np.asarray(x, dtype=np.float32) | |
| state_mean = _to_np(ckpt["state_mean"] if "state_mean" in ckpt else sd["state_mean"]) | |
| state_std = _to_np(ckpt["state_std"] if "state_std" in ckpt else sd["state_std"]) | |
| state_dim = len(state_mean) | |
| # Infer chunk length from the actor output layer (action_dim * chunk_len). | |
| chunk_len = int(sd["actor"]["policy.4.weight"].shape[0] // action_dim) | |
| self.chunk_len = chunk_len | |
| # Reconstruct agent (only image_encoder + actor used at deploy). | |
| self.agent = OfflineDrQV2BCAgent( | |
| image_in_channels=frame_stack * 3, | |
| state_dim=state_dim, action_dim=action_dim, | |
| state_mean=torch.from_numpy(state_mean), | |
| state_std=torch.from_numpy(state_std), | |
| device=device, chunk_len=chunk_len, | |
| ) | |
| # Partial load: encoder + actor ONLY. The critic (and IQL V head) is not | |
| # needed at deploy and may differ in architecture across checkpoints. | |
| self.agent.image_encoder.load_state_dict(sd["image_encoder"]) | |
| self.agent.actor.load_state_dict(sd["actor"]) | |
| self.agent.train(False) | |
| print(f"[deploy] ckpt step={ckpt.get('step','?')} action_dim={action_dim} " | |
| f"state_dim={state_dim} chunk_len={chunk_len} device={device}") | |
| self._frames: Optional[list] = None # initialized on reset() | |
| self._ens = TemporalEnsembler(chunk_len, action_dim, m=0.01) | |
| # ------------------------------------------------------------------ | |
| def reset(self) -> None: | |
| """Call at the start of each episode to reset the frame stack + ensembler.""" | |
| self._frames = None | |
| self._ens.reset() | |
| def _resize_uint8(self, img: np.ndarray) -> np.ndarray: | |
| if img.dtype != np.uint8: | |
| img = img.astype(np.uint8) | |
| if img.shape[0] == self.image_size and img.shape[1] == self.image_size: | |
| return img | |
| return np.asarray(Image.fromarray(img).resize( | |
| (self.image_size, self.image_size), Image.BILINEAR)) | |
| def step(self, image_raw: np.ndarray, state: np.ndarray) -> np.ndarray: | |
| """One inference step. Call once per 100ms control cycle. | |
| Args: | |
| image_raw: [H, W, 3] uint8 — single camera frame this step (any H, W). | |
| MUST be the base/side view (matches training). | |
| state: [8] float — Franka 7 joint angles (rad) + gripper width (m). | |
| Returns: | |
| action: [8] float64 — target_joint_angles[:7] (rad) | |
| + target_gripper_width[7] (m). | |
| Send action[:7] to Franka joint controller and | |
| action[7] to gripper controller. | |
| """ | |
| # 1. resize to 84x84 uint8 | |
| img_small = self._resize_uint8(image_raw) | |
| # 2. update frame stack (oldest first; replicate first frame at reset) | |
| if self._frames is None: | |
| self._frames = [img_small.copy() for _ in range(self.frame_stack)] | |
| else: | |
| # copy: _resize_uint8 may return the caller's array by reference when the | |
| # frame is already 84x84; without copy a reused camera buffer would alias | |
| # all stacked frames -> stack collapses to [t,t,t] -> silent mis-actuation. | |
| self._frames.append(img_small.copy()) | |
| self._frames = self._frames[-self.frame_stack:] | |
| # 3. assemble channel-first obs: | |
| # [t-2 chan 0..2, t-1 chan 0..2, t chan 0..2] | |
| stacked = np.stack(self._frames, axis=0) | |
| obs = stacked.transpose(0, 3, 1, 2).reshape( | |
| self.frame_stack * 3, self.image_size, self.image_size) | |
| obs_t = torch.from_numpy(obs) | |
| state_t = torch.from_numpy(np.asarray(state, dtype=np.float32)) | |
| # 4. predict a chunk of future actions, then temporally ensemble across | |
| # overlapping past chunks -> the action for THIS timestep (chunk_len=1 | |
| # => single action, no ensembling). | |
| chunk = self.agent.act_chunk(obs_t, state_t).detach().cpu().numpy().astype(np.float64) # [K, A] | |
| action_n = self._ens.step(chunk) # [A] | |
| action_n = np.clip(action_n, -1.0, 1.0) | |
| # 5. de-normalize [-1, 1] -> physical | |
| return (action_n + 1.0) * 0.5 * self.action_range + self.action_min | |
| # ===================================================================== | |
| def offline_smoke(ckpt_path: str) -> None: | |
| """No-robot sanity check: replay 5 demo frames + states through the agent, | |
| print per-step action vs demo action L2 error.""" | |
| fixt = next(iter(sorted((THIS_DIR / "smoke_fixtures").glob("*.npz"))), None) | |
| if fixt is None or not fixt.exists(): | |
| print(f"[smoke] no fixture .npz under {THIS_DIR/'smoke_fixtures'}"); sys.exit(2) | |
| print(f"[smoke] fixture: {fixt.name}") | |
| d = np.load(fixt) | |
| frames, states, demo_actions = d["frames"], d["states"], d["demo_actions"] | |
| agent = DeployAgent(ckpt_path) | |
| agent.reset() | |
| print(f"\n[smoke] running {len(frames)} demo frames:") | |
| for i in range(len(frames)): | |
| a = agent.step(frames[i], states[i]) | |
| err = np.linalg.norm(a - demo_actions[i]) | |
| print(f" step {i}: action[:4]={np.round(a[:4],3)} " | |
| f"demo[:4]={np.round(demo_actions[i][:4],3)} L2_err={err:.3f}") | |
| print("\n[smoke] OK — model loads + produces finite actions in valid range.") | |
| print(" L2_err ~0.2 is normal (BC term keeps policy close to demo).") | |
| print(" If you see NaN or |action| > Franka joint limit -> something is wrong.") | |
| # ===================================================================== | |
| def robot_loop_template(ckpt_path: str, n_episodes: int = 20, | |
| max_steps: int = 250, control_hz: float = 10.0) -> None: | |
| """Skeleton for real robot trials. REPLACE the FrankaRobot stub below | |
| with your actual Franka SDK calls. Logs per-episode success rate.""" | |
| agent = DeployAgent(ckpt_path) | |
| # ==================== REPLACE THIS STUB ==================== | |
| class FrankaRobot: | |
| """Replace each method with your Franka SDK (LeRobot, franka-py, | |
| polymetis, frankx, ROS, ...). All five methods must be implemented.""" | |
| def go_home(self) -> None: | |
| """Move arm to home pose at startup. Block until done.""" | |
| print("[robot] go_home (stub)"); time.sleep(0.5) | |
| def reset_episode(self) -> None: | |
| """Per-episode reset: move arm to the start pose used during | |
| data collection (see episode 0, frame 0 in smoke_fixtures), | |
| and wait for human to place knife at the initial position.""" | |
| print("[robot] reset_episode (stub) — place knife at start pose") | |
| time.sleep(0.5) | |
| def get_image(self) -> np.ndarray: | |
| """Return current camera frame as HxWx3 uint8. Use the SIDE view | |
| (base_rgb) — NOT the wrist camera.""" | |
| return np.zeros((256, 256, 3), dtype=np.uint8) | |
| def get_state(self) -> np.ndarray: | |
| """Return current state as float32 array of length 8: | |
| [joint_0, joint_1, ..., joint_6, gripper_width] | |
| All in physical units: rad for joints, meters for gripper.""" | |
| return np.zeros(8, dtype=np.float32) | |
| def send_joint_target(self, q7: np.ndarray, gripper: float) -> None: | |
| """Send a single target. q7 is 7-dim ABSOLUTE joint target (rad). | |
| gripper is target width in meters. Franka joint position controller | |
| will smoothly track the target during the 100ms interval before | |
| the next step().""" | |
| pass | |
| def episode_done(self) -> bool: | |
| """Optional early-termination check. Return True to break the loop.""" | |
| return False | |
| robot = FrankaRobot() | |
| # ============================================================ | |
| successes, period = [], 1.0 / control_hz | |
| robot.go_home() | |
| for ep in range(n_episodes): | |
| print(f"\n=== Episode {ep+1}/{n_episodes} ===") | |
| agent.reset() | |
| robot.reset_episode() | |
| for t in range(max_steps): | |
| loop_t0 = time.time() | |
| img = robot.get_image() | |
| state = robot.get_state() | |
| action = agent.step(img, state) | |
| robot.send_joint_target(action[:7], gripper=float(action[7])) | |
| if robot.episode_done(): | |
| break | |
| elapsed = time.time() - loop_t0 | |
| if elapsed < period: | |
| time.sleep(period - elapsed) | |
| ans = input(f" Episode {ep+1} success? (y/n/skip) ").strip().lower() | |
| if ans == "skip": | |
| continue | |
| successes.append(ans == "y") | |
| print(f" → running SR: {sum(successes)}/{len(successes)} = " | |
| f"{sum(successes)/len(successes):.1%}") | |
| if successes: | |
| print(f"\n=== Final: {sum(successes)}/{len(successes)} = " | |
| f"{sum(successes)/len(successes):.1%} ===") | |
| # ===================================================================== | |
| def main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--ckpt", required=True, | |
| help="Path to ckpt: checkpoints/{wantc,viper,diffrew}_best.pt") | |
| p.add_argument("--mode", choices=["smoke", "robot"], default="smoke", | |
| help="'smoke' = offline sanity check (no robot); " | |
| "'robot' = run real robot loop (replace SDK stub first)") | |
| p.add_argument("--episodes", type=int, default=20) | |
| p.add_argument("--max-steps", type=int, default=250) | |
| args = p.parse_args() | |
| if args.mode == "smoke": | |
| offline_smoke(args.ckpt) | |
| else: | |
| robot_loop_template(args.ckpt, n_episodes=args.episodes, | |
| max_steps=args.max_steps) | |
| if __name__ == "__main__": | |
| main() | |