File size: 15,245 Bytes
6b79146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""FastWAM policy server for the stack_cube_eef (end-effector) checkpoint.

Same robot, same wire protocol, different action space. The pick_red model in
serve.py predicts joint angles, so its actions go straight to the controllers.
This checkpoint predicts dual-arm EEF poses, which the G1 cannot execute:
g1_client/arm_controller.py only accepts 14 joint targets, and the client can
only *measure* joints (main_openpi.py builds state from arm.get_arm_q()).

Rather than push kinematics onto the robot-side client — which is deliberately
torch-free and would then need pinocchio plus a matching URDF — this server owns
both conversions, so the wire format stays byte-identical to serve.py and the
existing client runs unmodified:

    client                     server
    ------                     ------
    joint state (16)  ---->    FK  -> EEF state (16) -> normalize -> model
    joint actions     <----    IK  <- EEF actions [H,16] <- denormalize

The FK/IK model is a mirror of openpi-fintune/scripts/joint_to_eef.py, which is
what generated the training data: a pinocchio reduced 14-DoF model with 'L_ee'/
'R_ee' frames on the wrist-yaw joints at +0.05 m along x, poses in the pelvis
frame, waist/legs/fingers locked at zero. Any drift between that converter and
this file silently biases every action, so the constants below are duplicated
verbatim on purpose rather than re-derived.

Extra setup beyond serve.py's (pinocchio is not in the fastwam env):
    conda activate fastwam
    pip install pin

Usage (from the FastWAM/ directory):
  python serve_stack_cube_eef.py \\
      --config     runs/stack_cube_eef_1e-4/<run>/config.yaml \\
      --ckpt       runs/stack_cube_eef_1e-4/<run>/checkpoints/weights/step_XXXXXX.pt \\
      --norm-stats runs/stack_cube_eef_1e-4/<run>/dataset_stats.json \\
      --port 8000

