File size: 10,922 Bytes
2ba0b15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Replay original joint-space demonstrations with explicit episode boundaries.

Keep ManiSkill's position conversion, and invert its actual CPU Euler controller
for pose conversion. Only initial states are restored; all subsequent observations
are generated by executed actions. Each successful record carries its source ID.
"""

import copy
import hashlib
import json
from collections.abc import Callable
from pathlib import Path
from typing import Any

import gymnasium as gym
import h5py
import mani_skill.envs  # noqa: F401
import numpy as np
import torch
from mani_skill.trajectory.utils.actions.conversion import from_pd_joint_pos
from mani_skill.utils import common
from mani_skill.utils.geometry.rotation_conversions import (
    matrix_to_euler_angles,
    quaternion_to_matrix,
)
from mani_skill.utils.structs.pose import Pose
from mani_skill.utils.wrappers.record import RecordEpisode
from pydantic import BaseModel, ConfigDict, PositiveInt
from pydantic_settings import CliApp

from lim.reference_act import ACTION_DIMENSIONS, ACTControlMode


class PoseReplayConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    source: Path
    """Original joint-position H5, with matching source metadata JSON."""
    output_dir: Path
    """New directory; existing data is never overwritten."""
    control_mode: ACTControlMode = "pd_ee_delta_pose"
    """Target controller, with all camera settings retained from the source."""
    source_ids: tuple[int, ...]
    """Explicit original episode IDs attempted in this declared order."""
    max_substeps: PositiveInt = 4
    """Maximum target-control steps per source action, matching official replay."""
    save_video: bool = False
    """Save observer videos for the pilot; formal data need not record videos."""


class TargetReplayConfig(BaseModel, frozen=True):
    model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
    original: Any
    """Original joint-control environment."""
    target: Any
    """Target pose environment, optionally wrapped for recording."""
    actions: Any
    """Original joint-position demonstration actions."""
    max_substeps: PositiveInt = 4
    """Bounded target-action retries for clipped commands."""
    on_target_step: Callable[[int], None] | None = None
    """Optional observer called after each executed target step with its source action index."""


def pose_target_command(controller, goal_world):
    """Return a bounded command and whether the requested delta was clipped."""
    if (
        controller.config.frame != "root_translation:root_aligned_body_rotation"
        or not controller.config.use_delta
        or controller.config.use_target
        or not controller.config.normalize_action
    ):
        raise ValueError("Expected current-pose-relative normalized root-frame control")
    previous = controller.ee_pose_at_base
    goal = controller.root_link.pose.inv() * goal_world
    low, high = controller.action_space_low[:3], controller.action_space_high[:3]
    pos = 2 * (goal.p - previous.p - low) / (high - low) - 1
    # CPU ManiSkill 3.0.1 applies Euler XYZ *negative* rot_lower, then left-composes.
    delta_rotation = goal.q
    from mani_skill.utils.geometry.rotation_conversions import (
        quaternion_invert,
        quaternion_multiply,
    )

    delta_rotation = quaternion_multiply(delta_rotation, quaternion_invert(previous.q))
    angles = matrix_to_euler_angles(quaternion_to_matrix(delta_rotation), "XYZ")
    rot = angles / controller.config.rot_lower
    norm = torch.linalg.norm(rot, dim=-1, keepdim=True)
    clipped = bool((pos.abs() > 1).any() or (norm > 1).any())
    return torch.cat([pos.clamp(-1, 1), rot / norm.clamp(min=1)], dim=-1), clipped


def replay_targets(config: TargetReplayConfig):
    original = config.original.unwrapped.agent.controller
    target = config.target.unwrapped.agent.controller
    ori_arm, arm = original.controllers["arm"], target.controllers["arm"]
    pin = original.articulation.create_pinocchio_model()
    info = {}
    for source_index, action in enumerate(config.actions):
        action = common.to_tensor(action, device=config.original.unwrapped.device)
        parts = original.to_action_dict(action)
        config.original.step(action)
        qpos = original.articulation.get_qpos().clone()
        qpos[:, ori_arm.active_joint_indices] = ori_arm._target_qpos
        pin.compute_forward_kinematics(qpos.cpu().numpy()[0])
        goal = Pose.create(
            original.articulation.pose.sp * pin.get_link_pose(arm.ee_link.index)
        )
        for _ in range(config.max_substeps):
            command, clipped = pose_target_command(arm, goal)
            out = {**parts, "arm": command[0]}
            _, _, _, _, info = config.target.step(target.from_action_dict(out))
            if config.on_target_step is not None:
                config.on_target_step(source_index)
            if not clipped:
                break
    return info


def tree_first(group):
    return {
        k: tree_first(v) if isinstance(v, h5py.Group) else v[0]
        for k, v in group.items()
    }


def replace_last(destination, source):
    if isinstance(destination, dict):
        for key in destination:
            replace_last(destination[key], source[key])
    else:
        destination[-1] = source[-1]


def run(config: PoseReplayConfig):
    torch.set_num_threads(4)
    config.output_dir.mkdir(parents=True, exist_ok=False)
    metadata = json.loads(config.source.with_suffix(".json").read_text())
    episodes = {e["episode_id"]: e for e in metadata["episodes"]}
    if len(set(config.source_ids)) != len(config.source_ids):
        raise ValueError("Duplicate source IDs")
    env_info = metadata["env_info"]
    kwargs = copy.deepcopy(env_info["env_kwargs"])
    kwargs.update(sim_backend="physx_cpu", num_envs=1, max_episode_steps=200)
    original = gym.make(env_info["env_id"], **kwargs)
    kwargs.update(obs_mode="rgb", control_mode=config.control_mode)
    target = RecordEpisode(
        gym.make(env_info["env_id"], **kwargs),
        output_dir=str(config.output_dir),
        trajectory_name="trajectory",
        save_trajectory=True,
        save_video=config.save_video,
        save_on_reset=False,
        info_on_video=True,
        video_fps=20,
    )
    records = []
    try:
        with h5py.File(config.source) as source:
            for source_id in config.source_ids:
                episode = episodes[source_id]
                if episode["control_mode"] != "pd_joint_pos":
                    raise ValueError("Source must use joint-position expert actions")
                group = source[f"traj_{source_id}"]
                reset = copy.deepcopy(episode["reset_kwargs"])
                # Explicitly clear even FAILED attempts before another reset.
                if target._trajectory_buffer is not None:
                    target.flush_trajectory(save=False)
                if config.save_video:
                    target.flush_video(save=False)
                original.reset(**reset)
                target.reset(**reset)
                initial = tree_first(group["env_states"])
                original.unwrapped.set_state_dict(initial)
                target.unwrapped.set_state_dict(initial)
                initial_obs = target.unwrapped.get_obs()
                replace_last(target._trajectory_buffer.state, common.batch(initial))
                replace_last(
                    target._trajectory_buffer.observation,
                    common.to_numpy(common.batch(initial_obs)),
                )
                if config.save_video:
                    target.render_images = []
                if config.control_mode == "pd_ee_delta_pos":
                    info = from_pd_joint_pos(
                        config.control_mode, group["actions"][:], original, target
                    )
                else:
                    info = replay_targets(
                        TargetReplayConfig(
                            original=original,
                            target=target,
                            actions=group["actions"][:],
                            max_substeps=config.max_substeps,
                        )
                    )
                success = bool(common.to_numpy(info["success"]).item())
                buffer = target._trajectory_buffer
                count = len(buffer.action) - 1
                assert buffer.action.shape[-1] == ACTION_DIMENSIONS[config.control_mode]
                assert len(buffer.observation["extra"]["tcp_pose"]) == count + 1
                record = {
                    "source_episode_id": source_id,
                    "source_episode_seed": episode["episode_seed"],
                    "source_steps": len(group["actions"]),
                    "target_steps": count,
                    "success": success,
                    "output_episode_id": target._episode_id + 1 if success else None,
                    "max_abs_rotation_action": float(
                        np.abs(buffer.action[1:, :, 3:6]).max()
                    )
                    if config.control_mode == "pd_ee_delta_pose"
                    else None,
                }
                target.flush_trajectory(save=success)
                if success:
                    target._json_data["episodes"][-1].update(
                        source_episode_id=source_id,
                        source_episode_seed=episode["episode_seed"],
                    )
                if config.save_video:
                    target.flush_video(name=f"source{source_id}", save=success)
                records.append(record)
                with (config.output_dir / "attempts.jsonl").open("a") as f:
                    f.write(json.dumps(record) + "\n")
                print("REPLAY_EPISODE", json.dumps(record), flush=True)
    finally:
        # Successful data were flushed deliberately; never save residual failures.
        if target._trajectory_buffer is not None:
            target.flush_trajectory(save=False)
        target.close()
        original.close()
    result = {
        "config": config.model_dump(mode="json"),
        "source_sha256": hashlib.sha256(config.source.read_bytes()).hexdigest(),
        "attempted": len(records),
        "successful": sum(r["success"] for r in records),
        "records": records,
        "rotation_encoding": "CPU Euler XYZ inverse including rot_lower sign; radial clipping",
        "state_restoration": "source state0 only; saved initial state and observation repaired before actions",
        "episode_boundary": "flush failed and successful attempts independently",
    }
    (config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n")
    print("REPLAY_COMPLETE", json.dumps(result), flush=True)


if __name__ == "__main__":
    run(CliApp.run(PoseReplayConfig))