File size: 8,706 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
"""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