Download fair-comparison/flow-v1/code/lim/evaluate_phase_chunk.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/evaluate_phase_chunk.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/evaluate_phase_chunk.py
-
curl -L -o evaluate_phase_chunk.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/evaluate_phase_chunk.py
13.9 kB
| """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)) | |