File size: 33,889 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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
"""Load the pinned official ACT and audit its unmodified evaluation path."""

import hashlib
import importlib.util
import io
import json
import math
import sys
import time
from functools import partial
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Literal

import gymnasium as gym
import numpy as np
import pynvml
import torch
from pydantic import BaseModel, ConfigDict, PositiveInt, model_validator
from pydantic_settings import CliApp

from lim.act_policy import ACTPolicyConfig, build_policy, evaluation_transport
from lim.action_encoding import encoded_dimension, sixd_to_controller
from lim.chunk_coordinates import pose_target_contract
from lim.gripper_execution import GripperExecutionConfig
from lim.normalization import checked_statistics
from lim.profile import process_gpu_memory
from lim.tasks import TASKS

PROFILE_SCOPE = (
    "batch1 raw CPU RGB/proprioception through official resize, transfers, normalization, "
    "ResNet, configured policy and native temporal aggregation (with target conversion "
    "for chunk_relative); simulator-free replay of saved raw "
    "inputs; excludes camera acquisition/transport and low-level physical control; "
    "NVML sampled after each iteration"
)

ACTControlMode = Literal["pd_ee_delta_pos", "pd_ee_delta_pose"]
ACTION_DIMENSIONS = {"pd_ee_delta_pos": 4, "pd_ee_delta_pose": 7}


def load_checkpoint(path):
    raw = path.read_bytes()
    checkpoint = torch.load(io.BytesIO(raw), map_location="cpu", weights_only=False)
    if "ema_agent" not in checkpoint or checkpoint["norm_stats"] is not None:
        raise ValueError("Expected official delta-control EMA checkpoint")
    return checkpoint, {
        "checkpoint_sha256": hashlib.sha256(raw).hexdigest(),
        "loaded_weight_key": "ema_agent",
    }


def check_policy_checkpoint(checkpoint, config):
    declared = ACTPolicyConfig.model_validate(checkpoint.get("policy", {}))
    if (
        declared != config.policy
        or checkpoint.get("num_queries", 30) != config.num_queries
        or checkpoint.get("control_mode", "pd_ee_delta_pos") != config.control_mode
    ):
        raise ValueError(
            "Checkpoint policy, control mode or prediction horizon differs from evaluation"
        )
    if "ema_agent" in checkpoint:
        # Metadata alone must not relabel a Q30 network as Q1. Wrappers add
        # prefixes, but every supported ACT variant owns one query embedding.
        weights = checkpoint["ema_agent"]
        queries = [
            value
            for name, value in weights.items()
            if name.endswith("query_embed.weight")
        ]
        if len(queries) != 1 or tuple(queries[0].shape) != (
            config.num_queries,
            config.architecture.hidden_dim,
        ):
            raise ValueError(
                "Checkpoint query embedding disagrees with prediction horizon"
            )
        for name, value in weights.items():
            if name.endswith("pos_table") and tuple(value.shape) != (
                1,
                config.num_queries + 2,
                config.architecture.hidden_dim,
            ):
                raise ValueError(
                    "Checkpoint posterior position table disagrees with prediction horizon"
                )
    checked_statistics(
        checkpoint.get("normalization"),
        declared.normalization,
        declared.action_encoding,
    )
    if declared.method == "chunk_relative" and declared.action_encoding == "rotation6d":
        # The contract must match the checkpoint's own label frame, so a model is
        # never evaluated in a frame it was not trained in.
        expected = pose_target_contract(
            declared.chunk_anchor,
            declared.chunk_pose_supervision,
            declared.chunk_gripper_supervision,
            declared.chunk_padding,
            declared.chunk_normalization_population,
            declared.chunk_label_offset,
            declared.chunk_waypoint_threshold_m,
            declared.chunk_bspline_knots,
        )
        if checkpoint.get("action_target_contract") != expected:
            raise ValueError(
                "Checkpoint contract does not match its anchor, pose or gripper supervision"
            )


def source_provenance(config):
    declared = json.loads(Path("round2/reference-source.json").read_text())
    source = Path("third_party/ManiSkill/examples/baselines/act/train_rgbd.py")
    if config.source.resolve() != source.resolve():
        raise ValueError("Reference source must match the pinned official loader")
    actual = {
        p: hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in declared["sha256"]
    }
    if actual != declared["sha256"]:
        raise ValueError("Official source differs from audited hashes")
    return {"official_source_sha256": actual, "reference_commit": declared["commit"]}


class ACTArchitectureConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    hidden_dim: PositiveInt = 256
    """Official ACT transformer hidden width."""
    dim_feedforward: PositiveInt = 512
    """Official transformer feed-forward width."""
    enc_layers: PositiveInt = 2
    """Encoder layers in the official architecture."""
    dec_layers: PositiveInt = 4
    """Decoder layers in the official architecture."""


class ReferenceConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    mode: Literal["witness", "evaluate", "profile"] = "witness"
    """Environment witness, fixed-checkpoint evaluation, or simulator-free profile."""
    source: Path = Path("third_party/ManiSkill/examples/baselines/act/train_rgbd.py")
    """Pinned, unmodified official implementation containing Agent and preprocessing."""
    checkpoint: Path | None = None
    """Official final checkpoint; evaluation and profile load its ema_agent entry."""
    output_dir: Path = Path("artifacts/round2/witness")
    """New output directory, with raw episode or timing records."""
    episodes: PositiveInt = 100
    """Fixed number of complete evaluation episodes."""
    num_envs: PositiveInt = 10
    """CPU physics vector environments; episodes must be divisible by this count."""
    seed_start: int = 50000
    """Explicit, disjoint per-episode seed block."""
    observations: Path | None = None
    """Folder with saved raw RGB/proprioceptive inputs for profiling."""
    iterations: PositiveInt = 500
    """Measured warmed profile calls; 30 additional warmup calls precede these."""
    demonstration_metadata: Path = Path(
        "data/official-demos/StackCube-v1/motionplanning/trajectory.rgb.pd_ee_delta_pos.physx_cpu.json"
    )
    """Converted demonstration metadata supplying the evaluation sensor configuration."""
    architecture: ACTArchitectureConfig = ACTArchitectureConfig()
    """Explicit trained model shape; defaults preserve the Round2 small reference."""
    policy: ACTPolicyConfig = ACTPolicyConfig()
    """Trained architecture/input variant; must match checkpoint metadata."""
    num_queries: PositiveInt = 30
    """Actual trained decoder query count, including one for a single-target model;
    native evaluation queries fresh observations each control step."""
    video_seeds: tuple[int, ...] = ()
    """Optional explicit scene seeds to record, including raw RGB and observer view."""
    keypose_trace: bool = False
    """Record read-only target, TCP error, and arrival-gate diagnostics for keyposes."""
    control_mode: ACTControlMode = "pd_ee_delta_pos"
    """Controller shared by the trained action labels and online environment."""
    gripper_execution: GripperExecutionConfig = GripperExecutionConfig()
    """Optional inference-only gripper intervention and chunk-level diagnostics."""

    @model_validator(mode="after")
    def validate_execution(self):
        if self.keypose_trace and (
            self.mode != "evaluate" or self.policy.keypose is None
        ):
            raise ValueError("Keypose diagnostics require keypose evaluation")
        if self.policy.keypose is not None and (
            self.mode != "evaluate" or self.control_mode != "pd_ee_delta_pose"
        ):
            raise ValueError(
                "Keypose transport currently supports pose evaluation only"
            )
        if self.gripper_execution.active and (
            self.mode != "evaluate"
            or self.control_mode != "pd_ee_delta_pose"
            or self.policy.method != "cvae"
            or self.policy.action_encoding != "rotation6d"
            or self.policy.keypose is not None
        ):
            raise ValueError(
                "Gripper execution experiments require CVAE pose6D evaluation"
            )
        return self


def load_official(config):
    source_provenance(config)
    # The vendor's act/ is a namespace directory; its setup.find_packages()
    # does not install it. Match direct train_rgbd.py execution's import root.
    source_root = str(config.source.resolve().parent)
    if source_root not in sys.path:
        sys.path.insert(0, source_root)
    # Use the file's importable name so forkserver CPU workers can reconstruct
    # the official observation-wrapper class from the inherited sys.path.
    spec = importlib.util.spec_from_file_location(config.source.stem, config.source)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    # Agent and Dataset reference the script's module-global args at runtime.
    module.args = module.Args(
        **config.architecture.model_dump(),
        include_depth=False,
        env_id="StackCube-v1",
        control_mode=config.control_mode,
        max_episode_steps=200,
        sim_backend="physx_cpu",
        temporal_agg=True,
        num_queries=config.num_queries,
    )
    return module


class AuditConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    env: Any
    """Official environment, before visual preprocessing and CPU metric wrappers."""
    snapshots: Path
    """Raw policy-input snapshots, saved only from the first vector slot."""
    stride: int
    """Number of vector slots for deterministic snapshot ownership."""
    seed_start: int
    """First held-out seed, used only for snapshot ownership."""


class ReleasedSupportAudit(gym.Wrapper):
    def __init__(self, config: AuditConfig):
        super().__init__(config.env)
        self.config = config
        self.streak = 0
        self.once = False
        self.explicit_seed = None
        self.step_index = 0

    def snapshot(self, obs):
        if (
            self.explicit_seed is None
            or (self.explicit_seed - self.config.seed_start) % self.config.stride
        ):
            return
        if self.step_index not in (0, 10, 30, 70, 120, 199):
            return
        folder = self.config.snapshots
        folder.mkdir(parents=True, exist_ok=True)
        if len(list(folder.glob("*.pt"))) >= 12:
            return

        def cpu(value):
            if isinstance(value, dict):
                return {k: cpu(v) for k, v in value.items()}
            return value.detach().cpu().clone() if torch.is_tensor(value) else value

        torch.save(
            cpu(obs), folder / f"seed{self.explicit_seed}_step{self.step_index}.pt"
        )

    def reset(self, **kwargs):
        obs, info = self.env.reset(**kwargs)
        self.streak, self.once, self.step_index = 0, False, 0
        self.explicit_seed = kwargs.get("seed")
        self.snapshot(obs)
        return obs, info

    def step(self, action):
        obs, reward, terminated, truncated, info = self.env.step(action)
        base = self.env.unwrapped
        if base.spec.id != "StackCube-v1":
            # The released-support audit is StackCube's cube-on-cube rule; other
            # tasks only need the observation snapshots.
            self.step_index += 1
            self.snapshot(obs)
            return obs, reward, terminated, truncated, info
        source, target = base.cubeA, base.cubeB
        support_force = base.scene.get_pairwise_contact_forces(source, target)
        contact = 0.0
        for link in base.agent.robot.get_links():
            contact = max(
                contact,
                float(
                    torch.linalg.norm(
                        base.scene.get_pairwise_contact_forces(source, link), dim=-1
                    ).item()
                ),
            )
        strict = (
            abs(float(support_force[0, 2])) > 0.1
            and float((source.pose.p - target.pose.p)[0, 2]) > 0.025
            and bool(source.is_static(lin_thresh=1e-2, ang_thresh=0.5).item())
            and contact < 0.01
            and bool((base.agent.robot.get_qpos()[0, -2:] >= 0.035).all())
        )
        self.streak = self.streak + 1 if strict else 0
        self.once = self.once or self.streak >= 20
        info["audit_release_once"] = self.once
        info["audit_release_at_end"] = self.streak >= 20
        info["audit_robot_contact"] = contact
        self.step_index += 1
        self.snapshot(obs)
        return obs, reward, terminated, truncated, info


def audit_wrapper(env, snapshots, stride, seed_start):
    return ReleasedSupportAudit(
        AuditConfig(env=env, snapshots=snapshots, stride=stride, seed_start=seed_start)
    )


class RecorderConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    env: Any
    """Official CPU vector environment with SAME_STEP autoreset semantics."""
    run: ReferenceConfig
    """Declared seed block and output destination."""


