File size: 13,949 Bytes
0a3f650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""One frozen dense+phase model, three separately logged execution contracts."""

import json
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Literal

import gymnasium as gym
import mani_skill.envs  # noqa: F401
import numpy as np
import torch
from mani_skill.utils.wrappers import CPUGymWrapper
from pydantic import BaseModel, ConfigDict, PositiveInt
from pydantic_settings import CliApp

from lim.act_policy import build_policy
from lim.action_encoding import sixd_to_controller
from lim.chunk_coordinates import chunk_relative_to_world, world_to_chunk_relative
from lim.chunk_endpoint import check_endpoint_controller
from lim.chunk_phase import chunk_selection
from lim.evaluate_planned_keypose import planning_state, verify_planning_unchanged
from lim.gripper_feedback import (
    FeedbackReaderConfig,
    GripperCompletionConfig,
    PandaGripperFeedback,
)
from lim.keypose_diagnostics import (
    TrainingResetConfig,
    TrainingSceneReset,
    predict_action_chunk,
)
from lim.keypose_phase import read_phase_logits
from lim.planned_keypose import (
    MplibKeyposePlanner,
    PlannedExecutorConfig,
    PlannedKeyposeExecutor,
    PlannerConfig,
)
from lim.reference_act import (
    ReferenceConfig,
    check_policy_checkpoint,
    load_checkpoint,
    load_official,
)


class PhaseChunkEvaluationConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    reference: Path
    """Frozen fixed-anchor phase-supervised dense checkpoint and sensor configuration."""
    output_dir: Path
    """New results directory; never overwrite a previous run."""
    mode: Literal["full", "boundary", "endpoint"]
    """Full30 playback, phase-prefix playback, or planned prefix endpoint."""
    episodes: PositiveInt = 60
    """All consecutive scenes, including failures."""
    seed_start: int = 54000
    """First scene seed."""
    training_dataset: Path | None = None
    """Optional restoration of training initial states only, never labels for control."""
    gripper_completion: GripperCompletionConfig = GripperCompletionConfig()
    """Original planned executor completion contract; playback has no extra dwell."""


def write_row(stream, row):
    stream.write(json.dumps(row, allow_nan=False) + "\n")


def run(config: PhaseChunkEvaluationConfig):
    torch.set_num_threads(4)
    torch.manual_seed(0)
    np.random.seed(0)
    reference = ReferenceConfig.model_validate_json(config.reference.read_text())
    if not (
        reference.policy.chunk_phase_weight > 0
        and reference.policy.method == "chunk_relative"
        and reference.policy.chunk_anchor == "chunk_start_tcp"
        and reference.num_queries == 30
        and reference.control_mode == "pd_ee_delta_pose"
        and not reference.gripper_execution.active
    ):
        raise ValueError("Expected one phase-supervised fixed-anchor Q30 pose6D model")
    checkpoint, provenance = load_checkpoint(reference.checkpoint)
    check_policy_checkpoint(checkpoint, reference)
    module = load_official(reference)
    metadata = json.loads(reference.demonstration_metadata.read_text())
    sensor = metadata["env_info"]["env_kwargs"]["sensor_configs"]
    planned = config.mode == "endpoint"
    control_mode = "pd_joint_pos" if planned else "pd_ee_delta_pose"
    config.output_dir.mkdir(parents=True, exist_ok=False)
    for folder in ("plans", "query_observations"):
        (config.output_dir / folder).mkdir()
    raw = gym.make(
        "StackCube-v1",
        obs_mode="rgb",
        control_mode=control_mode,
        reward_mode="sparse",
        render_mode="rgb_array",
        sim_backend="physx_cpu",
        num_envs=1,
        reconfiguration_freq=1,
        max_episode_steps=200,
        sensor_configs=sensor,
    )
    if config.training_dataset is not None:
        raw = TrainingSceneReset(
            TrainingResetConfig(env=raw, dataset=config.training_dataset)
        )
    env = CPUGymWrapper(
        module.FlattenRGBDObservationWrapper(raw, depth=False),
        ignore_terminations=True,
        record_metrics=True,
    )
    spaces = SimpleNamespace(
        single_observation_space=env.observation_space,
        single_action_space=gym.spaces.Box(-1, 1, (7,), dtype=np.float32),
    )
    records = []
    started = time.time()
    try:
        agent = (
            build_policy(
                module,
                spaces,
                module.args,
                reference.policy,
                checkpoint.get("normalization"),
            )
            .cuda()
            .eval()
        )
        agent.load_state_dict(checkpoint["ema_agent"])
        if not np.isclose(env.unwrapped.control_timestep, 0.05):
            raise ValueError("Expected 20Hz physical playback")
        with (
            (config.output_dir / "predictions.jsonl").open("x") as queries,
            (config.output_dir / "steps.jsonl").open("x") as steps,
            (config.output_dir / "episodes.jsonl").open("x") as episodes,
        ):
            for seed in range(config.seed_start, config.seed_start + config.episodes):
                obs, _ = env.reset(seed=seed)
                base = env.unwrapped
                check_endpoint_controller(
                    base.agent._controller_configs["pd_ee_delta_pose"]["arm"]
                )
                np.testing.assert_allclose(
                    base.agent.robot.pose.raw_pose[0, 3:].cpu().numpy(),
                    [1, 0, 0, 0],
                    atol=1e-5,
                )
                torch.save(
                    {
                        "observation": obs,
                        "cubeA_pose": base.cubeA.pose.raw_pose.cpu(),
                        "cubeB_pose": base.cubeB.pose.raw_pose.cpu(),
                    },
                    config.output_dir / f"initial-{seed}.pt",
                )
                initial_grip = float(
                    np.float32(
                        np.clip((obs["state"][7:9].mean() + 0.01) / 0.05 * 2 - 1, -1, 1)
                    )
                )
                executor = PlannedKeyposeExecutor(
                    PlannedExecutorConfig(
                        initial_gripper=initial_grip,
                        gripper_completion=config.gripper_completion,
                    )
                )
                planner = (
                    MplibKeyposePlanner(PlannerConfig(env=env)) if planned else None
                )
                feedback = (
                    PandaGripperFeedback(
                        FeedbackReaderConfig(
                            env=env, completion=config.gripper_completion
                        )
                    )
                    if planned
                    else None
                )
                query = cursor = consume = failures = 0
                once = False
                world = None
                for step in range(200):
                    before = obs["state"].copy()
                    needs_query = (
                        executor.needs_prediction if planned else cursor == consume
                    )
                    if needs_query:
                        query += 1
                        np.savez_compressed(
                            config.output_dir
                            / f"query_observations/seed{seed}-query{query}.npz",
                            **obs,
                        )
                        chunk = predict_action_chunk(agent, obs)
                        logits = read_phase_logits(agent)[0].detach().cpu()
                        if chunk.shape != (30, 10) or not torch.isfinite(chunk).all():
                            raise ValueError("Expected finite fixed-anchor chunk")
                        selection = chunk_selection(logits, config.mode)
                        consume, cursor = selection["consume_length"], 0
                        world = chunk_relative_to_world(
                            chunk, torch.tensor(before[18:25])
                        )
                        target = world[selection["selected_index"]]
                        prefix_grip = world[: selection["phase_prefix_length"], -1] >= 0
                        row = {
                            "seed": seed,
                            "step": step,
                            "query": query,
                            "state_before": before.tolist(),
                            "relative_chunk": chunk.tolist(),
                            "world_chunk": world.tolist(),
                            "phase_logits": logits.tolist(),
                            **selection,
                            "within_prefix_gripper_sign_changes": int(
                                (prefix_grip[1:] != prefix_grip[:-1]).sum()
                            ),
                            "model_target": target.tolist(),
                            "planning_status": None,
                            "path_steps": 0,
                        }
                        if planned:
                            physical = planning_state(base)
                            plan = planner.plan(target)
                            verify_planning_unchanged(physical, planning_state(base))
                            row["planning_status"] = planner.last_status
                            failures += int(plan is None)
                            if plan is not None:
                                np.savez_compressed(
                                    config.output_dir
                                    / f"plans/seed{seed}-query{query}.npz",
                                    position=plan["position"],
                                    velocity=plan["velocity"],
                                    time=plan["time"],
                                )
                                row["path_steps"] = len(plan["position"])
                            executor.begin(
                                target,
                                None if plan is None else plan["position"],
                                before[:9],
                                source_query=query,
                            )
                        write_row(queries, row)
                    if planned:
                        index = selection["selected_index"]
                        command, details = executor.command(before[18:25])
                    else:
                        index = cursor
                        command = sixd_to_controller(
                            world_to_chunk_relative(
                                world[index], torch.tensor(before[18:25])
                            )
                        ).numpy()
                        cursor += 1
                        details = {"phase": "playback"}
                    obs, _, _, _, info = env.step(command)
                    if planned:
                        measured = feedback.read(float(command[-1]))
                        details["gripper_measurement"] = measured.model_dump(
                            mode="json"
                        )
                        if details["phase"] == "gripper":
                            details["gripper_feedback"] = executor.observe_gripper(
                                measured
                            )
                        details["executor_phase_after"] = executor.phase
                    success = bool(info["success"])
                    once = once or success
                    write_row(
                        steps,
                        {
                            "seed": seed,
                            "step": step,
                            "query": query,
                            "chunk_index": index,
                            "state_before": before.tolist(),
                            "state_after": obs["state"].tolist(),
                            "command": command.tolist(),
                            "success": success,
                            **details,
                        },
                    )
                episode = {
                    "seed": seed,
                    "steps": 200,
                    "success_once": once,
                    "success_at_end": success,
                    "policy_calls": query,
                    "planning_failures": failures,
                    "gripper_timeouts": executor.gripper_timeouts if planned else 0,
                }
                assert once == bool(
                    info["episode"]["success_once"]
                ) and success == bool(info["episode"]["success_at_end"])
                write_row(episodes, episode)
                records.append(episode)
    finally:
        env.close()
    result = {
        "status": "complete",
        "config": config.model_dump(mode="json"),
        "policy": reference.policy.model_dump(mode="json"),
        "provenance": provenance,
        "sensor_configs": sensor,
        "parameters": sum(p.numel() for p in agent.parameters()),
        "control_mode": control_mode,
        "control_hz": 20,
        "episodes": len(records),
        "counts": {
            key: sum(int(r[key]) for r in records)
            for key in ("success_once", "success_at_end")
        },
        "started_epoch": started,
        "ended_epoch": time.time(),
        "scope": "Single frozen EMA; predicted per-action phases only. Fixed-anchor targets, never integrated. No temporal ensemble. Full/boundary use identical per-step TCP conversion; endpoint changes controller/path/feedback too. Horizon truncation is not certified stage completion. Success is recorded only, never a control input.",
    }
    (config.output_dir / "result.json").write_text(
        json.dumps(result, indent=2, allow_nan=False) + "\n"
    )
    print("PHASE_CHUNK_COMPLETE", json.dumps(result), flush=True)


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