"""Explicit, logged interventions for frozen keypose diagnostics only.""" import hashlib import json from pathlib import Path from typing import Any import gymnasium as gym import h5py import numpy as np import torch from pydantic import BaseModel, ConfigDict, Field def predict_action_chunk(agent, observation): """Batch-one inference, including the checkpoint's native denormalization.""" with torch.inference_mode(): inputs = { k: torch.as_tensor(v, device="cuda")[None] for k, v in observation.items() } return agent.get_action(inputs)[0].cpu() def predict_keypose(agent, observation): """The same batch-one/query-zero entrypoint for probes and closed-loop runs.""" return predict_action_chunk(agent, observation)[0] def first_target_intervention(predicted, *, query, cube_xy=None): """Privileged XY only, on query one only; never mutate raw model output.""" target = predicted.clone() if cube_xy is not None: if query != 1: raise ValueError("First-target diagnostic must not affect later queries") xy = torch.as_tensor(cube_xy, dtype=target.dtype) if xy.shape != (2,) or not torch.isfinite(xy).all(): raise ValueError("Expected finite cube center XY") target[:2] = xy return target class FirstTargetXYZConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) dataset: Path """Annotated training H5 whose adjacent JSON maps seed to episode_id.""" alpha: float = Field(ge=0, le=1, allow_inf_nan=False) """Retained fraction of first predicted XYZ residual relative to expert XYZ.""" class TrainingFirstTargetXYZ: """First-query oracle intervention; never a phase selector or model input.""" def __init__(self, config: FirstTargetXYZConfig): self.config = config metadata_path = config.dataset.with_suffix(".json") metadata_bytes = metadata_path.read_bytes() metadata = json.loads(metadata_bytes) self.episodes = {e["episode_seed"]: e for e in metadata["episodes"]} if len(self.episodes) != len(metadata["episodes"]): raise ValueError("Ambiguous training scene seeds") with config.dataset.open("rb") as stream: dataset_hash = hashlib.file_digest(stream, "sha256").hexdigest() self.source = { "dataset": str(config.dataset.resolve()), "dataset_sha256": dataset_hash, "metadata": str(metadata_path.resolve()), "metadata_sha256": hashlib.sha256(metadata_bytes).hexdigest(), } def apply(self, predicted, *, query, seed): if query < 1: raise ValueError("Expected a positive query index") target = predicted.clone() # Later decisions must not read labels, change targets, or choose phases. if query != 1: return target, None if target.shape != (10,) or not torch.isfinite(target).all(): raise ValueError("Expected a finite ten-dimensional keypose prediction") if seed not in self.episodes: raise ValueError(f"No saved training demonstration for seed {seed}") episode = self.episodes[seed] group_name = f"traj_{episode['episode_id']}/keyframes" with h5py.File(self.config.dataset, "r") as data: key = data[group_name] if ( key.attrs.get("pose_frame") != "world" or key["name"].asstr()[0] != "approach" or key["kind"].asstr()[0] != "move" or int(key["start_action"][0]) != 0 or int(key["action_keyframe_index"][0]) != 0 ): raise ValueError("Expected the initial world-frame approach target") expert_pose = np.asarray(key["target_pose_world"][0]) if expert_pose.shape != (7,) or not np.isfinite(expert_pose).all(): raise ValueError("Expected a finite saved world pose7") expert_xyz = torch.as_tensor( expert_pose[:3], dtype=target.dtype, device=target.device ) alpha = self.config.alpha if alpha == 0: target[:3] = expert_xyz elif alpha != 1: target[:3] = expert_xyz + alpha * (predicted[:3] - expert_xyz) # alpha=1 deliberately performs no arithmetic on the executed target. return target, { **self.source, "seed": seed, "episode_id": episode["episode_id"], "h5_target_path": f"{group_name}/target_pose_world", "h5_target_index": 0, "primitive": "approach", "alpha": alpha, "expert_xyz": expert_xyz.tolist(), "predicted_xyz": predicted[:3].tolist(), "executed_xyz": target[:3].tolist(), "residual_before_m": (predicted[:3] - expert_xyz).tolist(), "residual_after_m": (target[:3] - expert_xyz).tolist(), "scope": "Privileged first-query XYZ diagnostic, including alpha=1 identity; not learned-policy performance", } def nearest_cube_intervention(predicted, *, cubes): """Privileged XY on every query, snapped to the cube the model already chose. Replaces XY precision ONLY. Height, orientation, continuous gripper and the decision of when to advance stay exactly as predicted, so this isolates localization error from phase advancement. The model's own object choice is preserved by selecting the nearest center; the margin is recorded so that ambiguous cases stay visible instead of being silently attributed. """ target = predicted.clone() if not torch.isfinite(target).all(): raise ValueError("Cannot intervene on a nonfinite prediction") if not cubes: raise ValueError("Expected at least one named cube center") names = sorted(cubes) centers = torch.stack( [torch.as_tensor(cubes[name], dtype=target.dtype).reshape(-1) for name in names] ) if centers.shape != (len(names), 2) or not torch.isfinite(centers).all(): raise ValueError("Expected finite cube center XY per cube") distances = (centers - target[:2]).norm(dim=-1) order = distances.argsort() chosen = int(order[0]) target[:2] = centers[chosen] return target, { "intervened_cube": names[chosen], "correction_mm": float(distances[chosen]) * 1000, "runner_up_cube": names[int(order[1])] if len(names) > 1 else None, "selection_margin_mm": float(distances[int(order[1])] - distances[chosen]) * 1000 if len(names) > 1 else None, "cube_centers_m": {name: centers[i].tolist() for i, name in enumerate(names)}, } class TrainingResetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Physical environment before observation, recording and metric wrappers.""" dataset: Path """Saved training trajectories; only initial physical states are restored.""" class TrainingSceneReset(gym.Wrapper): def __init__(self, config: TrainingResetConfig): super().__init__(config.env) self.config = config metadata = json.loads(config.dataset.with_suffix(".json").read_text()) self.episodes = {e["episode_seed"]: e for e in metadata["episodes"]} if len(self.episodes) != len(metadata["episodes"]): raise ValueError("Ambiguous training scene seeds") def reset(self, *, seed=None, options=None): episode = self.episodes[seed] _, _ = self.env.reset(**episode["reset_kwargs"]) def first(group): return { k: first(v) if isinstance(v, h5py.Group) else v[0] for k, v in group.items() } with h5py.File(self.config.dataset, "r") as data: group = data[f"traj_{episode['episode_id']}"] state = first(group["env_states"]) base = self.unwrapped base.set_state_dict(state) # Joint targets must start at restored joints, not random reset joints. base.agent.controller.reset() obs = base.get_obs() np.testing.assert_allclose( obs["agent"]["qpos"].cpu()[0], group["obs/agent/qpos"][0], atol=1e-6 ) np.testing.assert_allclose( obs["extra"]["tcp_pose"].cpu()[0], group["obs/extra/tcp_pose"][0], atol=1e-6, ) info = base.get_info() info["diagnostic_training_episode_id"] = episode["episode_id"] return obs, info