class SeededRecorder:
    """Record official metrics, explicitly seed each new batch, preserve ACT evaluation."""

    def __init__(self, config: RecorderConfig):
        self.config = config
        self.rows = []
        self.calls = 0
        self.seed_batch = 0
        self.model_queries = 0
        self.previous_model_queries = 0
        self.batch_steps = 0

    def count_inference(self, module, inputs):
        self.model_queries += 1

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

    def reset(self):
        start = self.config.run.seed_start + self.seed_batch * self.num_envs
        return self.config.env.reset(seed=list(range(start, start + self.num_envs)))

    def step(self, action):
        obs, reward, terminated, truncated, info = self.config.env.step(action)
        self.calls += 1
        self.batch_steps += 1
        if truncated.any():
            assert truncated.all()
            for slot, final in enumerate(info["final_info"]):
                row = {k: np.asarray(v).item() for k, v in final["episode"].items()}
                row.update(
                    seed=self.config.run.seed_start
                    + self.seed_batch * self.num_envs
                    + slot,
                    audit_release_once=bool(final["audit_release_once"]),
                    audit_release_at_end=bool(final["audit_release_at_end"]),
                    steps=self.batch_steps,
                    policy_calls=self.model_queries - self.previous_model_queries,
                )
                self.rows.append(row)
                with (self.config.run.output_dir / "episodes.jsonl").open("a") as f:
                    f.write(json.dumps(row) + "\n")
            print(
                json.dumps(
                    {
                        "completed": len(self.rows),
                        "success_once": sum(r["success_once"] for r in self.rows),
                        "success_at_end": sum(r["success_at_end"] for r in self.rows),
                    }
                ),
                flush=True,
            )
            self.seed_batch += 1
            self.previous_model_queries = self.model_queries
            self.batch_steps = 0
            if len(self.rows) < self.config.run.episodes:
                # SAME_STEP already performed an unseeded reset. Replace that
                # initial state before any policy action, keeping final_info intact.
                obs, _ = self.reset()
        return obs, reward, terminated, truncated, info


def create_env(module, config, count):
    metadata = json.loads(config.demonstration_metadata.read_text())
    info = metadata["env_info"]
    if info["env_id"] not in TASKS:
        raise ValueError("Demonstration metadata task mismatch")
    sensor_configs = info["env_kwargs"]["sensor_configs"]
    if info["env_kwargs"].get("control_mode") != config.control_mode:
        raise ValueError("Demonstration metadata and evaluation controller differ")
    if config.policy.method == "chunk_relative" and config.control_mode != (
        "pd_ee_delta_pose"
        if config.policy.action_encoding == "rotation6d"
        else "pd_ee_delta_pos"
    ):
        raise ValueError(
            "Chunk-relative action encoding and physical source controller disagree"
        )
    wrappers = [
        partial(
            audit_wrapper,
            snapshots=config.output_dir / "raw_observations",
            stride=count,
            seed_start=config.seed_start,
        ),
    ]
    if config.video_seeds:
        from lim.policy_video import policy_video_wrapper

        wrappers.append(
            partial(
                policy_video_wrapper,
                output_dir=config.output_dir / "videos",
                seeds=config.video_seeds,
                label="keypose"
                if config.policy.keypose is not None
                else config.policy.method,
            )
        )
    wrappers.append(partial(module.FlattenRGBDObservationWrapper, depth=False))
    return module.make_eval_envs(
        info["env_id"],
        count,
        "physx_cpu",
        {
            "control_mode": config.control_mode,
            "reward_mode": "sparse",
            "obs_mode": "rgb",
            "render_mode": "rgb_array",
            "max_episode_steps": 200,
            "sensor_configs": sensor_configs,
        },
        None,
        wrappers=wrappers,
    )