`--action-space eef` / `--state-space eef` disable the respective conversion and
pass raw EEF through, for a client that does its own kinematics.
"""

import argparse
import logging
import sys
from pathlib import Path

import numpy as np

FASTWAM_ROOT = Path(__file__).resolve().parent
if str(FASTWAM_ROOT) not in sys.path:
    sys.path.insert(0, str(FASTWAM_ROOT))

from serve import FastWAMModel, _serve  # noqa: E402  (path setup must precede)

log = logging.getLogger("g1_fastwam.serve_eef")

# --- verbatim from openpi-fintune/scripts/joint_to_eef.py --------------------
# The dataset's EEF definition. Changing anything here without regenerating the
# dataset makes the policy's inputs and outputs mean something different.
ARM_JOINT_NAMES = [
    "left_shoulder_pitch_joint", "left_shoulder_roll_joint",
    "left_shoulder_yaw_joint", "left_elbow_joint", "left_wrist_roll_joint",
    "left_wrist_pitch_joint", "left_wrist_yaw_joint",
    "right_shoulder_pitch_joint", "right_shoulder_roll_joint",
    "right_shoulder_yaw_joint", "right_elbow_joint", "right_wrist_roll_joint",
    "right_wrist_pitch_joint", "right_wrist_yaw_joint",
]
EE_OFFSET = 0.05  # meters along x of the wrist yaw frame (same as G1_29_ArmIK)

_DEFAULT_ASSETS = (FASTWAM_ROOT.parent / "pi" / "openpi-fintune" / "scripts"
                   / "assets" / "g1")
DEFAULT_URDF = str(_DEFAULT_ASSETS / "g1_body29_hand14.urdf")
DEFAULT_ASSETS = str(_DEFAULT_ASSETS)


class G1ArmKinematics:
    """FK and damped-least-squares IK on the 14-DoF dual-arm reduced model.

    FK is the exact inverse of what produced the dataset. IK is a Levenberg-
    Marquardt CLIK over both arms at once (12-D stacked task error): the two
    arms are kinematically decoupled once the waist is locked, but solving them
    jointly keeps one convergence test and one iteration budget for the pair.
    """

    def __init__(self, urdf_path=DEFAULT_URDF, assets_dir=DEFAULT_ASSETS,
                 ik_max_iters=60, ik_tol=1e-4, ik_damping=1e-6, ik_dt=1.0):
        import pinocchio as pin
        self._pin = pin

        robot = pin.RobotWrapper.BuildFromURDF(urdf_path, assets_dir)
        lock_names = [n for n in robot.model.names[1:] if n not in ARM_JOINT_NAMES]
        reduced = robot.buildReducedRobot(
            list_of_joints_to_lock=lock_names,
            reference_configuration=np.zeros(robot.model.nq),
        )
        model = reduced.model
        if model.nq != 14:
            raise RuntimeError(f"expected 14-dof reduced model, got nq={model.nq}")
        model.addFrame(pin.Frame(
            "L_ee", model.getJointId("left_wrist_yaw_joint"), 0,
            pin.SE3(np.eye(3), np.array([EE_OFFSET, 0, 0])), pin.FrameType.OP_FRAME))
        model.addFrame(pin.Frame(
            "R_ee", model.getJointId("right_wrist_yaw_joint"), 0,
            pin.SE3(np.eye(3), np.array([EE_OFFSET, 0, 0])), pin.FrameType.OP_FRAME))

        self.model = model
        self.data = model.createData()
        self.frame_ids = (model.getFrameId("L_ee"), model.getFrameId("R_ee"))
        # dataset column i -> position in the pinocchio q vector
        self.q_index = np.array(
            [model.joints[model.getJointId(n)].idx_q for n in ARM_JOINT_NAMES])
        self.q_lower = model.lowerPositionLimit[self.q_index].copy()
        self.q_upper = model.upperPositionLimit[self.q_index].copy()

        self.ik_max_iters = int(ik_max_iters)
        self.ik_tol = float(ik_tol)
        self.ik_damping = float(ik_damping)
        self.ik_dt = float(ik_dt)

    # ---- FK: joint (16) -> EEF (16) ----------------------------------------

    def fk16(self, joints16: np.ndarray) -> np.ndarray:
        """[14 joints, 2 grippers] -> [L xyz+quat, R xyz+quat, 2 grippers].

        Quaternions are canonicalized to qw >= 0. The dataset converter chained
        signs frame-by-frame (fix_quat_continuity), which left every episode on
        the positive-qw cover (stats.json: qw in [0.816, 1.0]); a single-frame
        FK has no predecessor to chain from, so it must pick that cover
        explicitly or half the states land on the wrong side of the normalizer.
        """
        pin = self._pin
        q = np.zeros(self.model.nq)
        q[self.q_index] = np.asarray(joints16, dtype=np.float64)[:14]
        pin.framesForwardKinematics(self.model, self.data, q)

        out = np.empty(16, dtype=np.float32)
        for k, fid in enumerate(self.frame_ids):
            xyzquat = pin.SE3ToXYZQUAT(self.data.oMf[fid])  # [x,y,z,qx,qy,qz,qw]
            if xyzquat[6] < 0:
                xyzquat[3:7] = -xyzquat[3:7]
            out[7 * k:7 * (k + 1)] = xyzquat
        out[14:] = np.asarray(joints16, dtype=np.float32)[14:]
        return out

    # ---- IK: EEF (16) -> joint (16) ----------------------------------------

    def _to_se3(self, pose7: np.ndarray):
        """[x,y,z,qx,qy,qz,qw] -> SE3, tolerating a non-unit predicted quat."""
        pin = self._pin
        quat = np.asarray(pose7[3:7], dtype=np.float64)
        norm = np.linalg.norm(quat)
        if norm < 1e-8:
            raise ValueError(f"degenerate predicted quaternion: {pose7[3:7]}")
        quat = quat / norm
        rot = pin.Quaternion(quat[3], quat[0], quat[1], quat[2]).matrix()  # (w,x,y,z)
        return pin.SE3(rot, np.asarray(pose7[0:3], dtype=np.float64))

    def ik_single(self, eef16, q_warm14):
        """One EEF pose pair -> 14 joints, warm-started from q_warm14.

        Returns (joints14, residual_norm). The 7-DoF arms are redundant, so the
        warm start is what picks the branch: seeded from the robot's measured
        pose and then chained down the chunk, consecutive solutions stay in the
        same elbow configuration instead of flipping mid-trajectory.
        """
        pin = self._pin
        targets = [self._to_se3(eef16[0:7]), self._to_se3(eef16[7:14])]

        q = np.zeros(self.model.nq)
        q[self.q_index] = np.asarray(q_warm14, dtype=np.float64)

        err = np.zeros(12)
        jac = np.zeros((12, self.model.nv))
        for _ in range(self.ik_max_iters):
            pin.framesForwardKinematics(self.model, self.data, q)
            for k, (fid, target) in enumerate(zip(self.frame_ids, targets)):
                iMd = self.data.oMf[fid].actInv(target)
                err[6 * k:6 * k + 6] = pin.log(iMd).vector
                jf = pin.computeFrameJacobian(self.model, self.data, q, fid, pin.LOCAL)
                jac[6 * k:6 * k + 6] = -pin.Jlog6(iMd.inverse()) @ jf
            if np.linalg.norm(err) < self.ik_tol:
                break
            vel = -jac.T @ np.linalg.solve(
                jac @ jac.T + self.ik_damping * np.eye(12), err)
            q = pin.integrate(self.model, q, vel * self.ik_dt)
            q[self.q_index] = np.clip(q[self.q_index], self.q_lower, self.q_upper)

        return q[self.q_index].copy(), float(np.linalg.norm(err))

    def ik_chunk(self, eef_actions: np.ndarray, q_start14: np.ndarray) -> np.ndarray:
        """[H,16] EEF actions -> [H,16] joint actions (grippers passed through)."""
        out = np.empty((len(eef_actions), 16), dtype=np.float32)
        q_warm = np.asarray(q_start14, dtype=np.float64)
        worst = 0.0
        for t, action in enumerate(eef_actions):
            q_warm, residual = self.ik_single(action, q_warm)
            out[t, :14] = q_warm
            out[t, 14:] = action[14:]
            worst = max(worst, residual)
        if worst > 1e-2:
            # Unreachable or badly-conditioned target: the arm will track the
            # closest pose it can, which is silent divergence unless flagged.
            log.warning("IK residual %.4f over chunk (tol %.1e) — target likely "
                        "unreachable; joints are a least-squares fit, not exact.",
                        worst, self.ik_tol)
        return out


class EEFFastWAMModel(FastWAMModel):
    """FastWAMModel with joint<->EEF conversion wrapped around infer().

    Everything about the model itself — image concat geometry, normalizer,
    sampler settings — is inherited unchanged; only the meaning of the state in
    and the actions out differs.
    """

    def __init__(self, *args, kinematics=None, state_space="joint",
                 action_space="joint", **kwargs):
        super().__init__(*args, **kwargs)
        self.kinematics = kinematics
        self.state_space = state_space
        self.action_space = action_space
        if (state_space == "joint" or action_space == "joint") and kinematics is None:
            raise ValueError("joint state/action space requires a G1ArmKinematics")
        log.info("EEF server ready | state_space=%s | action_space=%s",
                 state_space, action_space)

    def metadata(self) -> dict:
        meta = super().metadata()
        meta.update({
            "model": "fastwam-eef",
            "model_action_space": "eef",   # what the checkpoint predicts
            "state_space": self.state_space,    # what the client should send
            "action_space": self.action_space,  # what the client will receive
        })
        return meta

    def infer(self, obs: dict) -> dict:
        state_raw = np.asarray(obs["state"], dtype=np.float32)
        if state_raw.shape != (16,):
            raise ValueError(f"expected 16-dim state, got {state_raw.shape}")

        if self.state_space == "joint":
            joints14 = state_raw[:14].astype(np.float64)
            model_state = self.kinematics.fk16(state_raw)
        else:
            joints14 = None
            model_state = state_raw

        result = super().infer({**obs, "state": model_state})
        eef_actions = result["actions"]  # [H, 16] raw EEF (denormalized upstream)

        if self.action_space == "eef":
            return {"actions": eef_actions}
        return {"actions": self.kinematics.ik_chunk(eef_actions, joints14)}


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--config", required=True,
                   help="Run config.yaml (run_dir/config.yaml).")
    p.add_argument("--ckpt", required=True, help="FastWAM checkpoint .pt to serve.")
    p.add_argument("--norm-stats", required=True,
                   help="dataset_stats.json paired with the checkpoint. Must be "
                        "the EEF run's stats — pick_red's are joint-space and "
                        "would denormalize into nonsense.")
    p.add_argument("--client-root", default=str(FASTWAM_ROOT.parent / "g1-client"),
                   help="Path to the g1-client repo, for the shared wire codec.")
    p.add_argument("--host", default="0.0.0.0")
    p.add_argument("--port", type=int, default=8000)
    p.add_argument("--device", default="cuda")
    p.add_argument("--mixed-precision", default="bf16", choices=["no", "fp16", "bf16"])
    p.add_argument("--action-horizon", type=int, default=None)
    p.add_argument("--num-inference-steps", type=int, default=None)
    p.add_argument("--seed", type=int, default=None)
    p.add_argument("--state-space", default="joint", choices=["joint", "eef"],
                   help="What the client sends. 'joint' (default) runs FK here.")
    p.add_argument("--action-space", default="joint", choices=["joint", "eef"],
                   help="What the client receives. 'joint' (default) runs IK here.")
    p.add_argument("--urdf", default=DEFAULT_URDF)
    p.add_argument("--assets", default=DEFAULT_ASSETS)
    p.add_argument("--ik-max-iters", type=int, default=60)
    p.add_argument("--ik-tol", type=float, default=1e-4)
    p.add_argument("--ik-damping", type=float, default=1e-6)
    args = p.parse_args()

    client_root = str(Path(args.client_root).expanduser().resolve())
    if client_root not in sys.path:
        sys.path.insert(0, client_root)
    try:
        from g1_client.msgpack_numpy import Packer, unpackb
    except ImportError as e:
        raise SystemExit(
            f"Could not import g1_client.msgpack_numpy from --client-root={client_root!r}: {e}\n"
            "Point --client-root at the g1-client repo so client and server share one wire codec."
        )

    kinematics = None
    if args.state_space == "joint" or args.action_space == "joint":
        if not Path(args.urdf).exists():
            raise SystemExit(f"URDF not found: {args.urdf}\nPass --urdf/--assets.")
        try:
            kinematics = G1ArmKinematics(
                urdf_path=args.urdf, assets_dir=args.assets,
                ik_max_iters=args.ik_max_iters, ik_tol=args.ik_tol,
                ik_damping=args.ik_damping,
            )
        except ImportError as e:
            raise SystemExit(
                f"pinocchio is required for joint<->EEF conversion: {e}\n"
                "Install it into the fastwam env (`pip install pin`), or run with "
                "--state-space eef --action-space eef to do kinematics client-side."
            )
        log.info("Loaded G1 kinematics from %s", args.urdf)

    model = EEFFastWAMModel(
        config_path=args.config, checkpoint_path=args.ckpt,
        norm_stats_path=args.norm_stats, device=args.device,
        mixed_precision=args.mixed_precision, action_horizon=args.action_horizon,
        num_inference_steps=args.num_inference_steps, seed=args.seed,
        kinematics=kinematics, state_space=args.state_space,
        action_space=args.action_space,
    )
    _serve(model, args.host, args.port, Packer, unpackb)


if __name__ == "__main__":
    main()