"""Matched single-environment evaluation of frozen reactive and planned keyposes.""" import hashlib import inspect 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, Field, NonNegativeInt, PositiveInt, model_validator, ) from pydantic_settings import CliApp from lim.act_policy import build_policy from lim.chunk_coordinates import chunk_relative_to_world from lim.chunk_endpoint import check_endpoint_controller, dense_chunk_endpoint from lim.gripper_feedback import ( FeedbackReaderConfig, GripperCompletionConfig, PandaGripperFeedback, ) from lim.keypose_control import KeyposeControlConfig, keypose_command from lim.keypose_diagnostics import ( FirstTargetXYZConfig, TrainingFirstTargetXYZ, TrainingResetConfig, TrainingSceneReset, first_target_intervention, nearest_cube_intervention, predict_action_chunk, predict_keypose, ) from lim.keypose_phase import KEYPOSE_PHASE_NAMES, read_phase_logits from lim.keypose_stop import read_stop_logits from lim.planned_keypose import ( MplibKeyposePlanner, PlannedExecutorConfig, PlannedKeyposeExecutor, PlannerConfig, ) from lim.policy_video import PolicyVideo, PolicyVideoConfig from lim.reference_act import ( AuditConfig, ReferenceConfig, ReleasedSupportAudit, check_policy_checkpoint, load_checkpoint, load_official, source_provenance, ) class EvaluationConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) reference: Path = Path("round9/specs/eval-keypose-main.json") """Frozen model and sensor contract; checked against its trained action semantics.""" target_source: Literal[ "keypose", "dense_chunk_endpoint", "chunk_relative_endpoint" ] = "keypose" """Direct query-zero keypose, or nominal endpoint composed from a dense delta chunk.""" mode: Literal["reactive", "planned"] """Fresh prediction each step, or full planned path before each prediction.""" reactive_gripper_gate: bool = True """Reactive only: false directly executes predicted gripper, changing no motion command.""" output_dir: Path """New directory containing every episode, command, prediction and plan.""" episodes: PositiveInt = 60 """Consecutive original ID scenes; no selection or retries.""" seed_start: int = 54000 """First paired scene seed.""" max_steps: PositiveInt = 200 """Physical control steps per scene; non-200 budgets are horizon diagnostics.""" video_seeds: tuple[int, ...] = (54000, 54017) """Selected recordings; the model does not see the observer camera.""" gripper_completion: GripperCompletionConfig = GripperCompletionConfig() """Finger encoder/contact feedback criteria for planned execution completion.""" resume_after_incomplete: bool = False """Keep querying after an unmet gripper command instead of freezing the episode. The original contract has no path back from gripper_timeout: the 27 stalled chunk_relative endpoint episodes spent 2,314 further steps (42.9% of their budget) without a single new query. Default false preserves scored runs. """ carry_gripper_feedback: bool = False """Reuse fresh motion-time gripper stability for an exactly unchanged command.""" phase_gripper_events: bool = False """Use predicted close/open classes to hold the arm and execute the predicted continuous gripper immediately; other classes retain full planned motion.""" motion_replan_steps: NonNegativeInt = 0 """Refresh the target after N actual motion steps; zero executes full paths.""" first_close_hold: bool = False """On the first requested open-to-close transition, hold measured arm joints and execute only the predicted gripper. Context retains the raw request, whose arm pose was bypassed, after gripper feedback completion.""" hold_after_first_release: bool = False """After the first predicted negative-to-nonnegative gripper transition completes its original path and feedback, hold its final command to horizon.""" honor_predicted_stop: bool = False """Consume the checkpoint's stop-after-target prediction only after full execution and feedback; false logs the same logits but continues querying.""" terminal_gripper_event: bool = False """For a predicted terminal target with nonnegative gripper, bypass its arm pose and hold measured joints during the original gripper feedback.""" training_dataset: Path | None = None """Diagnostic only: restore saved training states selected by episode seed.""" first_target_xyz_alpha: float | None = Field( default=None, ge=0, le=1, allow_inf_nan=False ) """Training-scene oracle only: first XYZ = expert + alpha * model residual. None preserves the original path; alpha=1 is an exact identity diagnostic. Rotation, gripper and all later predictions remain the model's outputs. """ first_target_xy: Literal["predicted", "cube_center"] = "predicted" """Diagnostic only: replace first target XY, retaining all other predictions.""" every_target_xy: Literal["predicted", "nearest_cube_center"] = "predicted" """Diagnostic only: replace EVERY target XY with the nearest cube center. Isolates localization precision from phase advancement: height, orientation, continuous gripper and the decision of when to advance remain the model's. """ @property def diagnostic_xy(self): """Number of active privileged-XY interventions; zero for a scored run.""" return int(self.first_target_xy != "predicted") + int( self.every_target_xy != "predicted" ) @model_validator(mode="after") def check_single_intervention(self): if self.terminal_gripper_event and not self.honor_predicted_stop: raise ValueError("Terminal gripper events require predicted-stop execution") if self.honor_predicted_stop and ( self.mode != "planned" or self.target_source != "keypose" or self.hold_after_first_release or self.first_close_hold or self.motion_replan_steps or self.carry_gripper_feedback or self.resume_after_incomplete or self.phase_gripper_events or self.diagnostic_xy or self.first_target_xyz_alpha is not None or not self.reactive_gripper_gate ): raise ValueError("Predicted stop requires an isolated planned context lane") if self.hold_after_first_release and ( self.mode != "planned" or self.target_source != "keypose" or self.first_close_hold or self.motion_replan_steps or self.carry_gripper_feedback or self.resume_after_incomplete or self.phase_gripper_events or self.diagnostic_xy or self.first_target_xyz_alpha is not None or not self.reactive_gripper_gate ): raise ValueError("Release hold requires an isolated planned context lane") if self.first_close_hold and ( self.mode != "planned" or self.target_source != "keypose" or self.motion_replan_steps or self.carry_gripper_feedback or self.resume_after_incomplete or self.phase_gripper_events or self.diagnostic_xy or self.first_target_xyz_alpha is not None or not self.reactive_gripper_gate ): raise ValueError("First-close hold requires an isolated planned lane") if self.motion_replan_steps and ( self.mode != "planned" or self.target_source != "keypose" or self.carry_gripper_feedback or self.resume_after_incomplete or self.phase_gripper_events or self.diagnostic_xy or self.first_target_xyz_alpha is not None or not self.reactive_gripper_gate ): raise ValueError("Motion replanning requires an isolated planned lane") if self.phase_gripper_events and ( self.mode != "planned" or self.target_source != "keypose" or self.carry_gripper_feedback or self.resume_after_incomplete or self.diagnostic_xy or self.first_target_xyz_alpha is not None ): raise ValueError( "Phase gripper events require an isolated planned keypose lane" ) if not self.reactive_gripper_gate and self.mode != "reactive": raise ValueError("Disabling the gripper gate requires reactive execution") if self.carry_gripper_feedback and self.mode != "planned": raise ValueError("Motion feedback carry requires planned execution") if self.diagnostic_xy > 1: raise ValueError( "Choose one XY intervention; combining them confounds the diagnostic" ) if self.first_target_xyz_alpha is not None: if ( self.mode != "planned" or self.target_source != "keypose" or self.training_dataset is None ): raise ValueError( "First XYZ residual diagnostic requires planned keypose and training_dataset" ) if self.diagnostic_xy: raise ValueError( "First XYZ residual diagnostic cannot combine with XY interventions" ) if self.target_source != "keypose" and ( self.mode != "planned" or self.diagnostic_xy or self.training_dataset is not None ): raise ValueError( "Dense endpoint diagnostic uses planned execution without privileged interventions" ) return self def reactive_action(current, target, previous_gripper, control, *, gripper_gate=True): """Apply the original TCP controller, optionally replacing its gripper only.""" command, reached, position_error, rotation_error = keypose_command( current, target, previous_gripper, control ) gated = command[..., -1].clone() requested = target[..., -1].clamp(-1, 1) would_change = bool((gated != requested).item()) if not gripper_gate: command[..., -1] = requested return command, { "phase": "reactive", "reached": bool(reached.item()), "position_error_m": position_error.item(), "rotation_error_rad": rotation_error.item(), "requested_gripper": requested.item(), "gated_gripper": gated.item(), "gate_would_change_gripper": would_change, "gripper_gate_blocked": bool(gripper_gate and would_change), "reactive_gripper_gate": gripper_gate, } def phase_prediction_details(agent): """Read only the latest batch-one prior forward; no environment phase input.""" logits = read_phase_logits(agent).detach().cpu() if ( logits.shape != (1, len(KEYPOSE_PHASE_NAMES)) or not torch.isfinite(logits).all() ): raise ValueError("Expected finite batch-one six-class prior phase logits") return { "phase_logits_prior": logits[0].tolist(), "predicted_phase": int(logits[0].argmax().item()), } def is_gripper_phase(details): """Only the current model argmax selects an event; no ordering or sign rule.""" index = details["predicted_phase"] if index not in range(len(KEYPOSE_PHASE_NAMES)): raise ValueError("Invalid predicted phase") return KEYPOSE_PHASE_NAMES[index] in ("close_gripper", "open_gripper") def with_completed_target(observation, previous): """Encode the prior feedback-completed request; no expert phase is supplied. Normally its arm path executed. The explicit first-close-hold intervention preserves the requested pose despite bypassing it and logs that exception. """ context = np.zeros(11, dtype=np.float32) if previous is not None: value = np.asarray(previous, dtype=np.float32) if value.shape != (10,) or not np.isfinite(value).all(): raise ValueError("Expected a finite completed world keypose10") context[:10], context[10] = value, 1 return {**observation, "completed_target": context} def should_hold_first_close(predicted, executed_gripper, *, already_held): """First closing request after an actual nonnegative actuator command.""" target = torch.as_tensor(predicted) if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected finite raw predicted world keypose10") if executed_gripper is not None and not np.isfinite(executed_gripper): raise ValueError("Expected a finite previously executed gripper command") return bool( not already_held and executed_gripper is not None and executed_gripper >= 0 and target[-1] < 0 ) def is_first_release_request(predicted, executed_gripper, *, already_requested): """A predicted opening follows an actual negative actuator command.""" target = torch.as_tensor(predicted) if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected finite raw predicted world keypose10") if executed_gripper is not None and not np.isfinite(executed_gripper): raise ValueError("Expected a finite previously executed gripper command") return bool( not already_requested and executed_gripper is not None and executed_gripper < 0 and target[-1] >= 0 ) def completed_target_hold_command(command, feedback, *, query, hold_query): """Latch only a physically executed command after the selected feedback completes.""" if ( hold_query is None or query != hold_query or feedback.get("status") != "complete" ): return None result = np.asarray(command, dtype=np.float32).copy() if result.shape != (8,) or not np.isfinite(result).all(): raise ValueError("Expected the finite executed joint/gripper command8") return result def stop_prediction_details(agent): """Read the latest prior forward without another model call or oracle input.""" logits = read_stop_logits(agent).detach().cpu().clone() if logits.shape != (1,) or not torch.isfinite(logits).all(): raise ValueError("Expected one finite stop-after-target logit") return { "stop_logit": float(logits[0]), "stop_probability": float(logits[0].sigmoid()), "stop_after_target": bool(logits[0] >= 0), } def is_terminal_gripper_event(predicted, stop_after_target): """Use only the model's terminal intent and original gripper request.""" target = torch.as_tensor(predicted) if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected finite raw predicted world keypose10") return bool(stop_after_target and target[-1] >= 0) def planning_state(base): """Read physical state without rendering or taking a simulation step.""" return { "qpos": base.agent.robot.get_qpos().detach().cpu().numpy().copy(), "qvel": base.agent.robot.get_qvel().detach().cpu().numpy().copy(), "tcp": base.agent.tcp.pose.raw_pose.detach().cpu().numpy().copy(), "elapsed_steps": torch.as_tensor(base.elapsed_steps).cpu().numpy().copy(), } def verify_planning_unchanged(before, after): if before.keys() != after.keys(): raise ValueError("Planning state fields differ") for key in before: if not np.array_equal(before[key], after[key]): raise RuntimeError(f"Planner dry-run changed physical {key}") return True def executor_trace(executor): """Log active execution separately from the latest (possibly rejected) query.""" return { "goal_id": executor.goal_id, "path_revision": executor.path_revision, "active_target_query": executor.active_query, "completed_target_from_query": executor.completed_target_query, "completed_target": None if executor.completed_target is None else executor.completed_target.tolist(), "completed_goals": executor.completed_goals, "motion_steps_since_attempt": executor.motion_steps_since_attempt, "goal_motion_steps": executor.goal_motion_steps, "total_motion_steps": executor.total_motion_steps, "goal_replan_attempts": executor.goal_replan_attempts, } def run(config: EvaluationConfig): torch.set_num_threads(4) torch.manual_seed(0) np.random.seed(0) config.output_dir.mkdir(parents=True, exist_ok=False) (config.output_dir / "plans").mkdir() if config.motion_replan_steps: (config.output_dir / "query_observations").mkdir() reference = ReferenceConfig.model_validate_json(config.reference.read_text()) context_enabled = reference.policy.keypose_context != "none" stop_enabled = reference.policy.keypose_stop_head if config.honor_predicted_stop and not stop_enabled: raise ValueError( "Predicted stop requires a checkpoint trained with a stop head" ) if stop_enabled and ( config.hold_after_first_release or config.first_close_hold or config.motion_replan_steps ): raise ValueError("Stop-head evaluation cannot combine execution interventions") if config.hold_after_first_release and not context_enabled: raise ValueError("Release hold requires a context-enabled keypose checkpoint") if context_enabled and ( config.mode != "planned" or config.target_source != "keypose" or config.diagnostic_xy or config.first_target_xyz_alpha is not None or config.phase_gripper_events or config.carry_gripper_feedback or config.resume_after_incomplete ): raise ValueError( "Completed goal conditioning requires an isolated planned lane" ) if config.phase_gripper_events and reference.policy.keypose_phase_weight <= 0: raise ValueError( "Phase gripper events require a checkpoint trained with phase outputs" ) dense_endpoint = config.target_source == "dense_chunk_endpoint" relative_endpoint = config.target_source == "chunk_relative_endpoint" if dense_endpoint or relative_endpoint: if not ( reference.policy.keypose is None and reference.policy.method == ("chunk_relative" if relative_endpoint else "cvae") and reference.policy.action_encoding == "rotation6d" and reference.control_mode == "pd_ee_delta_pose" and reference.num_queries == 30 and not reference.gripper_execution.active ): raise ValueError("Expected frozen 30-query dense CVAE pose6D model") elif reference.policy.keypose is None: raise ValueError("Direct keypose evaluation requires a trained keypose model") control = reference.policy.keypose or KeyposeControlConfig() module = load_official(reference) checkpoint, provenance = load_checkpoint(reference.checkpoint) check_policy_checkpoint(checkpoint, reference) first_xyz_oracle = ( TrainingFirstTargetXYZ( FirstTargetXYZConfig( dataset=config.training_dataset, alpha=config.first_target_xyz_alpha ) ) if config.first_target_xyz_alpha is not None else None ) metadata = json.loads(reference.demonstration_metadata.read_text()) sensor = metadata["env_info"]["env_kwargs"]["sensor_configs"] control_mode = "pd_joint_pos" if config.mode == "planned" else "pd_ee_delta_pose" raw = gym.make( "StackCube-v1", obs_mode="rgb", control_mode=control_mode, reward_mode="sparse", render_mode="rgb_array", sim_backend="physx_cpu", reconfiguration_freq=1, max_episode_steps=config.max_steps, sensor_configs=sensor, ) if config.training_dataset is not None: raw = TrainingSceneReset( TrainingResetConfig(env=raw, dataset=config.training_dataset) ) env = ReleasedSupportAudit( AuditConfig( env=raw, snapshots=config.output_dir / "raw_observations", stride=10, seed_start=config.seed_start, ) ) env = PolicyVideo( PolicyVideoConfig( env=env, output_dir=config.output_dir / "videos", seeds=config.video_seeds, label=f"{config.target_source}-{config.mode}", max_steps=config.max_steps, ) ) env = module.FlattenRGBDObservationWrapper(env, depth=False) env = CPUGymWrapper(env, ignore_terminations=True, record_metrics=True) # Build against the checkpoint's original pose controller7, independent of # physical joint ABI8. The policy config distinguishes world poses from deltas. spaces = SimpleNamespace( single_observation_space=env.observation_space, single_action_space=gym.spaces.Box(-1, 1, (7,), dtype=np.float32), ) episodes = [] 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"]) with ( (config.output_dir / "steps.jsonl").open("x") as trace, (config.output_dir / "predictions.jsonl").open("x") as predictions, ): for seed in range(config.seed_start, config.seed_start + config.episodes): obs, _ = env.reset(seed=seed) base = env.unwrapped if dense_endpoint or relative_endpoint: check_endpoint_controller( base.agent._controller_configs["pd_ee_delta_pose"]["arm"] ) if relative_endpoint: 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", ) grip = torch.tensor( [np.clip((obs["state"][7:9].mean() + 0.01) / 0.05 * 2 - 1, -1, 1)], dtype=torch.float32, ) planner = ( MplibKeyposePlanner(PlannerConfig(env=env)) if config.mode == "planned" else None ) executor = PlannedKeyposeExecutor( PlannedExecutorConfig( control=control, gripper_completion=config.gripper_completion, initial_gripper=float(grip.item()), resume_after_incomplete=config.resume_after_incomplete, carry_gripper_feedback=config.carry_gripper_feedback, motion_replan_steps=config.motion_replan_steps, ) ) feedback_reader = ( PandaGripperFeedback( FeedbackReaderConfig( env=env, completion=config.gripper_completion ) ) if planner is not None else None ) calls, failures, plans_completed, gripper_events = 0, 0, 0, 0 previous_command = None first_close_hold_query = None release_query, release_request_step = None, None release_feedback_complete_step, hold_started_step = None, None stop_query, stop_request_step, stop_feedback_complete_step = ( None, None, None, ) terminal_command = None terminal_event_query = None terminal_hold_steps = 0 for step in range(config.max_steps): before = obs["state"].copy() replan = executor.needs_motion_replan if terminal_command is None and ( config.mode == "reactive" or executor.needs_prediction or replan ): if ( config.mode == "planned" and calls and not config.motion_replan_steps ): plans_completed += 1 query_state_before = ( executor_trace(executor) if config.motion_replan_steps else {} ) inference_start = ( time.monotonic() if config.motion_replan_steps else None ) endpoint_details = {} if dense_endpoint: chunk = predict_action_chunk(agent, obs) if chunk.shape != (reference.num_queries, 10): raise ValueError( "Dense checkpoint returned unexpected chunk shape" ) root_pose = base.agent.robot.pose.raw_pose[0].cpu() predicted, decoded = dense_chunk_endpoint( chunk, before[18:25], root_pose ) endpoint_details = { "dense_chunk": chunk.tolist(), "decoded_commands": decoded.tolist(), "robot_root_pose": root_pose.tolist(), "model_target_semantics": "nominal composed endpoint; raw model output is dense_chunk", } elif relative_endpoint: chunk = predict_action_chunk(agent, obs) if chunk.shape != (reference.num_queries, 10): raise ValueError( "Expected a 30x10 fixed-reference chunk" ) anchor = torch.tensor(before[18:25]) predicted = chunk_relative_to_world(chunk[-1], anchor) endpoint_details = { "relative_chunk": chunk.tolist(), "chunk_start_tcp": anchor.tolist(), "selected_query_index": len(chunk) - 1, "model_target_semantics": "query29 restored from its fixed chunk-start TCP; no delta accumulation", } else: model_obs = ( with_completed_target(obs, executor.completed_target) if context_enabled else obs ) predicted = predict_keypose(agent, model_obs) if context_enabled: endpoint_details = { "completed_target_input": model_obs[ "completed_target" ].tolist(), "completed_target_from_query": executor.completed_target_query, "context_mode": reference.policy.keypose_context, } if config.first_close_hold: endpoint_details.update( requested_target_context=model_obs[ "completed_target" ].tolist(), context_semantics="historical_requested_target_after_feedback", context_arm_pose_executed=None if executor.completed_target_query is None else executor.completed_target_query != first_close_hold_query, ) if reference.policy.keypose_phase_weight > 0: endpoint_details = phase_prediction_details(agent) if stop_enabled: endpoint_details.update(stop_prediction_details(agent)) if config.motion_replan_steps: inference_wall_s = time.monotonic() - inference_start observation_path = ( config.output_dir / f"query_observations/seed{seed}-query{calls + 1}.npz" ) np.savez_compressed(observation_path, **model_obs) target = first_target_intervention( predicted, query=calls + 1, cube_xy=base.cubeA.pose.p[0, :2].cpu() if config.first_target_xy == "cube_center" and calls == 0 else None, ) nearest = None if config.every_target_xy == "nearest_cube_center": # Live poses: a perfect localizer would read current state. target, nearest = nearest_cube_intervention( predicted, cubes={ "cubeA": base.cubeA.pose.p[0, :2].cpu(), "cubeB": base.cubeB.pose.p[0, :2].cpu(), }, ) xyz_intervention = None if first_xyz_oracle is not None: target, xyz_intervention = first_xyz_oracle.apply( predicted, query=calls + 1, seed=seed ) calls += 1 prediction = { "seed": seed, "step": step, "query": calls, "target": target.tolist(), "model_target": predicted.tolist(), "first_xy_overridden": config.first_target_xy == "cube_center" and calls == 1, "every_xy_overridden": nearest is not None, "state_before": before.tolist(), **( {"nearest_cube": nearest} if nearest is not None else {} ), **( {"first_xyz_intervention": xyz_intervention} if xyz_intervention is not None else {} ), **endpoint_details, } if stop_enabled: if stop_query is None and prediction["stop_after_target"]: stop_query, stop_request_step = calls, step prediction.update( stop_query=stop_query, stop_request_step=stop_request_step, honor_predicted_stop=config.honor_predicted_stop, ) event = config.phase_gripper_events and is_gripper_phase( endpoint_details ) hold_close = ( config.first_close_hold and should_hold_first_close( predicted, None if previous_command is None else float(previous_command[-1]), already_held=first_close_hold_query is not None, ) ) hold_terminal = ( config.terminal_gripper_event and is_terminal_gripper_event( predicted, prediction["stop_after_target"] ) ) if config.terminal_gripper_event: prediction.update( terminal_gripper_event=hold_terminal, arm_pose_executed=False if hold_terminal else None, ) if config.hold_after_first_release: release_requested = is_first_release_request( predicted, None if previous_command is None else float(previous_command[-1]), already_requested=release_query is not None, ) if release_requested: release_query, release_request_step = calls, step prediction.update( release_requested=release_requested, release_query=release_query, release_request_step=release_request_step, previous_executed_gripper=None if previous_command is None else float(previous_command[-1]), ) if config.first_close_hold: prediction.update( first_close_hold_triggered=hold_close, previous_executed_gripper=None if previous_command is None else float(previous_command[-1]), arm_pose_executed=False if hold_close else None, ) if event or hold_close or hold_terminal: executor.begin_gripper( target, before[:9], source_query=calls ) if hold_close: first_close_hold_query = calls elif hold_terminal: terminal_event_query = calls else: gripper_events += 1 prediction.update( planning_status="first_close_hold" if hold_close else "terminal_gripper_event" if hold_terminal else "gripper_event", planning_wall_s=0.0, path_steps=0, hold_arm_qpos=before[:7].tolist(), ) elif planner is not None: physical_before_plan = ( planning_state(base) if config.motion_replan_steps else None ) start = time.monotonic() plan = planner.plan(target) prediction["planning_wall_s"] = time.monotonic() - start prediction["planning_status"] = planner.last_status failures += int(plan is None) if config.motion_replan_steps: unchanged = verify_planning_unchanged( physical_before_plan, planning_state(base) ) if plan is not None: np.savez_compressed( config.output_dir / f"plans/seed{seed}-query{calls}.npz", position=plan["position"], velocity=plan["velocity"], time=plan["time"], ) prediction["path_steps"] = len(plan["position"]) if replan: accepted = executor.replace_motion_plan( target, None if plan is None else plan["position"], source_query=calls, ) else: executor.begin( target, None if plan is None else plan["position"], before[:9], source_query=calls, ) accepted = plan is not None if config.motion_replan_steps: prediction.update( query_kind="motion_replan" if replan else "goal_start", candidate_target=target.tolist(), accepted=accepted, active_target=executor.target.tolist(), query_state_before=query_state_before, **executor_trace(executor), candidate_path_steps=0 if plan is None else len(plan["position"]), dry_run_state_unchanged=unchanged, inference_wall_s=inference_wall_s, inference_planning_wall_s=inference_wall_s + prediction["planning_wall_s"], deadline_50ms_exceeded=inference_wall_s + prediction["planning_wall_s"] > 0.05, deadline_200ms_exceeded=inference_wall_s + prediction["planning_wall_s"] > 0.2, observation_file=str( observation_path.relative_to(config.output_dir) ), observation_sha256=hashlib.sha256( observation_path.read_bytes() ).hexdigest(), ) if accepted: prediction["first_command_minus_qpos"] = ( executor.path[0] - before[:7] ).tolist() prediction["first_command_minus_previous"] = ( None if previous_command is None else ( executor.path[0] - previous_command[:7] ).tolist() ) # A failed candidate must never become the executed target. target = executor.target.clone() predictions.write(json.dumps(prediction) + "\n") phase_before = executor.phase if terminal_command is not None: command = terminal_command.copy() if hold_started_step is None: hold_started_step = step terminal_hold_steps += 1 details = { "phase": "terminal_hold", "held_command": command.tolist(), } elif planner is None: command_tensor, details = reactive_action( torch.tensor(before[18:25])[None], target[None], grip, control, gripper_gate=config.reactive_gripper_gate, ) command = command_tensor[0].numpy() grip = command_tensor[:, -1].clone() else: command, details = executor.command(before[18:25]) obs, _, terminated, truncated, info = env.step(command) if config.motion_replan_steps and details["phase"] == "trajectory": executor.observe_motion_step() measured_gripper = ( feedback_reader.read( float(command[-1]) if config.carry_gripper_feedback else executor.gripper ) if planner is not None and details["phase"] != "terminal_hold" else None ) if planner is not None and details["phase"] == "gripper": details["gripper_feedback"] = executor.observe_gripper( measured_gripper ) elif ( planner is not None and config.carry_gripper_feedback and details["phase"] == "trajectory" ): details["motion_gripper_feedback"] = ( executor.observe_motion_gripper(measured_gripper) ) if config.motion_replan_steps: details.update( **executor_trace(executor), phase_before=phase_before, phase_after=executor.phase, qpos_before=before[:9].tolist(), qvel_before=before[9:18].tolist(), qvel_after=obs["state"][9:18].tolist(), completion_published=details.get( "gripper_feedback", {} ).get("status") == "complete", ) previous_command = command.copy() if config.first_close_hold: completed_now = ( details.get("gripper_feedback", {}).get("status") == "complete" ) details.update( first_close_hold_query=first_close_hold_query, first_close_hold_active=calls == first_close_hold_query, arm_pose_executed=False if calls == first_close_hold_query else (True if completed_now else None), request_feedback_completed=completed_now, completed_target_from_query=executor.completed_target_query, completed_target_arm_pose_executed=None if executor.completed_target_query is None else executor.completed_target_query != first_close_hold_query, ) previous_command = command.copy() if config.hold_after_first_release: if terminal_command is None: terminal_command = completed_target_hold_command( command, details.get("gripper_feedback", {}), query=calls, hold_query=release_query, ) if terminal_command is not None: release_feedback_complete_step = step details.update( release_query=release_query, release_request_step=release_request_step, release_feedback_complete_step=release_feedback_complete_step, hold_started_step=hold_started_step, terminal_hold_steps=terminal_hold_steps, ) previous_command = command.copy() if stop_enabled: if stop_feedback_complete_step is None: completed_command = completed_target_hold_command( command, details.get("gripper_feedback", {}), query=calls, hold_query=stop_query, ) if completed_command is not None: stop_feedback_complete_step = step if config.honor_predicted_stop: terminal_command = completed_command details.update( stop_query=stop_query, stop_request_step=stop_request_step, stop_feedback_complete_step=stop_feedback_complete_step, hold_started_step=hold_started_step, terminal_hold_steps=terminal_hold_steps, ) if config.terminal_gripper_event: details.update( terminal_event_query=terminal_event_query, terminal_gripper_event_active=calls == terminal_event_query, arm_pose_executed=False if calls == terminal_event_query else None, ) assert not terminated and bool(truncated) == ( step == config.max_steps - 1 ) trace.write( json.dumps( { "seed": seed, "step": step, "query": calls, "target": target.tolist(), "command": command.tolist(), "tcp_before": before[18:25].tolist(), "tcp_after": obs["state"][18:25].tolist(), "qpos_after": obs["state"][:9].tolist(), "success": bool(info["success"]), **details, } ) + "\n" ) row = {k: np.asarray(v).item() for k, v in info["episode"].items()} row.update( seed=seed, audit_release_once=bool(info["audit_release_once"]), audit_release_at_end=bool(info["audit_release_at_end"]), steps=config.max_steps, policy_calls=calls, planning_failures=failures, completed_plans=executor.completed_goals if config.motion_replan_steps else plans_completed + int(planner is not None and executor.needs_prediction), last_phase="terminal_hold" if terminal_hold_steps else executor.phase if planner else "reactive", # Cumulative: resuming clears the phase that used to record it. # With resume disabled a timeout is terminal, so this still # equals the previous 0/1 indicator on every scored run. gripper_timeouts=executor.gripper_timeouts if planner else 0, gripper_arrests=executor.gripper_arrests if planner else 0, ) if config.carry_gripper_feedback: row["gripper_feedback_carried"] = executor.gripper_feedback_carried if config.phase_gripper_events: row["gripper_event_queries"] = gripper_events if config.first_close_hold: row.update( first_close_hold_queries=int( first_close_hold_query is not None ), first_close_hold_query=first_close_hold_query, ) if config.hold_after_first_release: row.update( release_query=release_query, release_request_step=release_request_step, release_feedback_complete_step=release_feedback_complete_step, hold_started_step=hold_started_step, terminal_hold_steps=terminal_hold_steps, held_command=None if terminal_command is None else terminal_command.tolist(), ) if stop_enabled: row.update( stop_query=stop_query, stop_request_step=stop_request_step, stop_feedback_complete_step=stop_feedback_complete_step, honor_predicted_stop=config.honor_predicted_stop, hold_started_step=hold_started_step, terminal_hold_steps=terminal_hold_steps, held_command=None if terminal_command is None else terminal_command.tolist(), ) if config.terminal_gripper_event: row["terminal_event_query"] = terminal_event_query if config.motion_replan_steps: row.update( completed_goals=executor.completed_goals, accepted_paths=executor.accepted_paths, replan_attempts=executor.replan_attempts, replan_failures=executor.replan_failures, total_motion_steps=executor.total_motion_steps, unfinished_path_steps=len(executor.path) - executor.index if executor.phase == "trajectory" else 0, ) episodes.append(row) with (config.output_dir / "episodes.jsonl").open("a") as stream: stream.write(json.dumps(row) + "\n") predictions.flush() trace.flush() print("EPISODE_COMPLETE", json.dumps(row), flush=True) finally: env.close() from mani_skill.examples.motionplanning.base_motionplanner import motionplanner result = { "config": config.model_dump(mode="json"), "provenance": provenance | source_provenance(reference), "policy": reference.policy.model_dump(mode="json"), "sensor_configs": sensor, "control_mode": control_mode, "control_hz": 20, "diagnostic": config.training_dataset is not None or config.first_target_xyz_alpha is not None or config.first_target_xy != "predicted" or config.every_target_xy != "predicted" or config.max_steps != 200 or not config.reactive_gripper_gate or dense_endpoint or relative_endpoint, "pose_control_diagnostics": control.model_dump(mode="json"), "target_semantics": ( "Compose all 30 decoded deltas assuming perfect tracking; only final gripper is retained. " "Intermediate motion and gripper events are discarded, then re-planned by the unchanged executor." if dense_endpoint else ( "Last predicted relative target restored from the fixed chunk-start TCP; only final gripper retained." if relative_endpoint else "Latest query-zero world keypose" ) ), "episodes": len(episodes), "counts": { k: sum(r[k] for r in episodes) for k in ( "success_once", "success_at_end", "audit_release_once", "audit_release_at_end", ) }, "policy_calls": sum(r["policy_calls"] for r in episodes), "planning_failures": sum(r["planning_failures"] for r in episodes), "started_epoch": started, "ended_epoch": time.time(), "planner_source_sha256": hashlib.sha256( Path(inspect.getfile(motionplanner)).read_bytes() ).hexdigest(), "scope": f"Frozen final EMA ({config.target_source}); {config.max_steps} physical steps per scene. Planned: full joint trajectory then measured finger position/velocity or bilateral contact stability. Contact feedback only in executor, no task labels in model inputs or model updates. Timeout holds without replanning; TCP errors diagnostic only. Control20Hz is not fresh-observation policy20Hz." + ( f" Motion-only target updates after {config.motion_replan_steps} actual path steps; latest accepted path completes before gripper feedback. Failed replan retains old target/path/index. Completed context changes only on real feedback completion; unexecuted targets never enter it. No temporal ensemble. Additional inference/planning cost is logged; no continuity or realtime guarantee." if config.motion_replan_steps else "" ) + ( " Historical requested-target context retains the previous raw model request after feedback completion; initially invalid. The first-close-hold request bypasses its arm pose, so that context does not claim the pose executed or was reached. No expert target or phase is supplied." if context_enabled and config.first_close_hold else " Completed-target context comes only from the previous model target after executor completion; initially invalid. The zero-context control masks this input inside its model. No expert target or phase is supplied." if context_enabled else "" ) + ( " First-close hold is an actuator intervention: the first negative gripper request following an actual nonnegative gripper command holds measured joints and applies the unchanged continuous gripper request with native clipping/feedback. The raw requested pose is bypassed, not corrected. Trigger uses no query number, expert phase or task geometry. completed_plans includes this feedback-completed request and does not certify all poses executed." if config.first_close_hold else "" ) + ( " First predicted release after an actual negative gripper command executes its original full path and gripper feedback, then holds the last executed command through the unchanged horizon without further queries. This heuristic does not use task success, certify release, or implement a learned stop. Failure/timeout never enters terminal hold." if config.hold_after_first_release else "" ) + ( " Stop-after-target logits are read from the same zero-latent forward, with fixed probability threshold 0.5. Enabled execution holds the last actual command only after the selected request's declared execution and gripper feedback complete, through the unchanged horizon. Ignored execution records the same prediction without changing commands or queries. Task success, expert phase, and gripper sign never substitute for predicted terminal intent." if stop_enabled else "" ) + ( " A predicted terminal target with a nonnegative gripper request bypasses its arm pose: measured joints are held while the original continuous gripper request is completed by feedback, then the existing stop holds its last command to horizon. This request's raw world pose was not executed, and is never passed into a subsequent query. Completion counts refer to the gripper event, not reaching the bypassed world pose." if config.terminal_gripper_event else "" ) + ( " Privileged first-query XYZ = saved training approach XYZ + alpha * model residual. Rotation, gripper and all subsequent targets remain predicted. Every alpha, including the alpha=1 identity control, is an oracle diagnostic, not learned-policy performance." if first_xyz_oracle is not None else "" ) + ( " Motion-time stable feedback can complete an unchanged gripper command at the final path step; changed commands still require post-path feedback." if config.carry_gripper_feedback else "" ) + ( " Reactive gripper gate disabled: only the gripper scalar is replaced by the clipped model request; arm motion commands are unchanged." if not config.reactive_gripper_gate else "" ) + ( " The current prior-mode phase argmax selects arm hold for close/open events; continuous gripper is still the model prediction. No expert phase, forced stage order, or forced gripper sign. completed_plans counts completed action targets including gripper events." if config.phase_gripper_events else " Phase logits and argmax are diagnostic outputs from the current prior-mode policy forward only; no environment phase labels, target changes or phase-based execution decisions." if reference.policy.keypose_phase_weight > 0 else "" ), } (config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n") print("PLANNED_COMPARISON_COMPLETE", json.dumps(result), flush=True) if __name__ == "__main__": run(CliApp.run(EvaluationConfig))