def evaluate(config):
    if config.episodes % config.num_envs:
        raise ValueError("Episode count must be divisible by vector environment count")
    config.output_dir.mkdir(parents=True, exist_ok=False)
    module = load_official(config)
    official_evaluate = module.evaluate
    env = create_env(module, config, config.num_envs)
    gripper_trace = None
    keypose_trace = None
    try:
        ck, provenance = load_checkpoint(config.checkpoint)
        check_policy_checkpoint(ck, config)
        agent = build_policy(
            module, env, module.args, config.policy, ck.get("normalization")
        ).cuda()
        agent.load_state_dict(ck["ema_agent"])
        recorder = SeededRecorder(RecorderConfig(env=env, run=config))
        query_hook = agent.model.register_forward_pre_hook(recorder.count_inference)
        kwargs = {
            "stats": ck["norm_stats"],
            "num_queries": 1
            if config.policy.keypose is not None
            else config.num_queries,
            "temporal_agg": True,
            "max_timesteps": 200,
            "device": torch.device("cuda"),
            "sim_backend": "physx_cpu",
        }
        start = time.monotonic()
        physical_env = recorder
        if config.gripper_execution.active:
            from lim.action_objective import BinaryGripperEnv, BinaryGripperEnvConfig
            from lim.gripper_execution import (
                GripperAgent,
                GripperBoundaryConfig,
                GripperDecisionEnv,
                GripperPhysicalEnv,
                GripperTrace,
                GripperTraceConfig,
            )

            gripper_trace = GripperTrace(
                GripperTraceConfig(
                    execution=config.gripper_execution,
                    output_dir=config.output_dir,
                    num_envs=config.num_envs,
                    horizon=config.num_queries,
                    seed_start=config.seed_start,
                    bce=config.policy.action_loss.method == "gripper_bce",
                )
            )
            physical_env = GripperPhysicalEnv(
                GripperBoundaryConfig(
                    wrapped=recorder,
                    trace=gripper_trace,
                )
            )
            if config.gripper_execution.binary and not gripper_trace.config.bce:
                physical_env = BinaryGripperEnv(
                    BinaryGripperEnvConfig(env=physical_env)
                )
        evaluation_agent, evaluation_env = evaluation_transport(
            agent, physical_env, config.policy
        )
        if config.keypose_trace:
            from lim.keypose_trace import KeyposeTraceConfig, KeyposeTraceEnv

            keypose_trace = KeyposeTraceEnv(
                KeyposeTraceConfig(
                    env=evaluation_env,
                    path=config.output_dir / "keypose_trace.jsonl",
                    seed_start=config.seed_start,
                )
            )
            evaluation_env = keypose_trace
        if gripper_trace is not None:
            evaluation_agent = GripperAgent(
                GripperBoundaryConfig(
                    wrapped=evaluation_agent,
                    trace=gripper_trace,
                )
            )
            evaluation_env = GripperDecisionEnv(
                GripperBoundaryConfig(
                    wrapped=evaluation_env,
                    trace=gripper_trace,
                )
            )
        metrics = official_evaluate(
            config.episodes, evaluation_agent, evaluation_env, kwargs
        )
        query_hook.remove()
        assert recorder.model_queries == recorder.calls
        for name in ("success_once", "success_at_end"):
            assert int(np.asarray(metrics[name]).sum()) == sum(
                r[name] for r in recorder.rows
            )
        result = {
            "provenance": provenance | source_provenance(config),
            "sensor_configs": json.loads(config.demonstration_metadata.read_text())[
                "env_info"
            ]["env_kwargs"]["sensor_configs"],
            "config": config.model_dump(mode="json"),
            "episodes": len(recorder.rows),
            "counts": {
                key: sum(r[key] for r in recorder.rows)
                for key in (
                    "success_once",
                    "success_at_end",
                    "audit_release_once",
                    "audit_release_at_end",
                )
            },
            "policy_vector_calls": recorder.model_queries,
            "environment_vector_steps": recorder.calls,
            "expected_policy_vector_calls": config.episodes // config.num_envs * 200,
            "feedback_hz": 20,
            "parameters": sum(p.numel() for p in agent.parameters()),
            "wall_s": time.monotonic() - start,
            "gpu": torch.cuda.get_device_name(),
            "checkpoint_rule": "official final update EMA; no test checkpoint selection",
        }
        if config.policy.keypose is not None:
            result["action_execution"] = (
                "Newest first query world keypose; no temporal averaging; observed TCP controller with arrival-gated continuous gripper. No oracle stages or object states."
            )
        if config.policy.action_loss.method == "gripper_bce":
            result["gripper_execution"] = evaluation_env.diagnostics()
            if config.gripper_execution.aggregation == "latest":
                result["gripper_execution"]["rule"] = (
                    "newest chunk first-step p(open); >=0.5 opens; no hysteresis"
                )
        if gripper_trace is not None:
            result["gripper_intervention"] = gripper_trace.diagnostics()
        (config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
        print("REFERENCE_EVAL_COMPLETE", json.dumps(result), flush=True)
    finally:
        if keypose_trace is not None:
            keypose_trace.finish()
        if gripper_trace is not None:
            gripper_trace.close()
        env.close()


def witness(config):
    config.output_dir.mkdir(parents=True, exist_ok=True)
    torch.manual_seed(0)
    module = load_official(config)
    env = create_env(module, config, 1)
    try:
        obs, _ = env.reset(seed=123456)
        base = env.envs[0].unwrapped
        agent = build_policy(module, env, module.args, config.policy).cuda()
        state_shape, rgb_shape = list(obs["state"].shape), list(obs["rgb"].shape)
        with torch.inference_mode():
            pred = agent.get_action(
                {k: torch.as_tensor(v, device="cuda") for k, v in obs.items()}
            )
        assert (
            pred.shape
            == (
                1,
                config.num_queries,
                encoded_dimension(
                    ACTION_DIMENSIONS[config.control_mode],
                    config.policy.action_encoding,
                ),
            )
            and torch.isfinite(pred).all()
        )
        assert base.control_freq == 20
        command = (
            sixd_to_controller(pred[:, 0])
            if config.policy.action_encoding == "rotation6d"
            else pred[:, 0]
        )
        if config.policy.action_loss.method == "gripper_bce":
            _, execution_env = evaluation_transport(agent, env, config.policy)
            execution_env.step(pred[:, 0].cpu().numpy())
        else:
            env.step(command.cpu().numpy())
        result = {
            "status": "PASS",
            "actual_sensor_shader_packs": {
                k: v.config.shader_pack for k, v in base._sensors.items()
            },
            "gymnasium": gym.__version__,
            "torch": torch.__version__,
            "control_hz": base.control_freq,
            "control_mode": base.control_mode,
            "sim_hz": base.sim_freq,
            "robot": base.agent.uid,
            "state_shape": state_shape,
            "rgb_shape": rgb_shape,
            "action_shape": list(pred.shape),
            "controller_action_shape": list(command.shape),
            "action_encoding": config.policy.action_encoding,
            "parameters": sum(p.numel() for p in agent.parameters()),
            "gpu": torch.cuda.get_device_name(),
        }
        (config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
        print("REFERENCE_WITNESS", json.dumps(result), flush=True)
    finally:
        env.close()


class ReplayConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    module: Any
    """Pinned official module, supplying the exact RGB observation transformation."""
    observations: list
    """Raw CPU camera and proprioceptive observations; no encoded visual features."""


class SensorReplay:
    """Feed real raw inputs through official evaluate() without a physics environment."""

    def __init__(self, config: ReplayConfig):
        self.config = config
        self.processor = SimpleNamespace(
            include_rgb=True,
            include_depth=False,
            include_state=True,
            transforms=config.module.T.Compose(
                [config.module.T.Resize((224, 224), antialias=True)]
            ),
        )
        example = self.prepare(0)
        self.single_observation_space = gym.spaces.Dict(
            {
                "state": gym.spaces.Box(
                    -np.inf, np.inf, shape=example["state"].shape[1:], dtype=np.float32
                ),
                "rgb": gym.spaces.Box(
                    0, 255, shape=example["rgb"].shape[1:], dtype=np.uint8
                ),
            }
        )
        action_dim = ACTION_DIMENSIONS[config.module.args.control_mode]
        self.single_action_space = gym.spaces.Box(
            -1, 1, (action_dim,), dtype=np.float32
        )
        self.action_space = gym.spaces.Box(-1, 1, (1, action_dim), dtype=np.float32)
        self.num_envs = 1
        self.calls = 0
        self.started = None
        self.rows = []

    def prepare(self, index):
        # The official transform pops top-level keys only; preserve the raw record.
        raw = dict(self.config.observations[index % len(self.config.observations)])
        return self.config.module.FlattenRGBDObservationWrapper.observation(
            self.processor, raw
        )

    def next_observation(self):
        torch.cuda.synchronize()
        self.started = time.perf_counter()
        return self.prepare(self.calls)

    def reset(self):
        return self.next_observation(), {}

    def step(self, action):
        torch.cuda.synchronize()
        elapsed = (time.perf_counter() - self.started) * 1000
        if not np.isfinite(action).all():
            raise FloatingPointError("Nonfinite reference policy action")
        self.rows.append(
            {
                "index": self.calls,
                "total_ms": elapsed,
                "sampled_process_bytes": process_gpu_memory(),
            }
        )
        self.calls += 1
        truncated = np.array([self.calls % 200 == 0])
        # Required vector episode bookkeeping, deliberately containing no task score.
        info = (
            {"final_info": [{"episode": {"measurement_episode": self.calls // 200}}]}
            if truncated[0]
            else {}
        )
        return (
            self.next_observation(),
            np.array([0.0]),
            np.array([False]),
            truncated,
            info,
        )


def profile(config):
    if config.checkpoint is None or config.observations is None:
        raise ValueError("Profile requires checkpoint and raw observations")
    config.output_dir.mkdir(parents=True, exist_ok=False)
    module = load_official(config)
    paths = sorted(config.observations.glob("*.pt"))
    if not paths:
        raise ValueError("No raw observations for profile")
    raw_inputs = {p.name: p.read_bytes() for p in paths}
    replay = SensorReplay(
        ReplayConfig(
            module=module,
            observations=[
                torch.load(io.BytesIO(raw), map_location="cpu", weights_only=False)
                for raw in raw_inputs.values()
            ],
        )
    )
    checkpoint, provenance = load_checkpoint(config.checkpoint)
    check_policy_checkpoint(checkpoint, config)
    agent = build_policy(
        module, replay, module.args, config.policy, checkpoint.get("normalization")
    ).cuda()
    agent.load_state_dict(checkpoint["ema_agent"])
    pynvml.nvmlInit()
    model_queries = 0

    def count_query(module, inputs):
        nonlocal model_queries
        model_queries += 1

    query_hook = agent.model.register_forward_pre_hook(count_query)
    # Complete full 200-step official evaluator episodes. Measure exactly the
    # declared 500 calls after 30 warmup; trailing padding calls are separate.
    total_episodes = math.ceil((30 + config.iterations) / 200)
    evaluation_agent, evaluation_env = evaluation_transport(
        agent, replay, config.policy
    )
    module.evaluate(
        total_episodes,
        evaluation_agent,
        evaluation_env,
        {
            "stats": checkpoint["norm_stats"],
            "num_queries": config.num_queries,
            "temporal_agg": True,
            "max_timesteps": 200,
            "device": torch.device("cuda"),
            "sim_backend": "physx_cpu",
        },
    )
    query_hook.remove()
    assert model_queries == replay.calls
    measured = replay.rows[30 : 30 + config.iterations]
    assert len(measured) == config.iterations
    timings = [row["total_ms"] for row in measured]
    result = {
        "provenance": provenance
        | source_provenance(config)
        | {
            "raw_observations_sha256": {
                name: hashlib.sha256(raw).hexdigest()
                for name, raw in raw_inputs.items()
            }
        },
        "config": config.model_dump(mode="json"),
        "gpu": torch.cuda.get_device_name(),
        "parameters": sum(p.numel() for p in agent.parameters()),
        "raw_observations": len(paths),
        "warmup_calls": 30,
        "measured_calls": len(measured),
        "total_official_evaluator_calls": replay.calls,
        "actual_model_queries": model_queries,
        "trailing_unmeasured_calls": replay.calls - 30 - len(measured),
        "cold_ms": replay.rows[0]["total_ms"],
        "latency_ms": {
            str(p): float(np.percentile(timings, p)) for p in (50, 95, 99, 100)
        },
        "sampled_peak_process_bytes": max(
            row["sampled_process_bytes"] for row in replay.rows
        ),
        "peak_allocated_bytes": torch.cuda.max_memory_allocated(),
        "peak_reserved_bytes": torch.cuda.max_memory_reserved(),
        "scope": PROFILE_SCOPE,
    }
    with (config.output_dir / "iterations.jsonl").open("w") as out:
        for row in replay.rows:
            out.write(
                json.dumps(
                    row | {"measured": 30 <= row["index"] < 30 + config.iterations}
                )
                + "\n"
            )
    (config.output_dir / "result.json").write_text(json.dumps(result, indent=2))
    print("REFERENCE_PROFILE_COMPLETE", json.dumps(result), flush=True)


def run(config: ReferenceConfig):
    torch.set_num_threads(4)
    if config.mode == "witness":
        witness(config)
    elif config.mode == "evaluate":
        if config.checkpoint is None:
            raise ValueError("Evaluation requires a checkpoint")
        evaluate(config)
    else:
        profile(config)


if __name__ == "__main__":
    run(CliApp.run(ReferenceConfig))