File size: 14,428 Bytes
577c0a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""Keypose annotations with explicit pre-action/next-observation index semantics.

Dense observations and actions remain the canonical trajectory. Annotations are
additional supervision, never extra policy observations.
"""

from contextlib import ExitStack
from pathlib import Path
from typing import Literal

import h5py
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, PositiveInt
from pydantic_settings import CliApp


class KeyposeSegment(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    name: str
    """Human-readable expert primitive name."""
    kind: Literal["move", "close", "open"]
    """Executed motion or gripper primitive; dry-run planning has no segment."""
    start: NonNegativeInt
    """Inclusive action index, referring to the observation before that action."""
    end: PositiveInt
    """Exclusive action index, also the achieved endpoint observation index."""
    target_pose: tuple[float, ...] = Field(min_length=7, max_length=7)
    """Commanded world TCP position and quaternion in xyz,wxyz order."""
    gripper: Literal[-1, 1]
    """Command during the segment; closing and opening are explicit events."""


class AnnotationConfig(BaseModel, frozen=True):
    model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
    segments: tuple[KeyposeSegment, ...]
    """Contiguous expert primitives in source-action coordinates."""
    source_steps: PositiveInt
    """Number of source actions, before any controller conversion."""
    target_to_source: tuple[int, ...]
    """Source action index for every actually executed target action."""


def annotation_arrays(config: AnnotationConfig) -> dict[str, np.ndarray]:
    segments = config.segments
    if (
        not segments
        or segments[0].start != 0
        or segments[-1].end != config.source_steps
    ):
        raise ValueError("Segments must cover all source actions")
    previous = 0
    for segment in segments:
        if segment.start != previous or segment.end <= segment.start:
            raise ValueError("Segment gaps, overlap or empty primitive")
        pose = np.asarray(segment.target_pose)
        if not np.isfinite(pose).all() or not np.isclose(
            np.linalg.norm(pose[3:]), 1, atol=1e-4
        ):
            raise ValueError(
                "Target poses must have finite values and unit quaternions"
            )
        previous = segment.end
    mapping = np.asarray(config.target_to_source, dtype=np.int64)
    if (
        not len(mapping)
        or mapping[0] != 0
        or mapping[-1] != config.source_steps - 1
        or not np.array_equal(np.unique(mapping), np.arange(config.source_steps))
        or np.any(np.diff(mapping) < 0)
    ):
        raise ValueError("Replay mapping must cover every source action monotonically")
    source_ends = np.asarray([s.end for s in segments], dtype=np.int64)
    ends = np.searchsorted(mapping, source_ends, side="left")
    starts = np.r_[0, ends[:-1]]
    ids = np.searchsorted(ends, np.arange(len(mapping)), side="right")
    return {
        "start_action": starts,
        "end_action": ends,
        "source_start_action": np.asarray([s.start for s in segments], dtype=np.int64),
        "source_end_action": source_ends,
        "target_pose_world": np.asarray(
            [s.target_pose for s in segments], dtype=np.float32
        ),
        "gripper_command": np.asarray([s.gripper for s in segments], dtype=np.float32),
        "action_keyframe_index": ids,
        "target_to_source_action": mapping,
    }


def write_annotations(group, config: AnnotationConfig):
    arrays = annotation_arrays(config)
    if len(group["actions"]) != len(arrays["action_keyframe_index"]):
        raise ValueError("Replay trace and saved actions differ")
    keyframes = group.create_group("keyframes")
    keyframes.attrs.update(
        schema_version=1,
        pose_frame="world",
        pose_encoding="xyz,wxyz",
        interval="actions[start:end]; obs[end] is the achieved endpoint",
        label_scope="supervision only; never policy input",
    )
    for name, data in arrays.items():
        keyframes.create_dataset(name, data=data)
    for name, values in {
        "name": [s.name for s in config.segments],
        "kind": [s.kind for s in config.segments],
    }.items():
        keyframes.create_dataset(name, data=values, dtype=h5py.string_dtype("utf-8"))
    keyframes.create_dataset(
        "achieved_pose_world", data=group["obs/extra/tcp_pose"][:][arrays["end_action"]]
    )


class AuditConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    dataset: Path
    """Annotated ManiSkill H5; neighboring JSON supplies episode metadata."""
    output: Path
    """New audit JSON; no existing audit is overwritten."""
    source_dataset: Path | None = None
    """Annotated joint-control source for cross-file pose replay identity checks."""


def audit_dataset(config: AuditConfig):
    import hashlib
    import json

    metadata = json.loads(config.dataset.with_suffix(".json").read_text())
    rows = []
    with ExitStack() as stack:
        data = stack.enter_context(h5py.File(config.dataset, "r"))
        source = None
        source_episodes = {}
        if config.source_dataset is not None:
            source = stack.enter_context(h5py.File(config.source_dataset, "r"))
            source_metadata = json.loads(
                config.source_dataset.with_suffix(".json").read_text()
            )
            source_episodes = {e["episode_id"]: e for e in source_metadata["episodes"]}
        if len(data) != len(metadata["episodes"]):
            raise ValueError("Episode count differs from metadata")
        for episode in metadata["episodes"]:
            group = data[f"traj_{episode['episode_id']}"]
            actions = group["actions"][:]
            count = len(actions)
            key = group["keyframes"]
            starts, ends = key["start_action"][:], key["end_action"][:]
            if (
                len(starts) == 0
                or starts[0] != 0
                or ends[-1] != count
                or np.any(ends <= starts)
                or not np.array_equal(starts[1:], ends[:-1])
            ):
                raise ValueError("Invalid segment boundaries")
            if count != episode["elapsed_steps"] or not bool(group["success"][-1]):
                raise ValueError("Incomplete or unsuccessful saved demonstration")

            def check_observation(name, item, count=count):
                if isinstance(item, h5py.Dataset):
                    if len(item) != count + 1:
                        raise ValueError(f"Dense observations dropped: {name}")
                    if not np.isfinite(item[:]).all():
                        raise ValueError(f"Nonfinite observations: {name}")

            group["obs"].visititems(check_observation)
            ids = key["action_keyframe_index"][:]
            expected_ids = np.repeat(np.arange(len(ends)), ends - starts)
            if not np.array_equal(ids, expected_ids):
                raise ValueError("Pre-action target labels are misaligned")
            for field in [
                "name",
                "kind",
                "gripper_command",
                "target_pose_world",
                "achieved_pose_world",
            ]:
                if len(key[field]) != len(ends):
                    raise ValueError(f"Wrong number of segment labels: {field}")
            kinds = key["kind"].asstr()[:]
            if not set(kinds).issubset({"move", "close", "open"}):
                raise ValueError("Unknown segment kind")
            commands = key["gripper_command"][:]
            if np.any(commands[kinds == "close"] != -1) or np.any(
                commands[kinds == "open"] != 1
            ):
                raise ValueError("Gripper event type disagrees with its command")
            if not np.array_equal(actions[:, -1], key["gripper_command"][:][ids]):
                raise ValueError("Gripper event/action mismatch")
            actual = group["obs/extra/tcp_pose"][:][ends]
            if not np.array_equal(actual, key["achieved_pose_world"][:]):
                raise ValueError("Endpoint observation is misaligned")
            mapping = key["target_to_source_action"][:]
            source_ends = key["source_end_action"][:]
            source_starts = key["source_start_action"][:]
            if not np.array_equal(source_starts, np.r_[0, source_ends[:-1]]) or np.any(
                source_ends <= source_starts
            ):
                raise ValueError("Source segment boundaries are inconsistent")
            if not np.array_equal(np.unique(mapping), np.arange(source_ends[-1])):
                raise ValueError("Replay omitted source actions")
            if np.any(np.diff(mapping) < 0) or not np.array_equal(
                np.searchsorted(mapping, source_ends), ends
            ):
                raise ValueError("Replay boundary mapping is invalid")
            target = key["target_pose_world"][:]
            if not np.isfinite(actions).all() or not np.isfinite(target).all():
                raise ValueError("Nonfinite actions or targets")
            if not np.allclose(np.linalg.norm(target[:, 3:], axis=1), 1, atol=1e-4):
                raise ValueError("Invalid quaternion target")
            image_differences = {}
            if source is not None:
                source_id = episode["source_episode_id"]
                source_group = source[f"traj_{source_id}"]
                if not (
                    episode["episode_seed"]
                    == episode["source_episode_seed"]
                    == source_episodes[source_id]["episode_seed"]
                ):
                    raise ValueError("Source and target seed metadata disagree")
                for path in ["obs/agent/qpos", "obs/agent/qvel", "obs/extra/tcp_pose"]:
                    np.testing.assert_allclose(
                        group[path][0], source_group[path][0], rtol=0, atol=1e-6
                    )
                for camera in ["base_camera", "hand_camera"]:
                    path = f"obs/sensor_data/{camera}/rgb"
                    difference = np.abs(
                        group[path][0].astype(np.int16)
                        - source_group[path][0].astype(np.int16)
                    )
                    image_differences[camera] = {
                        "bitwise_equal": not bool(difference.any()),
                        "changed_channels": int(np.count_nonzero(difference)),
                        "mean_abs_0_255": float(difference.mean()),
                        "max_abs_0_255": int(difference.max()),
                    }
                    for parameter in ["cam2world_gl", "extrinsic_cv", "intrinsic_cv"]:
                        path = f"obs/sensor_param/{camera}/{parameter}"
                        np.testing.assert_allclose(
                            group[path][0], source_group[path][0], rtol=0, atol=1e-6
                        )
                for category in ["actors", "articulations"]:
                    for entity in source_group[f"env_states/{category}"]:
                        path = f"env_states/{category}/{entity}"
                        np.testing.assert_array_equal(
                            group[path][0], source_group[path][0]
                        )
                for field in ["name", "kind"]:
                    np.testing.assert_array_equal(
                        key[field].asstr()[:],
                        source_group[f"keyframes/{field}"].asstr()[:],
                    )
                np.testing.assert_array_equal(
                    source_starts, source_group["keyframes/start_action"][:]
                )
                np.testing.assert_array_equal(
                    target, source_group["keyframes/target_pose_world"][:]
                )
                np.testing.assert_array_equal(
                    source_ends, source_group["keyframes/end_action"][:]
                )
                np.testing.assert_array_equal(
                    actions[:, -1], source_group["actions"][:, -1][mapping]
                )
            position_error = np.linalg.norm(actual[:, :3] - target[:, :3], axis=1)
            quat_a = actual[:, 3:] / np.linalg.norm(
                actual[:, 3:], axis=1, keepdims=True
            )
            quat_b = target[:, 3:] / np.linalg.norm(
                target[:, 3:], axis=1, keepdims=True
            )
            rotation_error = 2 * np.arccos(
                np.clip(np.abs((quat_a * quat_b).sum(1)), 0, 1)
            )
            rows.append(
                {
                    "episode_id": episode["episode_id"],
                    "seed": episode["episode_seed"],
                    "actions": count,
                    "keyframes": len(ends),
                    "position_error_m": position_error.tolist(),
                    "rotation_error_deg": np.rad2deg(rotation_error).tolist(),
                    "segments": key["name"].asstr()[:].tolist(),
                    "initial_rgb_diagnostics": image_differences,
                }
            )
    digest = hashlib.sha256()
    with config.dataset.open("rb") as f:
        for chunk in iter(lambda: f.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    result = {
        "status": "passed",
        "dataset": str(config.dataset),
        "sha256": digest.hexdigest(),
        "episodes": len(rows),
        "dense_actions": sum(r["actions"] for r in rows),
        "keyframes": sum(r["keyframes"] for r in rows),
        "source_identity_checked": config.source_dataset is not None,
        "rgb_bitwise_identity": all(
            d["bitwise_equal"]
            for row in rows
            for d in row["initial_rgb_diagnostics"].values()
        )
        if config.source_dataset is not None
        else None,
        "rows": rows,
        "scope": "record integrity and endpoint error; no learned policy or sparse execution result",
    }
    config.output.parent.mkdir(parents=True, exist_ok=True)
    with config.output.open("x") as f:
        f.write(json.dumps(result, indent=2) + "\n")
    return result


if __name__ == "__main__":
    result = audit_dataset(CliApp.run(AuditConfig))
    print({k: v for k, v in result.items() if k != "rows"})