File size: 5,788 Bytes
b6f2e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause

"""Control loop for gates 2-5 of DEPLOYMENT.md. Implement ``RobotInterface`` for your stack; change
nothing else without a reason you can write down.

    # gate 2 -- shadow: arm is NOT commanded; policy runs on live data, everything is logged
    python deploy/robot_loop_template.py --checkpoint lilawam/stack_v1/real_finetune_from_sim_v1 \
        --mode shadow --seconds 20 --log logs/shadow_000.npz
    python deploy/check_live_log.py logs/shadow_000.npz

    # gate 4 -- first motion: half gain, 1 cm steps, 15 s cap, operator on the e-stop
    python deploy/robot_loop_template.py --checkpoint ... --mode execute --gain-scale 0.5 \
        --max-step 0.01 --seconds 15 --log logs/exec_000.npz

    # gate 5 -- evaluation episodes
    python deploy/robot_loop_template.py --checkpoint ... --mode execute --seconds 60 --log logs/eval_000.npz

Every run writes a step log; run ``check_live_log.py`` on it before the next run.
"""

from __future__ import annotations

import argparse
import sys
import time
from pathlib import Path

import numpy as np

DEPLOY = Path(__file__).resolve().parent
sys.path.insert(0, str(DEPLOY))

from lilawam_deploy import CONTROL_HZ, MAX_STEP_M, RealRobotAdapter, load_policy  # noqa: E402


class RobotInterface:
    """Fill these in for the lab's robot stack. Every method is called once per 10 Hz step.

    Conventions (see DEPLOYMENT.md "Interface"):
      * cameras: 640x480 **RGB** uint8 (convert from BGR if your driver gives OpenCV frames)
      * hand pose: **exactly the reading the teleoperation recordings stored as
        ``robot0_eef_pos`` / ``robot0_eef_quat``** -- measured to be the panda_hand origin
        translation [m] in the robot base frame and the **flange (panda_link8)** orientation, as a
        unit quaternion in **(x, y, z, w)** order. If your driver's end-effector/TCP setting differs
        from the one used while recording, fix the driver, not the adapter; ``check_live_log.py``
        flags a hand z that looks like a tool point.
      * gripper width [m], ~0.08 fully open.
    """

    def read(self) -> dict:
        """-> dict(agentview_raw, wrist_raw, hand_pos, hand_quat_xyzw, gripper_width)."""
        raise NotImplementedError

    def move_tool_by(self, delta_position: np.ndarray) -> None:
        """Move the tool point (0.1034 m ahead of panda_hand along its z) by ``delta_position``
        [m, base frame] within one 10 Hz period, holding the current orientation."""
        raise NotImplementedError

    def gripper(self, open_: bool) -> None:
        """Open, or close on the cube (grasp with moderate force). Only called on a change."""
        raise NotImplementedError

    def stop(self) -> None:
        """Hold position. Called on exit, exception or Ctrl-C."""
        raise NotImplementedError


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--checkpoint", required=True, help="e.g. lilawam/stack_v1/real_finetune_from_sim_v1")
    parser.add_argument("--weights", default=None, help="model.pt (default) or model_final.pt")
    parser.add_argument("--mode", choices=("shadow", "execute"), default="shadow")
    parser.add_argument("--seconds", type=float, default=20.0)
    parser.add_argument("--gain-scale", type=float, default=1.0, help="Multiplies deploy.json's action gain.")
    parser.add_argument("--max-step", type=float, default=MAX_STEP_M, help="Per-step displacement clamp [m].")
    parser.add_argument("--log", required=True, help="Step log path (.npz).")
    parser.add_argument("--server", default=None,
                        help="Cosmos only: URL of deploy/cosmos/cosmos_server.py (else the model runs in-process).")
    args = parser.parse_args()

    policy, spec = load_policy(args.checkpoint, args.weights, server=args.server)
    gain = spec["action"]["gain_m_per_unit"] * args.gain_scale
    adapter = RealRobotAdapter(policy, spec, action_gain=gain, max_step_m=args.max_step, log_path=args.log)
    robot = RobotInterface()
    print(f"{spec['name']}/{spec['_weights']}  obs_frame={spec['obs_frame']}  mode={args.mode}  gain={gain:.4f}"
          f"  max_step={args.max_step}  replan_every={adapter.replan_every}  log={args.log}")
    if args.mode == "execute":
        input("Arm WILL move. Operator on the e-stop, cubes inside the workspace box. Enter to start, Ctrl-C to abort: ")

    period, last_grip = 1.0 / CONTROL_HZ, None
    deadline = time.monotonic() + args.seconds
    try:
        adapter.reset()
        tick = time.monotonic()
        while time.monotonic() < deadline:
            command = adapter.step(**robot.read())
            if command.notes:
                print(f"step {adapter.step_count}: " + "; ".join(command.notes))
            if args.mode == "execute":
                robot.move_tool_by(command.delta_position)
                if command.gripper_open != last_grip:
                    robot.gripper(command.gripper_open)
                    last_grip = command.gripper_open
            tick += period
            now = time.monotonic()
            if now > tick + period:
                # A re-plan took longer than a period (always, for Cosmos): the arm held still meanwhile.
                # Restart the clock rather than firing catch-up steps back to back.
                tick = now
            time.sleep(max(0.0, tick - now))
    finally:
        if args.mode == "execute":
            robot.stop()
        path = adapter.close()
        print(f"step log: {path}\nnext: python deploy/check_live_log.py {path}")


if __name__ == "__main__":
    main()