File size: 9,255 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
"""Inference-only gripper interventions around the unchanged native evaluator."""

import json
from collections import deque
from pathlib import Path
from typing import Any, Literal

import numpy as np
import torch
from pydantic import BaseModel, ConfigDict, PositiveInt


class GripperExecutionConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    aggregation: Literal["native", "latest"] = "native"
    """Native temporal mean, or the newest chunk's first gripper prediction only."""
    binary: bool = False
    """Threshold the gripper at zero after aggregation; BCE already does this."""
    trace: bool = False
    """Write every aligned chunk contribution and actual physical command."""

    @property
    def active(self):
        return self.trace or self.binary or self.aggregation != "native"


class GripperTraceConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    execution: GripperExecutionConfig
    """Execution intervention, separate from the checkpoint's training policy."""
    output_dir: Path
    """Evaluation directory for gripper_steps.jsonl."""
    num_envs: PositiveInt
    """Synchronous vector slots, each with exactly one model query per step."""
    horizon: PositiveInt
    """Number of predicted actions per chunk."""
    seed_start: int
    """Recorder's explicit initial scene seed; each batch advances num_envs."""
    bce: bool
    """Whether the model output is 2*p(open)-1 rather than continuous L1 output."""


class GripperTrace:
    def __init__(self, config: GripperTraceConfig):
        self.config = config
        self.chunks = deque(maxlen=config.horizon)
        self.step = 0
        self.batch = 0
        self.pending = None
        self.command = None
        self.rows = 0
        self.disagreements = 0
        self.stream = (
            (config.output_dir / "gripper_steps.jsonl").open("x")
            if config.execution.trace
            else None
        )

    def reset(self):
        self.chunks.clear()
        self.step = 0
        self.batch = 0
        self.pending = None
        self.command = None

    def prediction(self, chunk):
        if chunk.shape != (self.config.num_envs, self.config.horizon, 10):
            raise ValueError("Expected one finite 10D pose chunk per vector slot")
        if not torch.isfinite(chunk).all():
            raise ValueError("Nonfinite policy chunk")
        if self.chunks and self.chunks[-1][0] == self.step:
            raise ValueError("More than one prediction for the same physical step")
        self.chunks.append((self.step, chunk.detach().clone()))

    def select(self, native_action):
        if not self.chunks or self.chunks[-1][0] != self.step:
            raise ValueError("Physical action must follow a fresh observation query")
        native = np.asarray(native_action)
        times = [time for time, _ in self.chunks]
        aligned = torch.stack(
            [chunk[:, self.step - time] for time, chunk in self.chunks], dim=1
        )
        # Exact vendor ordering: oldest to newest; older predictions get slightly
        # larger weights. This recomputation audits; it NEVER replaces native pose.
        weights = torch.exp(-0.01 * torch.arange(len(times), device=aligned.device))
        weights = weights / weights.sum()
        reconstructed = (aligned * weights[None, :, None]).sum(dim=1).cpu().numpy()
        np.testing.assert_allclose(native, reconstructed, rtol=1e-5, atol=1e-6)
        selected = np.array(native, copy=True)
        latest = self.chunks[-1][1][:, 0, -1].cpu().numpy()
        if self.config.execution.aggregation == "latest":
            selected[:, -1] = latest
        self.pending = {
            "chunk_created_step0": times,
            "chunk_action_index": [self.step - time for time in times],
            "weights": weights.cpu().tolist(),
            "aligned_gripper": aligned[..., -1].cpu().numpy(),
            "native": native.copy(),
            "selected": selected.copy(),
            "latest": latest.copy(),
        }
        return selected

    def physical_command(self, action):
        if self.pending is None or self.command is not None:
            raise ValueError("Unexpected physical command ordering")
        self.command = np.array(action, copy=True)

    def completed(self, terminated, truncated):
        pending, command = self.pending, self.command
        if pending is None or command is None:
            raise ValueError("Missing prediction or physical command record")
        expected = pending["selected"][:, -1]
        if self.config.bce or self.config.execution.binary:
            expected = np.where(expected >= 0, 1.0, -1.0)
        np.testing.assert_array_equal(command[:, -1], expected)
        for slot in range(self.config.num_envs):
            row = {
                "seed": self.config.seed_start
                + self.batch * self.config.num_envs
                + slot,
                "step0": self.step,
                "post_action_step": self.step + 1,
                "chunk_created_step0": pending["chunk_created_step0"],
                "chunk_action_index": pending["chunk_action_index"],
                "weights": pending["weights"],
                "chunk_gripper_scores": pending["aligned_gripper"][slot].tolist(),
                "latest_gripper_score": float(pending["latest"][slot]),
                "native_gripper_score": float(pending["native"][slot, -1]),
                "selected_gripper_score": float(pending["selected"][slot, -1]),
                "native_action_6d": pending["native"][slot].tolist(),
                "selected_action_6d": pending["selected"][slot].tolist(),
                "controller_command": command[slot].tolist(),
            }
            if self.config.bce:
                row["chunk_p_open"] = (
                    (pending["aligned_gripper"][slot] + 1) / 2
                ).tolist()
                row["latest_p_open"] = (row["latest_gripper_score"] + 1) / 2
                row["native_p_open"] = (row["native_gripper_score"] + 1) / 2
            self.disagreements += int(
                (row["latest_gripper_score"] >= 0) != (row["native_gripper_score"] >= 0)
            )
            if self.stream is not None:
                self.stream.write(json.dumps(row, allow_nan=False) + "\n")
            self.rows += 1
        self.pending = self.command = None
        if np.asarray(truncated).any():
            if not np.asarray(truncated).all():
                raise ValueError("Native ACT requires simultaneous vector truncation")
            self.chunks.clear()
            self.batch += 1
            self.step = 0
            if self.stream is not None:
                self.stream.flush()
        else:
            if np.asarray(terminated).any():
                raise ValueError("Native ACT requires ignore_terminations=True")
            self.step += 1

    def diagnostics(self):
        return {
            "recorded_commands": self.rows,
            "latest_native_sign_disagreements": self.disagreements,
            "aggregation": self.config.execution.aggregation,
            "binary": self.config.bce or self.config.execution.binary,
            "trace": "gripper_steps.jsonl" if self.stream is not None else None,
            "weights": "exp(-0.01*rank), normalized; oldest prediction rank=0",
            "scope": "controller input, before the controller's own clipping; "
            "probabilities only for BCE; geometry is diagnostic video metadata only",
        }

    def close(self):
        if self.stream is not None:
            self.stream.close()


class GripperBoundaryConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    wrapped: Any
    """Existing agent or environment; all unrelated behavior is delegated."""
    trace: Any
    """Shared per-evaluation GripperTrace; never passed into the learned policy."""


class GripperAgent:
    def __init__(self, config: GripperBoundaryConfig):
        self.config = config

    def __getattr__(self, name):
        return getattr(self.config.wrapped, name)

    def get_action(self, obs):
        chunk = self.config.wrapped.get_action(obs)
        self.config.trace.prediction(chunk)
        return chunk


class GripperDecisionEnv:
    def __init__(self, config: GripperBoundaryConfig):
        self.config = config

    def __getattr__(self, name):
        return getattr(self.config.wrapped, name)

    def reset(self, *args, **kwargs):
        self.config.trace.reset()
        return self.config.wrapped.reset(*args, **kwargs)

    def step(self, action):
        selected = self.config.trace.select(action)
        result = self.config.wrapped.step(selected)
        self.config.trace.completed(result[2], result[3])
        return result


class GripperPhysicalEnv:
    def __init__(self, config: GripperBoundaryConfig):
        self.config = config

    def __getattr__(self, name):
        return getattr(self.config.wrapped, name)

    def step(self, action):
        self.config.trace.physical_command(action)
        return self.config.wrapped.step(action)