diff --git a/.gitattributes b/.gitattributes index e268bd3a2d2a020d90d0d7f49b123b04e60dbceb..9a8a658503b6419bc642b80b0aba428779571d68 100644 --- a/.gitattributes +++ b/.gitattributes @@ -720,3 +720,11 @@ checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/36f39fcd checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/4bbd32adf2b7336cadcb18bb52047a5c filter=lfs diff=lfs merge=lfs -text checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/8e1c9a3cea3f74fc1d20691e046245a0 filter=lfs diff=lfs merge=lfs -text checkpoints/r2/shuffle/baseline/step8000/resume_state/ocdbt.process_0/d/e43002d36ecc20bd162287f94d990f41 filter=lfs diff=lfs merge=lfs -text +checkpoints/r2/shuffle/baseline/step9000/params/ocdbt.process_0/d/63d7385a0282182e209c36f5009987ac filter=lfs diff=lfs merge=lfs -text +checkpoints/r2/shuffle/baseline/step9000/params/ocdbt.process_0/d/a06069890aa4d04c31c910f8f5f67227 filter=lfs diff=lfs merge=lfs -text +checkpoints/r2/shuffle/baseline/step9000/params/ocdbt.process_0/d/aa7bed65eb2f1580ba7e32c788dbcba6 filter=lfs diff=lfs merge=lfs -text +checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/0e636c96c48077912e928b8466b48ebe filter=lfs diff=lfs merge=lfs -text +checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/2c882f98deed4eb7646b550ec4454166 filter=lfs diff=lfs merge=lfs -text +checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/7e7c067be6fc3ab0c386dcca415e7c32 filter=lfs diff=lfs merge=lfs -text +checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/b03ff5c988ddc142ab70b736239ecb93 filter=lfs diff=lfs merge=lfs -text +checkpoints/r2/shuffle/baseline/step9000/resume_state/ocdbt.process_0/d/e9dbd5f3c1ed092c0df1a8580e8520f2 filter=lfs diff=lfs merge=lfs -text diff --git a/checkpoints/r2/shuffle/baseline/step9000/README.md b/checkpoints/r2/shuffle/baseline/step9000/README.md new file mode 100644 index 0000000000000000000000000000000000000000..71d10e87fc5a291b5cf492833e6a26cd5a7a859b --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/README.md @@ -0,0 +1,49 @@ +--- +tags: [robotics, pi05, franka, lora] +--- + +# pi05-shuffle-baseline-lora-gbs4-pgb1-gpu4-r2-step9000 + +Second-round π0.5 LoRA fine-tuning for **shuffle**, checkpoint **9,000**. +Trained locally on **4 RTX A6000 GPUs**, **global batch 4**, **per-GPU batch 1**, +without gradient accumulation. This checkpoint represents **36,000 sample exposures**; +the run targets **12,500 optimizer updates / 50,000 sample exposures**. +Checkpoints are saved every **1,000** updates and at the final **12,500**. +Steps **5,000**, **10,000**, and **12,500** have standalone model repositories. +Other complete checkpoints are retained in the +[backup archive](https://huggingface.co/datasets/fm-dev/pi05-checkpoint-backups/tree/main/checkpoints/r2) +under `task/method/stepN/` with the same loading files and full resume state. +`r2` keeps these artifacts separate from the original 6,250-step experiment. + +Warmup: **250** updates to **5e-5**; cosine decay to **5e-6** at step **12,500**. +EMA: **0.999^4 = 0.996005996001**. AdamW, LoRA rank32, seed42. +Full settings are in `training_config.json`. + +No-history baseline: current base/wrist images, state and task instruction. + +Only robot execution rows supervise actions. Demonstration images, features and +original episode/frame coordinates remain available as history; execution start +does not reset the visual history. Episode splits and normalization use the +training split only. The recorded Cartesian end-effector/tool pose convention +must match the collection controller; do not apply an extra tool/flange offset. +Outputs have shape `(20,8)`: absolute xyz, unit XYZW quaternion in the positive-qx +chart, and gripper command in [0,1]. Numeric state/actions use STD normalization; +state tokens use a separate bounded train-q01/q99 view. + +Unknown action components remain NaN/false in the training dataset and are masked +in both flow conditioning and loss. Entirely unsupervised components: +**[7]**. In particular, Shuffle's +gripper output has no command supervision and must not be interpreted as learned +gripper control. Button Order has only limited verified closed-command labels. + +This repository includes EMA serving weights, normalization/history assets, +inference source, exact dependency versions, and full non-EMA/optimizer/RNG/sampler +resume state. Intermediate publication is not a policy-quality evaluation. +Offline evaluation, when included, does not establish real-robot success rate. + +Load with `from load_model import load, observe; policy = load()` from this bundle. +For history models call `observe(policy, base_rgb, state)` for every observed frame, +including demonstrations, and reset between episodes. Status-D additionally requires +explicit `history_keyframe_index` (an observed frame or None), `current_subgoal`, +and causal `transition_context_*` inputs in `policy.infer(...)`; its output includes +`transition_status`. Use the exported Writer schedule and matching control frame. diff --git a/checkpoints/r2/shuffle/baseline/step9000/_CHECKPOINT_METADATA b/checkpoints/r2/shuffle/baseline/step9000/_CHECKPOINT_METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ec0bb19d856130bb5554d02848d475d9a37079af --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/_CHECKPOINT_METADATA @@ -0,0 +1 @@ +{"item_handlers": {"assets": "openpi.training.checkpoints.CallbackHandler", "params": "orbax.checkpoint._src.handlers.pytree_checkpoint_handler.PyTreeCheckpointHandler", "resume_state": "orbax.checkpoint._src.handlers.pytree_checkpoint_handler.PyTreeCheckpointHandler"}, "metrics": {}, "performance_metrics": {}, "init_timestamp_nsecs": 1789048711257769417, "commit_timestamp_nsecs": 1789048746489655854, "custom_metadata": {}} \ No newline at end of file diff --git a/checkpoints/r2/shuffle/baseline/step9000/assets/franka/norm_stats.json b/checkpoints/r2/shuffle/baseline/step9000/assets/franka/norm_stats.json new file mode 100644 index 0000000000000000000000000000000000000000..14628cd465dd5f679dc9c373c3d7556d3736a9fc --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/assets/franka/norm_stats.json @@ -0,0 +1,88 @@ +{ + "norm_stats": { + "state": { + "mean": [ + 0.43004271388053894, + 0.01438639685511589, + 0.15972454845905304, + 0.8642361760139465, + -0.4695635437965393, + -0.005614287685602903, + 0.003596301656216383, + 0.0026823587249964476 + ], + "std": [ + 0.025760769844055176, + 0.13458988070487976, + 0.09128014743328094, + 0.08076709508895874, + 0.14975696802139282, + 0.04439425468444824, + 0.04049962759017944, + 0.000042953066440531984 + ], + "q01": [ + 0.35660686701536176, + -0.19194583505392074, + 0.04546925485134125, + 0.6543013167381286, + -0.7548727107048034, + -0.11300075851380825, + -0.06998954810202122, + 0.0026348750106990337 + ], + "q99": [ + 0.49797759830951693, + 0.2586104992032051, + 0.3494038268923759, + 0.9951327449083328, + -0.07059624232351777, + 0.07216263540089134, + 0.09449841350317002, + 0.002790587111376226 + ] + }, + "actions": { + "mean": [ + 0.42990756034851074, + 0.015801655128598213, + 0.1326005756855011, + 0.8696262240409851, + -0.4551904797554016, + 0.0005095235537737608, + 0.0030130352824926376, + 0.0 + ], + "std": [ + 0.02352166548371315, + 0.14162100851535797, + 0.07555239647626877, + 0.08528122305870056, + 0.15965595841407776, + 0.04530269280076027, + 0.041560959070920944, + 1.0 + ], + "q01": [ + 0.3335464817285538, + -0.19901523888111114, + 0.0370797111839056, + 0.6137884080410003, + -0.7878426039218902, + -0.24762430131435395, + -0.08285837218165397, + 0.0 + ], + "q99": [ + 0.4879460096359252, + 0.25839828968048095, + 0.337459173798561, + 0.9956820118427276, + -0.06469799026846947, + 0.08956875860691063, + 0.2402494329214096, + 0.0 + ] + } + } +} \ No newline at end of file diff --git a/checkpoints/r2/shuffle/baseline/step9000/assets/policy_metadata.json b/checkpoints/r2/shuffle/baseline/step9000/assets/policy_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..958a249116b1626ff11edf51d19634dd06113e1d --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/assets/policy_metadata.json @@ -0,0 +1,49 @@ +{ + "dataset": "/data/benchmarks/franka-demos/status-d-training/datasets/shuffle", + "representation": "absolute recorded end-effector xyz, unit xyzw with qx positive, commanded gripper open in [0,1]", + "gripper": "full-rate Joy edges matched to saved server requests; unknown=NaN/mask false; no bootstrap", + "run_purpose": "fine-tuning", + "target_steps": 12500, + "save_interval": 1000, + "task": "shuffle", + "prompt": "After the cups are shuffled, press the button next to the cup hiding the cube.", + "partial_action_supervision": true, + "unsupervised_action_components": [ + 7 + ], + "current_state_tokens": "train q01/q99 bounded [-1,1], constant spans map to zero", + "training_recipe": { + "method": "LoRA + Cartesian projections + optional history modules", + "gpus": 4, + "global_batch_size": 4, + "fsdp_devices": 1, + "gradient_accumulation": 1, + "action_dim": 8, + "action_horizon": 20, + "max_token_len": 128, + "ema_decay": 0.996005996001, + "reference_steps": 50000, + "reference_global_batch": 1, + "reference_ema_decay": 0.999, + "reference_warmup_steps": 1000, + "sample_exposures": 50000, + "warmup_steps": 250, + "decay_steps": 12500, + "peak_lr": 5e-05, + "decay_lr": 5e-06 + }, + "training_round": 2, + "training_setting": "baseline", + "action_supervision": "execution frames only; demonstration frames retained as visual history", + "checkpoint_retention": { + "save_interval": 1000, + "local_latest": 3, + "milestones": [ + 5000, + 10000, + 12500 + ], + "remote": "all" + }, + "gpu_allocator": "platform" +} \ No newline at end of file diff --git a/checkpoints/r2/shuffle/baseline/step9000/checkpoint_info.json b/checkpoints/r2/shuffle/baseline/step9000/checkpoint_info.json new file mode 100644 index 0000000000000000000000000000000000000000..cdd353ad1c9906be433d6543412619c90c9cbdd2 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/checkpoint_info.json @@ -0,0 +1,8 @@ +{ + "optimizer_step": 9000, + "target_steps": 12500, + "sample_exposures": 36000, + "full_resume_state_included": true, + "evaluation_status": "pending", + "training_round": 2 +} \ No newline at end of file diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/LICENSE b/checkpoints/r2/shuffle/baseline/step9000/code/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/examples/robomme/picmem_phase_a_rollout.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/examples/robomme/picmem_phase_a_rollout.py new file mode 100644 index 0000000000000000000000000000000000000000..16b8e80b55cb8b147e66276e38d2d194f8ab236e --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/examples/robomme/picmem_phase_a_rollout.py @@ -0,0 +1,1018 @@ +"""RoboMME simulator-side producer for the Phase-A evolving-memory rollout. + +The standard evaluator runs the simulator in a process separate from the +policy server. This module derives one strict runtime reset from the real +reset demonstration and emits only newly arrived events from the current +simulator trajectory. The reset/event envelopes travel inside the existing +``add_buffer`` request; images and robot states continue to use RoboMME's +normal buffer wire. + +This is an explicitly privileged oracle producer for the Phase-A upper bound. +It does not read a completed Run084 sidecar or any future rollout state. +Training remains bound to the corrected full Run084 artifact; evaluation is +bound instead to the pinned simulator episode identity and the exact live +demonstration prefix. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping, Sequence +from copy import deepcopy +from dataclasses import dataclass +from typing import Any + +import numpy as np + +from picmem.annotations import annotate_episode_from_steps +from picmem.memory.contracts import ManagerMode +from picmem.memory.manager import task_schema_for +from picmem.provenance.run084 import events_from_sidecar +from picmem.provenance.runtime_reader import ( + RuntimeReadError, + build_runtime_event, + build_runtime_reset, + build_runtime_source_contract, + canonical_json_sha256, + runtime_state_sha256, +) + +RUNTIME_BATCH_SCHEMA_VERSION = "picmem_phase_a_rollout_batch_v2" +RUNTIME_START_SCHEMA_VERSION = "picmem_phase_a_rollout_start_v1" +RUNTIME_ENVELOPE_SCHEMA_VERSION = "picmem_phase_a_rollout_event_envelope_v1" +RUNTIME_ACK_SCHEMA_VERSION = "picmem_phase_a_rollout_batch_ack_v1" +RUNTIME_RECEIPT_SCHEMA_VERSION = "picmem_phase_a_runtime_read_receipt_v3" +PRODUCER_SCHEMA_VERSION = "picmem_phase_a_robomme_oracle_producer_v1" + +SUPPORTED_TASKS = frozenset({"MoveCube", "PickXtimes", "VideoPlaceButton", "VideoUnmask"}) +TERMINAL_STATUSES = frozenset({"success", "fail", "timeout", "unknown"}) +GENESIS_BATCH_SHA256 = "0" * 64 +_ACK_FIELDS = frozenset( + { + "schema_version", + "batch_sequence", + "batch_sha256", + "duplicate", + "runtime_receipt", + } +) +_TERMINAL_OUTCOME_FIELDS = frozenset({"stop", "status"}) +_RUNTIME_EVENT_RECEIPT_BINDING_FIELDS = ( + "event_id", + "runtime_step", + "event_sha256", + "source_state_sha256", +) + + +@dataclass(frozen=True, slots=True) +class RuntimeEpisodeBinding: + """The exact reset authorization sent once to the policy server.""" + + start: Mapping[str, Any] + source_identity_sha256: str + source_contract_sha256: str + + +class RoboMMEPhaseAOracleProducer: + """Produce causal Phase-A runtime messages from one live RoboMME env.""" + + def __init__( + self, + *, + manager_mode: ManagerMode | str, + metadata_seed: int, + max_execution_steps: int, + ) -> None: + try: + self._manager_mode = ManagerMode(manager_mode) + except ValueError as exc: + raise RuntimeReadError(f"unsupported rollout manager_mode {manager_mode!r}") from exc + self._metadata_seed = _nat(metadata_seed, "metadata_seed") + self._max_execution_steps = _pos(max_execution_steps, "max_execution_steps") + self._task_env: Any | None = None + self._task_id: str | None = None + self._episode_id: int | None = None + self._identity_sha256: str | None = None + self._start: dict[str, Any] | None = None + self._start_sent = False + self._pending: list[dict[str, Any]] = [] + self._next_batch_sequence = 0 + self._last_acked_batch_sha256 = GENESIS_BATCH_SHA256 + self._inflight: dict[str, Any] | None = None + self._inflight_event_count = 0 + self._last_acked_runtime_receipt: dict[str, Any] | None = None + self._initial_event_ids: tuple[str, ...] = () + self._revision = 0 + self._event_ordinal = 0 + self._last_runtime_step = -1 + self._terminal_outcome: dict[str, Any] | None = None + self._last_task_timestep: int | None = None + self._target_cycles: int | None = None + self._cycle_start_step: int | None = None + self._last_move_subgoal: str | None = None + self._move_completions = 0 + self._move_step_count = 0 + + @property + def manager_mode(self) -> ManagerMode: + return self._manager_mode + + def begin_episode( + self, + env_runner: Any, + pretrajectory: Mapping[str, Any], + ) -> RuntimeEpisodeBinding: + """Bind and reset the producer from the real simulator reset result.""" + + self._clear_episode() + if not isinstance(pretrajectory, Mapping): + raise RuntimeReadError("RoboMME pretrajectory must be a mapping") + task_id = getattr(env_runner, "env_id", None) + if task_id not in SUPPORTED_TASKS: + raise RuntimeReadError(f"unsupported Phase-A rollout task {task_id!r}") + episode_id = _nat(getattr(env_runner, "episode_id", None), "episode_id") + env = getattr(env_runner, "env", None) + if env is None: + raise RuntimeReadError("RoboMME env_runner has no active environment") + task_env = _unwrapped(env) + + images = pretrajectory.get("images") + if not isinstance(images, Sequence) or isinstance(images, (str, bytes)) or not images: + raise RuntimeReadError("RoboMME pretrajectory images must be a non-empty sequence") + exec_start_step = len(images) - 1 + if task_id == "PickXtimes" and exec_start_step != 0: + raise RuntimeReadError("PickXtimes Phase-A rollout must begin execution at step zero") + if task_id != "PickXtimes" and exec_start_step <= 0: + raise RuntimeReadError(f"{task_id} Phase-A rollout requires a real demonstration prefix") + episode_end_step = exec_start_step + self._max_execution_steps + instruction = _canonical_instruction(pretrajectory.get("task_goal")) + reset_steps = _reset_steps_from_env(env, exec_start_step=exec_start_step, task_id=task_id) + source_path = f"robomme://test/{task_id}/{episode_id}" + dataset_version = "robomme_simulator_phase_a_runtime_v1" + + full_contract = _build_full_source_contract( + task_id=task_id, + episode_id=episode_id, + instruction=instruction, + dataset_version=dataset_version, + source_path=source_path, + reset_steps=reset_steps, + exec_start_step=exec_start_step, + episode_end_step=episode_end_step, + task_env=task_env, + first_images=images, + ) + source_contract = build_runtime_source_contract( + task_id=task_id, + source_contract=full_contract, + exec_start_step=exec_start_step, + episode_end_step=episode_end_step, + ) + source_contract_sha256 = canonical_json_sha256(source_contract) + source_identity = _simulator_source_identity( + task_env, + task_id=task_id, + episode_id=episode_id, + instruction=instruction, + source_path=source_path, + exec_start_step=exec_start_step, + episode_end_step=episode_end_step, + ) + source_identity_sha256 = canonical_json_sha256(source_identity) + reset = build_runtime_reset( + task_id=task_id, + episode_id=episode_id, + instruction=instruction, + dataset_version=dataset_version, + split="test", + source_path=source_path, + exec_start_step=exec_start_step, + episode_end_step=episode_end_step, + use_intervals=source_contract["use_intervals"], + source_identity_sha256=source_identity_sha256, + source_contract=source_contract, + reset_steps=reset_steps, + ) + start = { + "schema_version": RUNTIME_START_SCHEMA_VERSION, + "reset": reset, + "expected_identity_sha256": reset["identity_sha256"], + "expected_source_identity_sha256": source_identity_sha256, + "expected_source_contract_sha256": source_contract_sha256, + "manager_mode": self._manager_mode.value, + "metadata_seed": self._metadata_seed, + } + + initial_events = _initial_candidates( + task_id=task_id, + episode_id=episode_id, + instruction=instruction, + episode_end_step=episode_end_step, + exec_start_step=exec_start_step, + source_contract=full_contract, + ) + self._task_env = task_env + self._task_id = task_id + self._episode_id = episode_id + self._identity_sha256 = reset["identity_sha256"] + self._start = start + self._initial_event_ids = tuple(event.event_id for event in initial_events) + self._event_ordinal = len(initial_events) + self._last_runtime_step = exec_start_step + if task_id == "PickXtimes": + timestep = _nat(_required_attr(task_env, "timestep"), "PickXtimes.timestep") + target = _pos(_required_attr(task_env, "num_repeats"), "PickXtimes.num_repeats") + if timestep != 0: + raise RuntimeReadError("PickXtimes simulator did not reset to cycle zero") + self._last_task_timestep = timestep + self._target_cycles = target + self._cycle_start_step = exec_start_step + elif task_id == "MoveCube": + self._move_step_count = sum(1 for event in initial_events if event.kind == "demo_step") + if self._move_step_count <= 0: + raise RuntimeReadError("MoveCube reset did not produce demonstrated procedure steps") + self._last_move_subgoal = _online_subgoal(getattr(env_runner, "info", {})) + return RuntimeEpisodeBinding( + start=deepcopy(start), + source_identity_sha256=source_identity_sha256, + source_contract_sha256=source_contract_sha256, + ) + + def observe_after_step( + self, + env_runner: Any, + *, + runtime_step: int, + terminal_outcome: Mapping[str, Any] | None = None, + ) -> tuple[Mapping[str, Any], ...]: + """Observe one returned simulator state and enqueue only causal events. + + A terminal outcome describes the result of the action that produced + this exact state. Successful PickXtimes and video tasks emit a final + ``task_complete`` event. MoveCube completion remains the real final + ``step_complete`` transition, while failed/timeout/unknown outcomes + only cause the already-observed events to be delivered. + """ + + if self._task_env is None or self._task_id is None or self._episode_id is None: + raise RuntimeReadError("begin_episode must succeed before observe_after_step") + if self._terminal_outcome is not None: + raise RuntimeReadError("rollout already observed a terminal outcome") + runtime_step = _nat(runtime_step, "runtime_step") + if runtime_step <= self._last_runtime_step: + raise RuntimeReadError("rollout runtime_step must increase after env.step") + env = getattr(env_runner, "env", None) + if env is None or _unwrapped(env) is not self._task_env: + raise RuntimeReadError("RoboMME environment instance changed within an episode") + + emitted: list[dict[str, Any]] = [] + if self._task_id == "PickXtimes": + emitted.extend(self._observe_pick(runtime_step)) + elif self._task_id == "MoveCube": + emitted.extend(self._observe_move(getattr(env_runner, "info", {}), runtime_step)) + outcome = _terminal_outcome(terminal_outcome) + if outcome is not None: + if outcome["status"] == "success": + if self._task_id == "MoveCube": + if ( + self._last_move_subgoal != "all tasks completed" + or self._move_completions != self._move_step_count + ): + raise RuntimeReadError("successful MoveCube terminal state did not complete its live procedure") + else: + if self._task_id == "PickXtimes": + assert self._last_task_timestep is not None + assert self._target_cycles is not None + if self._last_task_timestep < 2 * self._target_cycles: + raise RuntimeReadError("successful PickXtimes terminal state precedes its target cycles") + emitted.append(self._terminal_completion(runtime_step, outcome)) + self._terminal_outcome = deepcopy(outcome) + self._pending.extend(emitted) + self._last_runtime_step = runtime_step + return tuple(deepcopy(emitted)) + + def peek_add_buffer_payload(self) -> dict[str, Any]: + """Return the current delivery without committing any producer state. + + Until an exact ACK arrives, every call returns a byte-equivalent deep + copy of the same in-flight batch. Events observed after the batch was + formed remain queued for the next sequence and cannot be removed by + acknowledgement of the older delivery. + """ + + if self._start is None: + raise RuntimeReadError("Phase-A producer has no active episode") + if self._inflight is None: + body = { + "schema_version": RUNTIME_BATCH_SCHEMA_VERSION, + "batch_sequence": self._next_batch_sequence, + "previous_batch_sha256": self._last_acked_batch_sha256, + "start": None if self._start_sent else deepcopy(self._start), + "events": deepcopy(self._pending), + } + self._inflight = {**body, "batch_sha256": canonical_json_sha256(body)} + self._inflight_event_count = len(self._pending) + return deepcopy(self._inflight) + + def acknowledge_add_buffer_payload(self, raw: Mapping[str, Any]) -> dict[str, Any]: + """Commit exactly the currently in-flight delivery after server ACK.""" + + if not isinstance(raw, Mapping) or set(raw) != _ACK_FIELDS: + raise RuntimeReadError("Phase-A rollout ACK fields mismatch") + if raw["schema_version"] != RUNTIME_ACK_SCHEMA_VERSION: + raise RuntimeReadError("Phase-A rollout ACK schema_version mismatch") + sequence = _nat(raw["batch_sequence"], "ack.batch_sequence") + batch_sha256 = _sha256(raw["batch_sha256"], "ack.batch_sha256") + if not isinstance(raw["duplicate"], bool): + raise RuntimeReadError("Phase-A rollout ACK duplicate must be boolean") + receipt = raw["runtime_receipt"] + receipt = _validated_runtime_receipt(receipt) + if self._inflight is None: + raise RuntimeReadError("Phase-A rollout ACK arrived without an in-flight batch") + if sequence != self._inflight["batch_sequence"]: + raise RuntimeReadError("Phase-A rollout ACK batch_sequence differs from in-flight") + if batch_sha256 != self._inflight["batch_sha256"]: + raise RuntimeReadError("Phase-A rollout ACK batch_sha256 differs from in-flight") + if self._inflight_event_count > len(self._pending): + raise RuntimeReadError("Phase-A rollout pending queue regressed before ACK") + if self._pending[: self._inflight_event_count] != self._inflight["events"]: + raise RuntimeReadError("Phase-A rollout pending prefix drifted before ACK") + if receipt.get("identity_sha256") != self._identity_sha256: + raise RuntimeReadError("Phase-A rollout ACK receipt identity differs from the episode") + if receipt.get("task_id") != self._task_id or receipt.get("episode_id") != self._episode_id: + raise RuntimeReadError("Phase-A rollout ACK receipt episode binding mismatch") + if receipt.get("manager_mode") != self._manager_mode.value: + raise RuntimeReadError("Phase-A rollout ACK receipt manager_mode mismatch") + self._validate_ack_receipt_progression(receipt) + + del self._pending[: self._inflight_event_count] + if self._inflight["start"] is not None: + self._start_sent = True + self._last_acked_batch_sha256 = batch_sha256 + self._next_batch_sequence += 1 + self._last_acked_runtime_receipt = deepcopy(receipt) + self._inflight = None + self._inflight_event_count = 0 + return deepcopy(dict(raw)) + + def _validate_ack_receipt_progression(self, receipt: Mapping[str, Any]) -> None: + """Bind one valid receipt to exactly the current in-flight event suffix.""" + + if self._inflight is None: + raise RuntimeReadError("Phase-A rollout ACK has no in-flight lineage") + previous = self._last_acked_runtime_receipt + previous_event_ids = [] if previous is None else _receipt_event_ids(previous, "previous runtime_receipt") + previous_events = [] if previous is None else _receipt_runtime_events(previous, "previous runtime_receipt") + base_revision = 0 if previous is None else _receipt_nat(previous, "next_revision", "previous runtime_receipt") + base_ordinal = ( + len(self._initial_event_ids) + if previous is None + else _receipt_nat(previous, "next_event_ordinal", "previous runtime_receipt") + ) + + initial_event_ids = _receipt_event_ids( + receipt, + "runtime_receipt", + field="initial_event_ids", + ) + if initial_event_ids != list(self._initial_event_ids): + raise RuntimeReadError("Phase-A rollout ACK initial_event_ids mismatch") + + inflight_event_ids: list[str] = [] + inflight_bindings: list[dict[str, Any]] = [] + for index, raw_envelope in enumerate(self._inflight["events"]): + if not isinstance(raw_envelope, Mapping): + raise RuntimeReadError("Phase-A in-flight event envelope is not a mapping") + event = raw_envelope.get("event") + if not isinstance(event, Mapping): + raise RuntimeReadError("Phase-A in-flight runtime event is not a mapping") + event_id = _text(event.get("event_id"), f"inflight.events[{index}].event_id") + revision = _nat(event.get("revision"), f"inflight.events[{index}].revision") + ordinal = _nat(event.get("event_ordinal"), f"inflight.events[{index}].event_ordinal") + if revision != base_revision + index: + raise RuntimeReadError("Phase-A in-flight event revision is not contiguous with its ACK base") + if ordinal != base_ordinal + index: + raise RuntimeReadError("Phase-A in-flight event ordinal is not contiguous with its ACK base") + inflight_event_ids.append(event_id) + inflight_bindings.append( + { + "event_id": event_id, + "runtime_step": _nat( + event.get("runtime_step"), + f"inflight.events[{index}].runtime_step", + ), + "event_sha256": _sha256( + event.get("event_sha256"), + f"inflight.events[{index}].event_sha256", + ), + "source_state_sha256": _sha256( + event.get("source_state_sha256"), + f"inflight.events[{index}].source_state_sha256", + ), + } + ) + + event_ids = _receipt_event_ids(receipt, "runtime_receipt") + expected_event_ids = [*previous_event_ids, *inflight_event_ids] + if event_ids != expected_event_ids: + raise RuntimeReadError("Phase-A rollout ACK runtime_event_ids do not match its batch lineage") + + runtime_events = _receipt_runtime_events(receipt, "runtime_receipt") + if runtime_events[: len(previous_events)] != previous_events: + raise RuntimeReadError("Phase-A rollout ACK runtime_events changed its committed prefix") + suffix = runtime_events[len(previous_events) :] + if len(suffix) != len(inflight_bindings): + raise RuntimeReadError("Phase-A rollout ACK runtime_events length does not match its batch") + for index, (event_receipt, expected) in enumerate(zip(suffix, inflight_bindings, strict=True)): + actual = {field: event_receipt.get(field) for field in _RUNTIME_EVENT_RECEIPT_BINDING_FIELDS} + if actual != expected: + raise RuntimeReadError(f"Phase-A rollout ACK runtime_events[{index}] is not bound to its batch event") + + expected_revision = base_revision + len(inflight_event_ids) + if _receipt_nat(receipt, "next_revision", "runtime_receipt") != expected_revision: + raise RuntimeReadError("Phase-A rollout ACK next_revision does not match its batch lineage") + expected_ordinal = base_ordinal + len(inflight_event_ids) + if _receipt_nat(receipt, "next_event_ordinal", "runtime_receipt") != expected_ordinal: + raise RuntimeReadError("Phase-A rollout ACK next_event_ordinal does not match its batch lineage") + + def _terminal_completion( + self, + runtime_step: int, + outcome: Mapping[str, Any], + ) -> dict[str, Any]: + assert self._task_id is not None + assert self._episode_id is not None + observed_state = { + "schema_version": PRODUCER_SCHEMA_VERSION, + "task_id": self._task_id, + "episode_id": self._episode_id, + "runtime_step": runtime_step, + "terminal_outcome": deepcopy(dict(outcome)), + } + return self._envelope( + runtime_step=runtime_step, + event_id=f"{self._episode_id}:runtime:task-complete", + kind="task_complete", + evidence=None, + observed_state=observed_state, + ) + + def _observe_pick(self, runtime_step: int) -> list[dict[str, Any]]: + assert self._task_env is not None + assert self._last_task_timestep is not None + assert self._target_cycles is not None + timestep = _nat(_required_attr(self._task_env, "timestep"), "PickXtimes.timestep") + if timestep < self._last_task_timestep: + raise RuntimeReadError("PickXtimes simulator timestep regressed") + if timestep > 2 * self._target_cycles + 1: + raise RuntimeReadError("PickXtimes simulator timestep exceeds target-cycle protocol") + result: list[dict[str, Any]] = [] + for edge in range(self._last_task_timestep + 1, timestep + 1): + if edge > 2 * self._target_cycles: + continue + if edge % 2 == 1: + self._cycle_start_step = runtime_step + continue + cycle = edge // 2 + start = self._cycle_start_step if self._cycle_start_step is not None else runtime_step + observed_state = { + "schema_version": PRODUCER_SCHEMA_VERSION, + "task_id": "PickXtimes", + "episode_id": self._episode_id, + "runtime_step": runtime_step, + "task_timestep": timestep, + "target_cycles": self._target_cycles, + "completed_cycle": cycle, + } + result.append( + self._envelope( + runtime_step=runtime_step, + event_id=f"{self._episode_id}:runtime:cycle:{cycle}", + kind="cycle_complete", + evidence=(min(start, runtime_step), runtime_step), + observed_state=observed_state, + ) + ) + self._cycle_start_step = runtime_step + self._last_task_timestep = timestep + return result + + def _observe_move(self, info: Any, runtime_step: int) -> list[dict[str, Any]]: + current = _online_subgoal(info) + previous = self._last_move_subgoal + self._last_move_subgoal = current + if previous is None or current is None or current == previous: + return [] + if previous in {"", "static", "no record", "all tasks completed"}: + return [] + if self._move_completions >= self._move_step_count: + return [] + self._move_completions += 1 + observed_state = { + "schema_version": PRODUCER_SCHEMA_VERSION, + "task_id": "MoveCube", + "episode_id": self._episode_id, + "runtime_step": runtime_step, + "completed_subgoal": previous, + "next_subgoal": current, + "completed_step_index": self._move_completions, + } + return [ + self._envelope( + runtime_step=runtime_step, + event_id=f"{self._episode_id}:runtime:step:{self._move_completions}", + kind="step_complete", + evidence=None, + observed_state=observed_state, + ) + ] + + def _envelope( + self, + *, + runtime_step: int, + event_id: str, + kind: str, + evidence: tuple[int, int] | None, + observed_state: Mapping[str, Any], + ) -> dict[str, Any]: + assert self._identity_sha256 is not None + assert self._task_id is not None + assert self._episode_id is not None + wire = build_runtime_event( + identity_sha256=self._identity_sha256, + task_id=self._task_id, + episode_id=self._episode_id, + runtime_step=runtime_step, + revision=self._revision, + event_id=event_id, + event_ordinal=self._event_ordinal, + kind=kind, + evidence=evidence, + value=None, + bindings=None, + confidence=1.0, + source_state_sha256=runtime_state_sha256(observed_state), + ) + self._revision += 1 + self._event_ordinal += 1 + return { + "schema_version": RUNTIME_ENVELOPE_SCHEMA_VERSION, + "event": wire, + "observed_source_state": deepcopy(dict(observed_state)), + } + + def _clear_episode(self) -> None: + self._task_env = None + self._task_id = None + self._episode_id = None + self._identity_sha256 = None + self._start = None + self._start_sent = False + self._pending.clear() + self._next_batch_sequence = 0 + self._last_acked_batch_sha256 = GENESIS_BATCH_SHA256 + self._inflight = None + self._inflight_event_count = 0 + self._last_acked_runtime_receipt = None + self._initial_event_ids = () + self._revision = 0 + self._event_ordinal = 0 + self._last_runtime_step = -1 + self._terminal_outcome = None + self._last_task_timestep = None + self._target_cycles = None + self._cycle_start_step = None + self._last_move_subgoal = None + self._move_completions = 0 + self._move_step_count = 0 + + +def attach_runtime_to_buffer( + buffer_payload: Mapping[str, Any], + producer: RoboMMEPhaseAOracleProducer, +) -> dict[str, Any]: + """Copy a normal RoboMME buffer request and attach the strict runtime batch.""" + + if not isinstance(buffer_payload, Mapping) or buffer_payload.get("add_buffer") is not True: + raise RuntimeReadError("Phase-A runtime can attach only to an add_buffer request") + if "picmem_phase_a_runtime" in buffer_payload: + raise RuntimeReadError("add_buffer already contains a Phase-A runtime payload") + return {**dict(buffer_payload), "picmem_phase_a_runtime": producer.peek_add_buffer_payload()} + + +def acknowledge_runtime_buffer( + buffer_payload: Mapping[str, Any], + response: Mapping[str, Any], + producer: RoboMMEPhaseAOracleProducer, +) -> dict[str, Any]: + """Validate one completed host response and commit its producer delivery.""" + + if not isinstance(buffer_payload, Mapping): + raise RuntimeReadError("Phase-A ACK requires the original add_buffer request") + batch = buffer_payload.get("picmem_phase_a_runtime") + if not isinstance(batch, Mapping): + raise RuntimeReadError("Phase-A ACK request is missing its runtime batch") + if not isinstance(response, Mapping) or response.get("add_buffer_finished") is not True: + raise RuntimeReadError("Phase-A add_buffer response is not complete") + ack = response.get("picmem_phase_a_runtime_ack") + if not isinstance(ack, Mapping): + raise RuntimeReadError("Phase-A add_buffer response is missing its runtime ACK") + if ack.get("batch_sequence") != batch.get("batch_sequence"): + raise RuntimeReadError("Phase-A response ACK sequence differs from its request") + if ack.get("batch_sha256") != batch.get("batch_sha256"): + raise RuntimeReadError("Phase-A response ACK hash differs from its request") + return producer.acknowledge_add_buffer_payload(ack) + + +def _build_full_source_contract( + *, + task_id: str, + episode_id: int, + instruction: str, + dataset_version: str, + source_path: str, + reset_steps: list[dict[str, Any]], + exec_start_step: int, + episode_end_step: int, + task_env: Any, + first_images: Sequence[Any], +) -> dict[str, Any]: + contract_spec = task_schema_for(task_id, instruction).contracts[0] + timeline: list[dict[str, Any]] = [] + if task_id in {"MoveCube", "VideoPlaceButton"}: + sentinel = { + "step": exec_start_step, + "simple_subgoal": "no record", + "grounded_subgoal": "no record", + "is_video_demo": False, + "is_subgoal_boundary": False, + "is_completed": False, + } + annotation = annotate_episode_from_steps( + task_id=task_id, + episode_id=episode_id, + steps=[*deepcopy(reset_steps), sentinel], + instruction=instruction, + dataset_version=dataset_version, + split="test", + source_path=source_path, + contract_source="runtime_reset_simulator", + policy_input_fields=["runtime visual history only"], + contract_variant="coarse", + ).to_json() + matches = [ + value for value in annotation.get("contracts", []) if value.get("contract_id") == contract_spec.contract_id + ] + if len(matches) != 1: + raise RuntimeReadError(f"{task_id} reset did not derive one exact primary contract") + timeline = deepcopy(matches[0].get("value_timeline", [])) + if not timeline: + raise RuntimeReadError(f"{task_id} reset did not derive initial oracle evidence") + elif task_id == "VideoUnmask": + actor = _required_attr(task_env, "bin_0") + point = _project_actor(task_env, actor, first_images) + timeline = [ + { + "step": exec_start_step - 1, + "evidence_interval": [0, exec_start_step - 1], + "value": point, + "confidence": 1.0, + "source": "runtime_simulator_oracle", + "update_kind": "set_once_from_reveal_or_grounded_subgoal", + } + ] + return { + "contract_id": contract_spec.contract_id, + "query": contract_spec.query, + "semantic_type": contract_spec.semantic_type.value, + "reducer_type": contract_spec.reducer_type.value, + "open_step": contract_spec.open_step, + "use_intervals": [[exec_start_step, episode_end_step]], + "value_timeline": timeline, + } + + +def _initial_candidates( + *, + task_id: str, + episode_id: int, + instruction: str, + episode_end_step: int, + exec_start_step: int, + source_contract: Mapping[str, Any], +) -> tuple[Any, ...]: + annotation = { + "task_id": task_id, + "episode_id": episode_id, + "task_instruction": instruction, + "num_steps": episode_end_step + 1, + "exec_start_step": exec_start_step, + "contracts": [deepcopy(dict(source_contract))], + "ordered_subgoals": [], + } + return tuple(events_from_sidecar(annotation)) + + +def _reset_steps_from_env(env: Any, *, exec_start_step: int, task_id: str) -> list[dict[str, Any]]: + if exec_start_step == 0: + return [] + wrapper = env + seen: set[int] = set() + demonstration_data: Any | None = None + while wrapper is not None and id(wrapper) not in seen: + seen.add(id(wrapper)) + values = getattr(wrapper, "__dict__", None) + if isinstance(values, dict) and "demonstration_data" in values: + demonstration_data = values["demonstration_data"] + break + wrapper = values.get("env") if isinstance(values, dict) else None + if not isinstance(demonstration_data, tuple) or len(demonstration_data) != 5: + raise RuntimeReadError(f"{task_id} runtime demonstration_data is unavailable") + info = demonstration_data[4] + if not isinstance(info, Mapping): + raise RuntimeReadError("RoboMME runtime demonstration info batch is unavailable") + fields = ( + "simple_subgoal", + "grounded_subgoal", + "is_video_demo", + "is_subgoal_boundary", + "is_completed", + ) + columns = {name: info.get(name) for name in fields} + if any(not isinstance(value, Sequence) or isinstance(value, (str, bytes)) for value in columns.values()): + raise RuntimeReadError("RoboMME reset is missing exact demonstration annotation columns") + if any(len(value) != exec_start_step + 1 for value in columns.values()): + raise RuntimeReadError("RoboMME demonstration columns do not align with reset images") + result: list[dict[str, Any]] = [] + for step in range(exec_start_step): + simple = _canonical_subgoal(columns["simple_subgoal"][step]) + grounded = _canonical_subgoal(columns["grounded_subgoal"][step]) + row = { + "step": step, + "simple_subgoal": simple, + "grounded_subgoal": grounded, + "is_video_demo": _bool(columns["is_video_demo"][step], "is_video_demo"), + "is_subgoal_boundary": _bool(columns["is_subgoal_boundary"][step], "is_subgoal_boundary"), + "is_completed": _bool(columns["is_completed"][step], "is_completed"), + } + if not row["is_video_demo"] or row["is_completed"]: + raise RuntimeReadError("RoboMME reset prefix is not a pure uncompleted demonstration") + result.append(row) + if _bool(columns["is_video_demo"][exec_start_step], "execution is_video_demo"): + raise RuntimeReadError("RoboMME execution boundary is still marked as video demonstration") + return result + + +def _simulator_source_identity( + task_env: Any, + *, + task_id: str, + episode_id: int, + instruction: str, + source_path: str, + exec_start_step: int, + episode_end_step: int, +) -> dict[str, Any]: + seed = getattr(task_env, "seed", 0) + if isinstance(seed, bool) or not isinstance(seed, (int, np.integer)): + raise RuntimeReadError("RoboMME simulator seed must be an integer") + difficulty = getattr(task_env, "difficulty", "unknown") + if not isinstance(difficulty, str) or not difficulty: + raise RuntimeReadError("RoboMME simulator difficulty must be non-empty") + spec = getattr(task_env, "task_spec", getattr(task_env, "spec", {})) + spec_sha256 = canonical_json_sha256(_plain_json(spec)) + return { + "schema_version": PRODUCER_SCHEMA_VERSION, + "task_id": task_id, + "episode_id": episode_id, + "instruction": instruction, + "source_path": source_path, + "seed": int(seed), + "difficulty": difficulty, + "simulator_spec_sha256": spec_sha256, + "exec_start_step": exec_start_step, + "episode_end_step": episode_end_step, + } + + +def _project_actor(task_env: Any, actor: Any, images: Sequence[Any]) -> dict[str, Any]: + image = np.asarray(images[-1]) + if image.ndim != 3 or image.shape[-1] not in (3, 4): + raise RuntimeReadError("RoboMME front image must have shape [H,W,3|4]") + camera = getattr(task_env, "front_camera", getattr(task_env, "camera", None)) + if camera is None: + raise RuntimeReadError("VideoUnmask simulator has no front camera") + intrinsic = _camera_matrix(camera, "get_intrinsic_matrix", "intrinsic_matrix") + if intrinsic.shape != (3, 3): + raise RuntimeReadError("RoboMME camera intrinsic matrix must be 3x3") + try: + extrinsic = _camera_matrix(camera, "get_extrinsic_matrix", "extrinsic_matrix") + except RuntimeReadError as exc: + model = _camera_matrix(camera, "get_model_matrix", "model_matrix") + if model.shape != (4, 4): + raise RuntimeReadError("RoboMME camera model matrix must be 4x4") from exc + try: + extrinsic = np.linalg.inv(model) + except np.linalg.LinAlgError as exc: + raise RuntimeReadError("RoboMME camera model matrix is singular") from exc + if extrinsic.shape not in {(3, 4), (4, 4)}: + raise RuntimeReadError("RoboMME camera extrinsic matrix must be 3x4 or 4x4") + position = _actor_position(actor) + world = np.concatenate((position, np.ones(1, dtype=np.float64))) + camera_point = extrinsic @ world + camera_xyz = camera_point[:3] + if not np.isfinite(camera_xyz).all() or camera_xyz[2] <= 0: + raise RuntimeReadError("VideoUnmask actor projects behind the front camera") + pixel = intrinsic @ camera_xyz + x = math.floor(float(pixel[0] / pixel[2]) + 0.5) + y = math.floor(float(pixel[1] / pixel[2]) + 0.5) + if not (0 <= x < image.shape[1] and 0 <= y < image.shape[0]): + raise RuntimeReadError("VideoUnmask actor projection is outside the front image") + return {"kind": "image_point", "x": x, "y": y} + + +def _camera_matrix(camera: Any, method: str, attribute: str) -> np.ndarray: + getter = getattr(camera, method, None) + raw = getter() if callable(getter) else getattr(camera, attribute, None) + if raw is None: + raise RuntimeReadError(f"RoboMME camera is missing {method}") + result = np.asarray(raw, dtype=np.float64) + if not np.isfinite(result).all(): + raise RuntimeReadError("RoboMME camera matrix must be finite") + return result + + +def _actor_position(actor: Any) -> np.ndarray: + if isinstance(actor, (np.ndarray, list, tuple)): + raw = actor + else: + pose = actor.get_pose() if callable(getattr(actor, "get_pose", None)) else getattr(actor, "pose", None) + raw = getattr(pose, "p", None) + result = np.asarray(raw, dtype=np.float64) + if result.shape == (1, 3): + result = result[0] + if result.shape != (3,) or not np.isfinite(result).all(): + raise RuntimeReadError("RoboMME actor position must be finite xyz") + return result + + +def _online_subgoal(info: Any) -> str | None: + if not isinstance(info, Mapping): + return None + raw = info.get("simple_subgoal_online", info.get("simple_subgoal")) + if isinstance(raw, Sequence) and not isinstance(raw, (str, bytes)): + raw = raw[-1] if raw else None + return _canonical_subgoal(raw) if isinstance(raw, str) else None + + +def _plain_json(value: Any) -> Any: + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, (float, np.floating)): + result = float(value) + if not math.isfinite(result): + raise RuntimeReadError("simulator identity contains non-finite values") + return result + if isinstance(value, np.integer): + return int(value) + if isinstance(value, np.ndarray): + return _plain_json(value.tolist()) + if isinstance(value, Mapping): + return {str(key): _plain_json(child) for key, child in value.items()} + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + return [_plain_json(child) for child in value] + # Gym specs are objects; bind their stable public identifier rather than a + # repr that can contain an address. + identifier = getattr(value, "id", None) + if isinstance(identifier, str) and identifier: + return {"id": identifier} + raise RuntimeReadError(f"simulator identity contains unsupported {type(value).__name__}") + + +def _unwrapped(env: Any) -> Any: + value = getattr(env, "unwrapped", None) + if value is None: + raise RuntimeReadError("RoboMME environment has no unwrapped task instance") + return value + + +def _required_attr(value: Any, name: str) -> Any: + if not hasattr(value, name): + raise RuntimeReadError(f"RoboMME simulator is missing required current field {name!r}") + return getattr(value, name) + + +def _canonical_instruction(value: Any) -> str: + if not isinstance(value, str) or not value.strip(): + raise RuntimeReadError("RoboMME task_goal must be a non-empty string") + return " ".join(value.strip().lower().split()) + + +def _canonical_subgoal(value: Any) -> str: + if not isinstance(value, str): + raise RuntimeReadError("RoboMME subgoal must be a string") + return " ".join(value.strip().lower().split()) + + +def _bool(value: Any, name: str) -> bool: + if not isinstance(value, (bool, np.bool_)): + raise RuntimeReadError(f"RoboMME {name} must be boolean") + return bool(value) + + +def _terminal_outcome(value: Mapping[str, Any] | None) -> dict[str, Any] | None: + if value is None: + return None + if not isinstance(value, Mapping) or set(value) != _TERMINAL_OUTCOME_FIELDS: + raise RuntimeReadError("terminal_outcome fields mismatch") + if not isinstance(value["stop"], (bool, np.bool_)) or not bool(value["stop"]): + raise RuntimeReadError("terminal_outcome.stop must be true") + status = value["status"] + if not isinstance(status, str) or status not in TERMINAL_STATUSES: + raise RuntimeReadError("terminal_outcome.status is unsupported") + return {"stop": True, "status": status} + + +def _receipt_event_ids( + receipt: Mapping[str, Any], + name: str, + *, + field: str = "runtime_event_ids", +) -> list[str]: + raw = receipt.get(field) + if not isinstance(raw, list) or any(not isinstance(value, str) or not value or "\0" in value for value in raw): + raise RuntimeReadError(f"Phase-A rollout ACK {name}.{field} must be a list of event IDs") + return list(raw) + + +def _receipt_runtime_events(receipt: Mapping[str, Any], name: str) -> list[dict[str, Any]]: + raw = receipt.get("runtime_events") + if not isinstance(raw, list) or any(not isinstance(value, Mapping) for value in raw): + raise RuntimeReadError(f"Phase-A rollout ACK {name}.runtime_events must be a list of mappings") + return [deepcopy(dict(value)) for value in raw] + + +def _receipt_nat(receipt: Mapping[str, Any], field: str, name: str) -> int: + return _nat(receipt.get(field), f"ACK {name}.{field}") + + +def _text(value: Any, name: str) -> str: + if not isinstance(value, str) or not value or "\0" in value: + raise RuntimeReadError(f"{name} must be a non-empty string without NUL") + return value + + +def _validated_runtime_receipt(value: Any) -> dict[str, Any]: + if not isinstance(value, Mapping): + raise RuntimeReadError("Phase-A rollout ACK runtime_receipt must be a mapping") + receipt = deepcopy(dict(value)) + if receipt.get("schema_version") != RUNTIME_RECEIPT_SCHEMA_VERSION: + raise RuntimeReadError("Phase-A rollout ACK runtime_receipt schema_version mismatch") + receipt_sha256 = _sha256( + receipt.get("receipt_sha256"), + "ack.runtime_receipt.receipt_sha256", + ) + body = {name: child for name, child in receipt.items() if name != "receipt_sha256"} + if canonical_json_sha256(body) != receipt_sha256: + raise RuntimeReadError("Phase-A rollout ACK runtime_receipt hash mismatch") + return receipt + + +def _sha256(value: Any, name: str) -> str: + if ( + not isinstance(value, str) + or len(value) != 64 + or any(character not in "0123456789abcdef" for character in value) + ): + raise RuntimeReadError(f"{name} must be lowercase SHA-256") + return value + + +def _nat(value: Any, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) < 0: + raise RuntimeReadError(f"{name} must be a non-negative integer") + return int(value) + + +def _pos(value: Any, name: str) -> int: + result = _nat(value, name) + if result <= 0: + raise RuntimeReadError(f"{name} must be positive") + return result + + +__all__ = [ + "GENESIS_BATCH_SHA256", + "PRODUCER_SCHEMA_VERSION", + "RUNTIME_ACK_SCHEMA_VERSION", + "RUNTIME_BATCH_SCHEMA_VERSION", + "RUNTIME_ENVELOPE_SCHEMA_VERSION", + "RUNTIME_RECEIPT_SCHEMA_VERSION", + "RUNTIME_START_SCHEMA_VERSION", + "RoboMMEPhaseAOracleProducer", + "RuntimeEpisodeBinding", + "acknowledge_runtime_buffer", + "attach_runtime_to_buffer", +] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_baseline.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..e7f02dfbfeabf408a3353d693037a441a67127a0 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_baseline.py @@ -0,0 +1,625 @@ +"""Franka converted HDF5 to the existing pi05 baseline training pipeline. + +Run with the robomme environment and the checkout root and robomme/src on PYTHONPATH. +Only converted HDF5 is read. No ROS runtime or raw bags are needed. +""" + +from __future__ import annotations + +import argparse +import dataclasses +import json +import pickle +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import cv2 +import h5py +import numpy as np + +BASE = "_cam_base_camera_color_image_raw_compressed" +WRIST = "_cam_hand_camera_color_image_raw_compressed" +POSE = "_franka_robot_state_broadcaster_current_pose" +PROMPTS = { + "pick3": "Pick up the cube and place it on the plate exactly three times, lifting it clear between placements, then press the blue button.", + "button_order": "Press the buttons in the same order as shown in the demonstration.", + "shuffle": "Track the cup hiding the cube during the shuffle, then press the button next to that cup.", +} + + +def canonical_pose(pose): + """Cartesian xyz + unit xyzw, in the qx-positive chart used by these demos.""" + pose = np.array(pose, dtype=np.float32, copy=True) + quaternion = pose[..., 3:7] + norm = np.linalg.norm(quaternion, axis=-1, keepdims=True) + if np.any(norm < 1e-6) or not np.isfinite(pose).all(): + raise ValueError("Pose must be finite with a nonzero quaternion") + quaternion /= norm + # This dataset keeps the tool facing down. Reject a crossing of this chart + # instead of introducing a discontinuity; other workspaces need another chart. + if np.any(np.abs(quaternion[..., 0]) < 0.1): + raise ValueError("Quaternion is outside this dataset's qx-positive chart") + quaternion *= np.where(quaternion[..., :1] < 0, -1, 1) + return pose + + +def command_targets(timestamps, joy_timestamps, buttons, initial_open): + """14=open, 15=close; pressed command persists after button release. + + Use the recorded Joy event time, not the nearest RGB frame, so a future + command cannot enter an earlier target. Simultaneous commands are unknown. + """ + order = np.argsort(joy_timestamps, kind="stable") + result = np.empty(len(timestamps), dtype=np.float32) + latch = initial_open + cursor = 0 + for i, stamp in enumerate(timestamps): + while cursor < len(order) and joy_timestamps[order[cursor]] <= stamp: + opened, closed = buttons[order[cursor], 14:16] != 0 + if opened or closed: + latch = np.nan if opened and closed else float(opened) + cursor += 1 + result[i] = latch + return result + + +def window_starts(timestamps, valid, horizon): + """Complete windows on the original ~15 Hz clock, never across a data gap.""" + if horizon <= 0: + raise ValueError("action horizon must be positive") + if len(timestamps) < horizon: + return np.empty(0, dtype=np.int64) + good = np.lib.stride_tricks.sliding_window_view(valid, horizon).all(axis=1) + if horizon > 1: + dt = np.diff(timestamps) + gaps_ok = (dt > 0) & (dt <= 100_000_000) + good &= np.lib.stride_tricks.sliding_window_view(gaps_ok, horizon - 1).all(axis=1) + return np.flatnonzero(good) + + +def initial_target(timestamps, joy_timestamps, buttons, widths): + """Infer a recording-start command only from its uninterrupted endpoint. + + A gripper can still be moving when recording starts. The first measured + width is therefore not its target. This uses the pre-command response as + offline supervision only; no future measurements become model inputs. + """ + events = joy_timestamps[np.any(buttons[:, 14:16], axis=1)] + prefix = widths[timestamps < events.min()] if len(events) else widths + prefix = prefix[np.isfinite(prefix)] + if len(prefix) < 5 or np.ptp(prefix[-5:]) > 0.05: + return np.nan + if np.all(prefix[-5:] >= 0.9) and np.all(np.diff(prefix) >= -0.05): + return 1.0 + if np.all(prefix[-5:] <= 0.1) and np.all(np.diff(prefix) <= 0.05): + return 0.0 + return np.nan + + +def decode_image(dataset): + image = cv2.imdecode(dataset[:], cv2.IMREAD_COLOR) + if image is None: + raise ValueError(f"Invalid JPEG: {dataset.name}") + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + return prepare_rgb(image) + + +def prepare_rgb(image): + """The same RGB resize/padding for converted data and online inference.""" + image = np.asarray(image) + if image.shape[:2] == (224, 224): + return image + h, w = image.shape[:2] + scale = 224 / max(h, w) + image = cv2.resize(image, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_LINEAR) + result = np.zeros((224, 224, 3), dtype=np.uint8) + y, x = (224 - image.shape[0]) // 2, (224 - image.shape[1]) // 2 + result[y : y + image.shape[0], x : x + image.shape[1]] = image + return result + + +def convert_episode(args): + path, output, episode_id, horizon = args + cv2.setNumThreads(1) + with h5py.File(path, "r") as source: + keys = sorted(source) + n = len(keys) + timestamps = np.zeros(n, dtype=np.int64) + joy_timestamps = np.zeros(n, dtype=np.int64) + buttons = np.zeros((n, 16), dtype=np.int32) + state = np.full((n, 8), np.nan, dtype=np.float32) + actions = np.full((n, 8), np.nan, dtype=np.float32) + valid = np.zeros(n, dtype=bool) + action_synced = np.zeros(n, dtype=bool) + missing_wrist = 0 + required = [ + BASE, + WRIST, + POSE + "_position", + POSE + "_orientation", + "_target_pose_position", + "_target_pose_orientation", + "_franka_gripper_joint_states/position", + ] + for i, key in enumerate(keys): + frame = source[key] + timestamps[i] = frame.attrs["timestamp"] + joy_timestamps[i] = frame["original_timestamps"].attrs.get("_spacenav_joy", timestamps[i]) + if "_spacenav_joy_buttons" in frame: + values = frame["_spacenav_joy_buttons"][:] + buttons[i, : min(16, len(values))] = values[:16] + if "_franka_gripper_joint_states/position" in frame: + gripper = frame["_franka_gripper_joint_states"] + names = [name.decode() for name in gripper["joint_names"][:]] + if len(names) != 2 or not all("finger_joint" in name for name in names): + raise ValueError(f"Unexpected gripper joints: {names}") + state[i, 7] = np.sum(gripper["position"][:]) / 0.08 + if "_target_pose_position" in frame and "_target_pose_orientation" in frame: + actions[i, :7] = canonical_pose( + np.r_[frame["_target_pose_position"][:], frame["_target_pose_orientation"][:]] + ) + action_synced[i] = abs(frame["sync_quality"].attrs.get("_target_pose", np.inf)) <= 40_000_000 + missing_wrist += WRIST not in frame + if not all(k in frame for k in required): + continue + state[i, :7] = canonical_pose(np.r_[frame[POSE + "_position"][:], frame[POSE + "_orientation"][:]]) + sync = frame["sync_quality"].attrs + valid[i] = all( + abs(sync.get(k, np.inf)) <= 40_000_000 for k in [WRIST, POSE, "_franka_gripper_joint_states"] + ) + initial_open = initial_target(timestamps, joy_timestamps, buttons, state[:, 7]) + actions[:, 7] = command_targets(timestamps, joy_timestamps, buttons, initial_open) + valid &= np.isfinite(state).all(axis=1) + # Only the observation at the start of a chunk is a model input. + # Future action targets need synchronized commands, not future images. + action_valid = action_synced & np.isfinite(actions).all(axis=1) + starts = window_starts(timestamps, action_valid, horizon) + starts = starts[valid[starts]] + output.mkdir(parents=True, exist_ok=False) + for local_index, i in enumerate(starts): + frame = source[keys[i]] + sample = { + "image": decode_image(frame[BASE]), + "wrist_image": decode_image(frame[WRIST]), + "state": state[i], + "actions": actions[i : i + horizon], + "prompt": PROMPTS[path.parent.name], + "epis_idx": np.asarray(episode_id), + "step_idx": np.asarray(i), + "timestamp_ns": timestamps[i], + } + with (output / f"{local_index}.pkl").open("xb") as handle: + pickle.dump(sample, handle, protocol=pickle.HIGHEST_PROTOCOL) + summary = { + "episode": path.stem, + "task": path.parent.name, + "frames": n, + "samples": len(starts), + "missing_wrist": int(missing_wrist), + "invalid_frames": int((~valid).sum()), + "initial_gripper_open": float(initial_open) if np.isfinite(initial_open) else None, + "fps": float(1e9 / np.median(np.diff(timestamps))), + } + return summary, state[starts], actions[starts[:, None] + np.arange(horizon)] + + +def prepare(source, output, horizon=20, workers=8): + from openpi.shared import normalize + + files = sorted(Path(source).glob("*/*.h5")) + if not files: + raise ValueError("No converted HDF5 episodes found") + output = Path(output) + output.mkdir(parents=True, exist_ok=False) + splits = {"train": [], "validation": []} + # Split whole episodes, independently within each task, with a fixed seed. + rng = np.random.default_rng(42) + for task in sorted({p.parent.name for p in files}): + group = [p for p in files if p.parent.name == task] + order = rng.permutation(len(group)) + held_out = set(order[: max(1, round(len(group) * 0.1))]) + for i, path in enumerate(group): + splits["validation" if i in held_out else "train"].append(path) + stats = {key: normalize.RunningStats() for key in ["state", "actions"]} + summaries = [] + with ProcessPoolExecutor(workers) as pool: + for split, paths in splits.items(): + data_dir = output / split / "data" + data_dir.mkdir(parents=True) + jobs = [(path, output / "episodes" / path.stem, files.index(path), horizon) for path in paths] + count = 0 + for (summary, states, actions), job in zip(pool.map(convert_episode, jobs), jobs, strict=True): + summary["split"] = split + summaries.append(summary) + for i in range(summary["samples"]): + (job[1] / f"{i}.pkl").rename(data_dir / f"{count + i}.pkl") + job[1].rmdir() + count += summary["samples"] + if split == "train" and len(states): + stats["state"].update(states) + stats["actions"].update(actions) + print(json.dumps(summary), flush=True) + (output / split / "meta").mkdir() + (output / split / "meta" / "stats.json").write_text(json.dumps({"total_samples": count})) + normalize.save(output / "assets" / "franka", {key: value.get_statistics() for key, value in stats.items()}) + (output / "episodes").rmdir() + (output / "dataset.json").write_text( + json.dumps( + { + "source": str(Path(source).resolve()), + "action_horizon": horizon, + "representation": "absolute flange xyz, unit xyzw with qx positive, gripper open in [0,1]", + "gripper": ( + "Joy 14 open / 15 close, latched at original event timestamps; initial stable measured endpoint" + ), + "image_processing": "JPEG decode to RGB, aspect-preserving 224x224 bilinear resize with black padding", + "sync_tolerance_ms": 40, + "max_window_gap_ms": 100, + "prompts": PROMPTS, + "episodes": summaries, + }, + indent=2, + ) + ) + + +@dataclasses.dataclass(frozen=True) +class FrankaInputs: + disable_context_gripper_command: bool = False + + def __call__(self, data): + result = { + "image": {"base_0_rgb": data["image"], "left_wrist_0_rgb": data["wrist_image"]}, + "image_mask": {"base_0_rgb": np.True_, "left_wrist_0_rgb": np.True_}, + "state": np.r_[canonical_pose(data["state"][:7]), data["state"][7]].astype(np.float32), + "prompt": data["prompt"], + "simple_subgoal": None, + "grounded_subgoal": None, + } + if "actions" in data: + result["actions"] = data["actions"] + if "action_component_valid_mask" in data: + result["action_component_valid_mask"] = data["action_component_valid_mask"] + for key in [ + "static_image_emb", "static_pos_emb", "static_state_emb", "static_mask", + "current_subgoal", "transition_context_action_delta", "transition_context_state_delta", + "transition_context_relative_age", "transition_context_valid_mask", + "transition_span_target", "transition_last_span_target", "transition_status_valid", + "transition_last_span_valid", + ]: + if data.get(key) is not None: + result[key] = data[key] + if self.disable_context_gripper_command and "transition_context_action_delta" in result: + context = np.asarray(result["transition_context_action_delta"]).copy() + context[..., 7] = 0 + result["transition_context_action_delta"] = context + return result + + +@dataclasses.dataclass(frozen=True) +class FrankaOutputs: + def __call__(self, data): + actions = np.asarray(data["actions"])[..., :8].copy() + actions[..., :7] = canonical_pose(actions[..., :7]) + actions[..., 7] = np.clip(actions[..., 7], 0, 1) + return {"actions": actions} + + +@dataclasses.dataclass(frozen=True) +class ResizeOnlyWhenNeeded: + def __call__(self, data): + if all(image.shape[:2] == (224, 224) for image in data["image"].values()): + return data + return {**data, "image": {key: prepare_rgb(image) for key, image in data["image"].items()}} + + +@dataclasses.dataclass(frozen=True) +class FrankaDataConfig: + assets_path: str + partial_supervision: bool = False + disable_context_gripper_command: bool = False + + def create(self, assets_dirs, model_config): + from mme_vla_suite.training import config + from openpi import transforms + from openpi.shared import normalize + + stats = normalize.load(Path(self.assets_path)) + data_inputs = [FrankaInputs(self.disable_context_gripper_command)] + model_transforms = config.ModelTransformFactory()(model_config) + model_inputs = list(model_transforms.inputs) + if self.partial_supervision: + from integrations.robomme.franka_partial import BoundedStateForTokenization + + data_inputs.append(BoundedStateForTokenization(stats["state"])) + model_inputs = [ + dataclasses.replace( + transform, + tokenizer=config.PaligemmaTokenizer(model_config.max_token_len, reject_truncation=True), + state_input_key="state_for_tokenization", + ) if isinstance(transform, config.TokenizePromptWithMemory) else transform + for transform in model_inputs + ] + model_transforms = transforms.Group( + inputs=[ResizeOnlyWhenNeeded() if isinstance(transform, transforms.ResizeImages) else transform + for transform in model_inputs], + outputs=model_transforms.outputs, + ) + return config.DataConfig( + repo_id="franka", + asset_id="franka", + norm_stats=stats, + use_quantile_norm=not self.partial_supervision, + data_transforms=transforms.Group(inputs=data_inputs, outputs=[FrankaOutputs()]), + model_transforms=model_transforms, + ) + + +def equivalent_step_budget(reference_steps=25000, reference_batch=1, global_batch=4): + """Preserve example count and sample-based warmup/EMA timescales.""" + if min(reference_steps, reference_batch, global_batch) <= 0: + raise ValueError("Steps and batch sizes must be positive") + return { + "reference_steps": reference_steps, "reference_global_batch": reference_batch, + "global_batch": global_batch, "sample_exposures": reference_steps * reference_batch, + "steps": (reference_steps * reference_batch + global_batch - 1) // global_batch, + "warmup_steps": (1000 * reference_batch + global_batch - 1) // global_batch, + "ema_decay": .999 ** (global_batch / reference_batch), + } + + +FORMAL_BUDGET = equivalent_step_budget() + + +def model_repo_id(task, history_frames, step): + """User-facing names explicitly identify global/per-GPU batch and checkpoint.""" + variant = f"uniform{history_frames}" if history_frames else "baseline" + return f"fm-dev/pi05-{task.replace('_', '-')}-{variant}-lora-gbs4-pgb1-gpu4-step{step}" + + +def make_train_config( + dataset, run_root, steps=FORMAL_BUDGET["steps"], resume=False, uniform_history=False, + save_interval=5000, warmup_steps=FORMAL_BUDGET["warmup_steps"], decay_steps=FORMAL_BUDGET["steps"], + exp_name="button-order", log_interval=100, history_frames=32, +): + from mme_vla_suite.training import config + from openpi.training import optimizer, weight_loaders + + dataset, run_root = Path(dataset).resolve(), Path(run_root).resolve() + spec = json.loads((dataset / "dataset.json").read_text()) + partial = spec.get("partial_action_supervision", False) + cfg = config.get_config("pi05_baseline") + cfg = dataclasses.replace( + cfg, + name="pi05_franka_baseline", + exp_name=exp_name, + model=dataclasses.replace( + cfg.model, action_horizon=spec["action_horizon"], discrete_state_input=True, max_token_len=128 + ), + data=FrankaDataConfig(str(dataset / "assets" / "franka"), partial_supervision=partial), + dataset_path=str(dataset / "train"), + batch_size=4 if partial else 8, + fsdp_devices=1 if partial else 4, + num_workers=4 if partial else 0, + ema_decay=FORMAL_BUDGET["ema_decay"] if partial else 0.99, + num_train_steps=steps, + full_state_checkpoints=True, + lr_schedule=optimizer.CosineDecaySchedule( + warmup_steps=warmup_steps, peak_lr=5e-5 if partial else 2.5e-5, + decay_steps=decay_steps, decay_lr=5e-6 if partial else 2.5e-6, + ), + checkpoint_base_dir=str(run_root / "checkpoints"), + weight_loader=weight_loaders.CheckpointWeightLoader( + "/data/robomme/models/openpi/openpi-assets/checkpoints/pi05_base/params" + ), + save_interval=save_interval, + keep_period=save_interval, + log_interval=log_interval, + wandb_enabled=False, + resume=resume, + policy_metadata={ + "dataset": str(dataset), + "representation": spec["representation"], + "gripper": spec["gripper"], + "run_purpose": "fine-tuning" if steps > 110 else "local training pipeline validation", + "target_steps": steps, + "save_interval": save_interval, + "task": spec.get("task", "pick3 + button_order"), + "prompt": spec.get("prompts", {}).get(spec.get("task")), + "partial_action_supervision": partial, + "unsupervised_action_components": spec.get("unsupervised_action_components", []), + "current_state_tokens": spec.get("current_state_tokens", "legacy quantile input"), + }, + metrics_path=str(run_root / "metrics.tsv"), + ) + if uniform_history: + from mme_vla_suite.models.config.utils import resolve_history_config_path + + if history_frames not in (16, 32): + raise ValueError("Franka uniform history supports 16 or 32 frames") + history_path = resolve_history_config_path(f"perceptual-franka-uniform{history_frames}-modul.yaml") + cfg = dataclasses.replace( + cfg, + name=f"pi05_franka_uniform{history_frames}_baseline", + model=dataclasses.replace(cfg.model, use_history=True, history_config=str(history_path)), + policy_metadata={ + **cfg.policy_metadata, + "history": { + "sampling": "uniform over [0,t], inclusive", + "frames": history_frames, + "camera": "base", + "tokens_per_frame": 16, + "integration": "FrameSamp modulation", + }, + }, + ) + if partial: + from flax import nnx + from openpi.shared import nnx_utils + from integrations.robomme.franka_partial import CartesianWeightLoader + + model = dataclasses.replace( + cfg.model, action_dim=8, paligemma_variant="gemma_2b_lora", action_expert_variant="gemma_300m_lora" + ) + cfg = dataclasses.replace( + cfg, model=model, + freeze_filter=nnx.Any(model.get_freeze_filter(), nnx_utils.PathRegex("time_mlp_.*")), + weight_loader=CartesianWeightLoader(cfg.weight_loader.params_path), + policy_metadata={**cfg.policy_metadata, "training_recipe": { + "method": "LoRA + Cartesian projections + optional history modules", + "gpus": 4, "global_batch_size": 4, "fsdp_devices": 1, + "gradient_accumulation": 1, "action_dim": 8, "action_horizon": 20, + "max_token_len": 128, "ema_decay": FORMAL_BUDGET["ema_decay"], + "reference_steps": 25000, "reference_global_batch": 1, + "reference_ema_decay": .999, "reference_warmup_steps": 1000, + "sample_exposures": steps * 4, + "warmup_steps": warmup_steps, "decay_steps": decay_steps, + "peak_lr": 5e-5, "decay_lr": 5e-6, + }}, + ) + return cfg + + +def train(dataset, run_root, steps=FORMAL_BUDGET["steps"], resume=False, uniform_history=False, **training_options): + import os + import sys + + if uniform_history: + # Free temporary initialization buffers so concurrent policy servers + # can share the four GPUs. The model/batch/optimizer are unchanged. + os.environ.setdefault("XLA_PYTHON_CLIENT_ALLOCATOR", "platform") + root = Path(__file__).resolve().parents[2] + sys.path.insert(0, str(root / "robomme" / "scripts")) + import train as trainer + + config = make_train_config(dataset, run_root, steps, resume, uniform_history, **training_options) + config = dataclasses.replace(config, policy_metadata={ + **config.policy_metadata, "gpu_allocator": os.environ.get("XLA_PYTHON_CLIENT_ALLOCATOR", "default"), + }) + trainer.main(config) + assets = config.checkpoint_dir / str(steps) / "assets" + if uniform_history: + (assets / "history_config.yaml").write_text(Path(config.model.history_config).read_text()) + (assets / "policy_metadata.json").write_text(json.dumps(config.policy_metadata, indent=2)) + + +def replay(dataset, checkpoint, output, uniform_history=False, history_frames=32): + """Reload a serving checkpoint and run one held-out observation per episode.""" + from mme_vla_suite.policies.policy_config import create_trained_policy + + dataset, checkpoint = Path(dataset), Path(checkpoint) + config = make_train_config(dataset, checkpoint.parents[3], uniform_history=uniform_history, history_frames=history_frames) + policy = create_trained_policy(config, checkpoint) + spec = json.loads((dataset / "dataset.json").read_text()) + results = [] + offset = 0 + for episode in spec["episodes"]: + if episode["split"] != "validation": + continue + count = episode["samples"] + if count: + with (dataset / "validation" / "data" / f"{offset + count // 2}.pkl").open("rb") as handle: + sample = pickle.load(handle) + if uniform_history: + from picmem.data.semantic_transition.sampling import even_sampling_indices + + policy.reset() + step = int(sample["step_idx"]) + episode_id = int(sample["epis_idx"]) + for index in even_sampling_indices(step, policy._metadata["history"]["frames"]): + feature = dataset / "features" / f"episode_{episode_id}" / f"token_emb_{index}.npy" + policy.mem_buffer._history_feats[index] = np.load(feature, allow_pickle=True).item() + policy.step_idx = step + prediction = policy.infer({key: sample[key] for key in ["image", "wrist_image", "state", "prompt"]}) + actions = prediction["actions"] + if actions.shape != (spec["action_horizon"], 8) or not np.isfinite(actions).all(): + raise ValueError(f"Invalid policy output for {episode['episode']}") + results.append( + { + "episode": episode["episode"], + "task": episode["task"], + "shape": list(actions.shape), + "all_finite": True, + "gripper_range": [float(actions[:, 7].min()), float(actions[:, 7].max())], + "infer_time_ms": float(prediction["infer_time_ms"]), + } + ) + print(json.dumps(results[-1]), flush=True) + offset += count + Path(output).write_text( + json.dumps( + { + "checkpoint": str(checkpoint), + "observations": results, + "scope": "offline checkpoint load and finite-output check; no robot rollout", + }, + indent=2, + ) + ) + + +def load_policy(checkpoint): + """Load either formal model using only its exported checkpoint directory.""" + from mme_vla_suite.training import config as training_config + from mme_vla_suite.policies.policy_config import create_trained_policy + + checkpoint = Path(checkpoint).resolve() + metadata = json.loads((checkpoint / "assets/policy_metadata.json").read_text()) + if not metadata.get("partial_action_supervision"): + raise ValueError("This entrypoint expects the verified partial Cartesian8 training recipe") + cfg = training_config.get_config("pi05_baseline") + history_path = checkpoint / "assets/history_config.yaml" + cfg = dataclasses.replace( + cfg, + model=dataclasses.replace( + cfg.model, action_dim=8, action_horizon=20, + max_token_len=metadata.get("training_recipe", {}).get("max_token_len", 128), discrete_state_input=True, + paligemma_variant="gemma_2b_lora", action_expert_variant="gemma_300m_lora", + use_history=history_path.exists(), history_config=str(history_path) if history_path.exists() else None, + ), + data=FrankaDataConfig( + str(checkpoint / "assets/franka"), partial_supervision=True, + disable_context_gripper_command=metadata.get("disable_context_gripper_command", False), + ), + policy_metadata=metadata, + ) + return create_trained_policy(cfg, checkpoint) + + +def observe(policy, base_rgb, state): + """Append each observed source frame, including current, before uniform-history inference.""" + if policy.mem_buffer is None: + return + state = np.r_[canonical_pose(np.asarray(state)[:7]), np.asarray(state)[7]].astype(np.float32) + policy.add_buffer({"images": prepare_rgb(base_rgb)[None, None], "state": state[None]}) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + prep = commands.add_parser("prepare") + prep.add_argument("--source", type=Path, required=True) + prep.add_argument("--output", type=Path, required=True) + prep.add_argument("--horizon", type=int, default=20) + prep.add_argument("--workers", type=int, default=8) + training = commands.add_parser("train") + training.add_argument("--dataset", type=Path, required=True) + training.add_argument("--run-root", type=Path, required=True) + training.add_argument("--steps", type=int, default=FORMAL_BUDGET["steps"]) + training.add_argument("--resume", action="store_true") + training.add_argument("--uniform-history", action="store_true") + training.add_argument("--history-frames", type=int, choices=[16, 32], default=32) + training.add_argument("--save-interval", type=int, default=5000) + training.add_argument("--warmup-steps", type=int, default=FORMAL_BUDGET["warmup_steps"]) + training.add_argument("--decay-steps", type=int, default=FORMAL_BUDGET["steps"]) + training.add_argument("--exp-name", default="button-order") + training.add_argument("--log-interval", type=int, default=100) + replay_parser = commands.add_parser("replay") + replay_parser.add_argument("--dataset", type=Path, required=True) + replay_parser.add_argument("--checkpoint", type=Path, required=True) + replay_parser.add_argument("--output", type=Path, required=True) + replay_parser.add_argument("--uniform-history", action="store_true") + replay_parser.add_argument("--history-frames", type=int, choices=[16, 32], default=32) + args = vars(parser.parse_args()) + command = args.pop("command") + {"prepare": prepare, "train": train, "replay": replay}[command](**args) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_execution.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_execution.py new file mode 100644 index 0000000000000000000000000000000000000000..eb45f121b96e093ce58c228ff26da98622175403 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_execution.py @@ -0,0 +1,113 @@ +"""Select execution action rows while retaining each episode's complete visual history.""" +from __future__ import annotations + +import argparse +from collections import Counter +import copy +import json +from pathlib import Path +import pickle +import tempfile + +import numpy as np + +from integrations.robomme.franka_partial import validate_actions + + +def prepare(dataset, annotations, output): + from openpi.shared import normalize + + dataset, annotations, output = map(Path, (dataset, annotations, output)) + if output.exists(): + raise FileExistsError(f"Preserve the existing dataset: {output}") + spec = copy.deepcopy(json.loads((dataset / "dataset.json").read_text())) + task = spec["task"] + candidates = {} + for path in (annotations / "events-candidates-v1" / task).glob("*.json"): + record = json.loads(path.read_text()) + if "raw_episode_id" in record: + candidates[record["raw_episode_id"]] = record + writer_version = "writer-astra-real-v2" if task == "button_order" else "writer-astra-real-v1" + episodes = {record["episode_id"]: record for record in spec["episodes"]} + source_offsets, cursor = {}, 0 + for episode in spec["episodes"]: + source_offsets[episode["episode_id"]] = cursor + cursor += episode["frames"] + if episode["split"] == "excluded": + continue + annotation = candidates[episode["episode"]] + if annotation["total_frames"] != episode["frames"]: + raise ValueError(f"Annotation/frame count mismatch: {episode['episode']}") + writer = json.loads((annotations / writer_version / task / f"episode_{annotation['episode_id']:06d}.json").read_text()) + if writer["total_frames"] != episode["frames"] or writer["first_decision_frame"] != annotation["execution_start"]: + raise ValueError(f"Writer/phase boundary mismatch: {episode['episode']}") + episode.update(execution_start=annotation["execution_start"], writer_episode_id=annotation["episode_id"]) + spec["prompts"][task] = writer["task_instruction"] + output.parent.mkdir(parents=True, exist_ok=True) + states, actions, counts, episode_counts = {}, {}, {}, Counter() + with tempfile.TemporaryDirectory(prefix=f".{output.name}-", dir=output.parent) as temporary: + build = Path(temporary) + (build / "features").symlink_to((dataset / "features").resolve(), target_is_directory=True) + for split in ("train", "validation", "test"): + (build / split / "data").mkdir(parents=True) + (build / split / "meta").mkdir() + (build / split / "features").symlink_to("../features", target_is_directory=True) + count = 0 + paths = sorted((dataset / split / "data").glob("*.pkl"), key=lambda p: int(p.stem)) + for path in paths: + with path.open("rb") as stream: + row = pickle.load(stream) + episode_id, frame = int(row["epis_idx"]), int(row["step_idx"]) + episode = episodes[episode_id] + if frame < episode["execution_start"]: + continue + validate_actions(row["actions"], row["action_component_valid_mask"]) + row.update(exec_start_idx=np.asarray(episode["execution_start"]), is_demo=np.asarray(False), + global_episode_id=np.asarray(episode_id), task_id=f"franka_{task}", + source_index=np.asarray(source_offsets[episode_id] + frame), prompt=spec["prompts"][task]) + with (build / split / "data" / f"{count}.pkl").open("xb") as stream: + pickle.dump(row, stream, protocol=pickle.HIGHEST_PROTOCOL) + count += 1 + episode_counts[episode_id] += 1 + if split == "train": + states[episode_id, frame] = row["state"] + for offset, action in enumerate(row["actions"]): + key = episode_id, frame + offset + if key in actions and not np.array_equal(actions[key], action, equal_nan=True): + raise ValueError(f"Overlapping action windows disagree: {key}") + actions[key] = action + counts[split] = count + (build / split / "meta/stats.json").write_text(json.dumps({"total_samples": count, "execution_samples": count})) + norms, valid_counts = {}, {} + for field, rows in (("state", states), ("actions", actions)): + matrix = np.stack(list(rows.values())) + columns = [v[np.isfinite(v)] for v in matrix.T] + if any(not len(v) for v in columns[:7]) or field == "state" and not len(columns[7]): + raise ValueError(f"Missing required normalization evidence: {field}") + norms[field] = normalize.NormStats( + mean=np.array([v.mean() if len(v) else 0 for v in columns]), + std=np.array([v.std() if len(v) else 1 for v in columns]), + q01=np.array([np.quantile(v, .01) if len(v) else 0 for v in columns]), + q99=np.array([np.quantile(v, .99) if len(v) else 0 for v in columns]), + ) + valid_counts[field] = [len(v) for v in columns] + normalize.save(build / "assets/franka", norms) + for episode in spec["episodes"]: + episode["samples"] = episode_counts[episode["episode_id"]] + spec.update(counts=counts, normalization_valid_counts=valid_counts, + normalization="train-only known-component STD; unique frames used in execution training windows", + action_supervision="execution frames only; demonstration frames retained as visual history", + frame_coordinates="original episode/frame IDs, never shifted at execution start", + representation="absolute recorded end-effector xyz, unit xyzw with qx positive, commanded gripper open in [0,1]", + previous_dataset=str(dataset.resolve()), annotation_source=str(annotations.resolve()), + unsupervised_action_components=[i for i, count in enumerate(valid_counts["actions"]) if not count]) + (build / "dataset.json").write_text(json.dumps(spec, indent=2)) + build.rename(output) + return {"task": task, "counts": counts, "output": str(output), "history_start_frame": 0} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + for name in ("dataset", "annotations", "output"): + parser.add_argument("--" + name, type=Path, required=True) + print(json.dumps(prepare(**vars(parser.parse_args()))), flush=True) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_history.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_history.py new file mode 100644 index 0000000000000000000000000000000000000000..cb2c2db4ad0ba74608a5b2d833a25f09c1fce6d6 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_history.py @@ -0,0 +1,258 @@ +"""Cache frozen base-camera features for the existing Uniform16 FrameSamp loader.""" + +from __future__ import annotations + +import argparse +import json +import multiprocessing +import os +import pickle +import shutil +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import cv2 +import h5py +import numpy as np + +from integrations.robomme.franka_baseline import BASE, POSE, canonical_pose, decode_image + + +def decode_episode(path): + cv2.setNumThreads(1) + with h5py.File(path, "r") as source: + keys = sorted(source) + images = np.empty((len(keys), 224, 224, 3), dtype=np.uint8) + states = np.zeros((len(keys), 8), dtype=np.float32) + state_valid = np.zeros(len(keys), dtype=bool) + for i, key in enumerate(keys): + frame = source[key] + images[i] = decode_image(frame[BASE]) + required = [POSE + "_position", POSE + "_orientation", "_franka_gripper_joint_states/position"] + if all(name in frame for name in required): + states[i, :7] = canonical_pose(np.r_[frame[required[0]][:], frame[required[1]][:]]) + states[i, 7] = frame[required[2]][:].sum() / 0.08 + state_valid[i] = True + # The recipe uses visual/position history only. Missing historical state + # remains a finite placeholder and is recorded, never used by the encoder. + return images, states, state_valid + + +def frozen_encoder(): + import flax.nnx as nnx + import flax.nnx.bridge as bridge + import jax + import jax.numpy as jnp + from openpi.models import model, siglip + + params = model.restore_params( + "/data/robomme/models/openpi/openpi-assets/checkpoints/pi05_base/params", + restore_type=np.ndarray, + )["PaliGemma"]["img"] + encoder = bridge.ToNNX( + siglip.Module( + num_classes=2048, + variant="So400m/14", + pool_type="none", + scan=True, + dtype_mm="bfloat16", + ) + ) + encoder.lazy_init(jnp.zeros((1, 224, 224, 3)), train=False, rngs=nnx.Rngs(0)) + graph, state = nnx.split(encoder) + # Match init_train_state's frozen-parameter dtype and checkpoint exactly. + state.replace_by_pure_dict(jax.tree.map(lambda x: jnp.asarray(x, dtype=jnp.bfloat16), params)) + return nnx.merge(graph, state) + + +def prepare(dataset, output, workers=8, batch_size=32): + import flax.nnx as nnx + import jax + import jax.numpy as jnp + from mme_vla_suite.shared.data_utils import pool_tokens_to_size + from mme_vla_suite.shared.posemb_3d import PosEmb3D + + dataset, output = Path(dataset).resolve(), Path(output).resolve() + spec = json.loads((dataset / "dataset.json").read_text()) + paths = sorted(Path(spec["source"]).glob("*/*.h5")) + output.mkdir(parents=True, exist_ok=False) + features = output / "features" + features.mkdir() + encoder = frozen_encoder() + position_encoder = PosEmb3D(768) + + @nnx.jit + def encode(module, images): + tokens, _ = module(images, train=False) + return pool_tokens_to_size(tokens, 16) + + summaries = [] + with ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn")) as pool: + for episode_id, (path, decoded) in enumerate(zip(paths, pool.map(decode_episode, paths), strict=True)): + images, states, state_valid = decoded + destination = features / f"episode_{episode_id}" + destination.mkdir() + positions = np.asarray(position_encoder(jnp.arange(len(images)), 4), dtype=np.float32) + for start in range(0, len(images), batch_size): + batch = images[start : start + batch_size] + length = len(batch) + # A fixed batch shape avoids recompiling for every episode tail. + if length < batch_size: + batch = np.pad(batch, ((0, batch_size - length), (0, 0), (0, 0), (0, 0))) + embeddings = np.asarray( + encode(encoder, jnp.asarray(batch, dtype=jnp.float32) / 127.5 - 1), dtype=np.float32 + ) + for offset in range(length): + i = start + offset + np.save( + destination / f"token_emb_{i}.npy", + { + "image_emb_4x4": embeddings[offset : offset + 1], + "pos_emb_4x4": positions[i : i + 1], + "state_emb": states[i], + }, + ) + summary = { + "episode": path.stem, + "episode_id": episode_id, + "frames": len(images), + "missing_unused_state_frames": int((~state_valid).sum()), + } + summaries.append(summary) + print(json.dumps(summary), flush=True) + del encoder + jax.clear_caches() + + for split in ["train", "validation"]: + destination = output / split + (destination / "data").mkdir(parents=True) + shutil.copytree(dataset / split / "meta", destination / "meta") + (destination / "features").symlink_to("../features", target_is_directory=True) + count = json.loads((destination / "meta" / "stats.json").read_text())["total_samples"] + for i in range(count): + with (dataset / split / "data" / f"{i}.pkl").open("rb") as handle: + row = pickle.load(handle) + # FrameSamp samples the whole observed prefix and does not use this + # recurrent/Status compatibility field to select its history. + row["exec_start_idx"] = np.asarray(0) + with (destination / "data" / f"{i}.pkl").open("xb") as handle: + pickle.dump(row, handle, protocol=pickle.HIGHEST_PROTOCOL) + shutil.copytree(dataset / "assets", output / "assets") + spec["baseline_dataset"] = str(dataset) + spec["history"] = { + "frames": 16, + "sampling": "even_sampling_indices(t,16), inclusive [0,t]", + "camera": "base", + "tokens_per_frame": 16, + "tokens": 256, + "use_historical_state": False, + "position": "absolute source-frame index and 4x4 spatial position", + "vision_checkpoint": "/data/robomme/models/openpi/openpi-assets/checkpoints/pi05_base/params", + "vision_dtype": "bfloat16", + "cache_dtype": "float32", + } + (output / "dataset.json").write_text(json.dumps(spec, indent=2)) + (output / "feature-summary.json").write_text(json.dumps(summaries, indent=2)) + print(f"Completed: {len(summaries)} episodes, {sum(row['frames'] for row in summaries)} frame features", flush=True) + + +def select_task(dataset, output, task): + """Reuse source rows and cached features; fit normalization on one task's train split.""" + from openpi.shared import normalize + + dataset, output = Path(dataset).resolve(), Path(output).resolve() + spec = json.loads((dataset / "dataset.json").read_text()) + selected = [episode for episode in spec["episodes"] if episode["task"] == task] + if not selected: + raise ValueError(f"No episodes for task {task}") + output.mkdir(parents=True, exist_ok=False) + (output / "features").symlink_to(dataset / "features", target_is_directory=True) + statistics = {key: normalize.RunningStats() for key in ["state", "actions"]} + counts = {"train": 0, "validation": 0} + offsets = dict(counts) + for split in counts: + (output / split / "data").mkdir(parents=True) + (output / split / "meta").mkdir() + (output / split / "features").symlink_to("../features", target_is_directory=True) + for episode in spec["episodes"]: + split, count = episode["split"], episode["samples"] + start = offsets[split] + offsets[split] += count + if episode["task"] != task: + continue + for index in range(start, start + count): + source = dataset / split / "data" / f"{index}.pkl" + os.link(source, output / split / "data" / f"{counts[split]}.pkl") + counts[split] += 1 + if split == "train": + with source.open("rb") as handle: + row = pickle.load(handle) + for key in statistics: + statistics[key].update(row[key][None]) + for split, count in counts.items(): + (output / split / "meta" / "stats.json").write_text(json.dumps({"total_samples": count})) + normalize.save(output / "assets" / "franka", {key: value.get_statistics() for key, value in statistics.items()}) + spec.update({"episodes": selected, "task": task, "parent_dataset": str(dataset), + "normalization_source": f"{task} training episodes only"}) + (output / "dataset.json").write_text(json.dumps(spec, indent=2)) + print(json.dumps({"task": task, "episodes": len(selected), "samples": counts}), flush=True) + + +def cache_task(source, output, task, batch_size=8): + """Cache every original frame for an additional task using the frozen encoder.""" + import flax.nnx as nnx + import jax.numpy as jnp + from mme_vla_suite.shared.data_utils import pool_tokens_to_size + from mme_vla_suite.shared.posemb_3d import PosEmb3D + + source, output = Path(source), Path(output) + paths = sorted(source.glob("*/*.h5")) + selected = [(i,p) for i,p in enumerate(paths) if p.parent.name == task] + if not selected: + raise ValueError(f"No converted episodes for {task}") + output.mkdir(parents=True, exist_ok=True) + encoder = frozen_encoder() + position_encoder = PosEmb3D(768) + + @nnx.jit + def encode(module, images): + tokens, _ = module(images, train=False) + return pool_tokens_to_size(tokens, 16) + + records = [] + for episode_id, path in selected: + images, states, state_valid = decode_episode(path) + destination = output / f"episode_{episode_id}" + destination.mkdir(exist_ok=True) + positions = np.asarray(position_encoder(jnp.arange(len(images)), 4), dtype=np.float32) + for start in range(0, len(images), batch_size): + batch = images[start:start + batch_size] + length = len(batch) + batch = np.pad(batch, ((0,batch_size-length),(0,0),(0,0),(0,0))) + embeddings = np.asarray(encode(encoder, jnp.asarray(batch, dtype=jnp.float32) / 127.5 - 1), dtype=np.float32) + for offset in range(length): + i = start + offset + np.save(destination / f"token_emb_{i}.npy", { + "image_emb_4x4": embeddings[offset:offset + 1], + "pos_emb_4x4": positions[i:i + 1], "state_emb": states[i], + }) + record = {"episode":path.stem,"episode_id":episode_id,"frames":len(images), + "missing_unused_state_frames":int((~state_valid).sum())} + records.append(record) + print(json.dumps(record),flush=True) + (output / "feature-summary.json").write_text(json.dumps(records,indent=2)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dataset", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument("--batch-size", type=int, default=32) + parser.add_argument("--task", help="Select one task from an already cached dataset instead of encoding features") + args = vars(parser.parse_args()) + task = args.pop("task") + if task: + select_task(args["dataset"], args["output"], task) + else: + prepare(**args) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_matrix.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c4590b893d224a772722bd18808fe4d512dc65 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_matrix.py @@ -0,0 +1,114 @@ +"""Run the remaining real-robot tasks and archive every complete checkpoint.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import subprocess +import sys +import time + +from integrations.robomme.franka_baseline import FORMAL_BUDGET, model_repo_id + + +def checkpoint_jobs(matrix): + for task in matrix["tasks"]: + slug = task["task"].replace("_", "-") + for variant in ("baseline", "uniform32"): + config = "pi05_franka_baseline" if variant == "baseline" else "pi05_franka_uniform32_baseline" + for step in (5000, FORMAL_BUDGET["steps"]): + yield { + "task": task["task"], "variant": variant, "step": step, + "checkpoint": str(Path(task["run_root"]) / variant / "checkpoints" / config / slug / str(step)), + "repo_id": model_repo_id(task["task"], 32 if variant == "uniform32" else 0, step), + } + + +def archive(matrix_path): + from huggingface_hub import HfApi + + matrix_path = Path(matrix_path) + tasks = json.loads(matrix_path.read_text()) + jobs = list(checkpoint_jobs(tasks)) + receipts = matrix_path.parent / "checkpoint-uploads" + receipts.mkdir(exist_ok=True) + api = HfApi() + while jobs: + for job in jobs[:]: + source = Path(job["checkpoint"]) + receipt = receipts / f"{job['task']}-{job['variant']}-{job['step']}.json" + if receipt.exists(): + jobs.remove(job) + continue + if not (source / "_CHECKPOINT_METADATA").exists(): + continue + if not (source / "resume_state").is_dir(): + raise ValueError(f"Complete training state is missing: {source}") + print(f"Uploading complete checkpoint {job['task']}/{job['variant']}/{job['step']}", flush=True) + api.create_repo(job["repo_id"], repo_type="model", private=False, exist_ok=True) + commit = api.upload_folder( + repo_id=job["repo_id"], repo_type="model", folder_path=source, + commit_message=f"Archive complete {job['step']}-step checkpoint including optimizer and sampler", + ) + remote = {f.path: f.size for f in api.list_repo_tree(job["repo_id"], recursive=True) + if hasattr(f, "size")} + files = [p for p in source.rglob("*") if p.is_file()] + for path in files: + name = path.relative_to(source).as_posix() + if remote.get(name) != path.stat().st_size: + raise RuntimeError(f"Remote checkpoint file missing or wrong size: {job['repo_id']}/{name}") + receipt.write_text(json.dumps({ + **job, "commit": commit.oid, "complete_checkpoint_verified": True, + "files": len(files), "bytes": sum(p.stat().st_size for p in files), + }, indent=2)) + jobs.remove(job) + print(f"Verified complete checkpoint: {job['repo_id']}", flush=True) + if jobs: + time.sleep(10) + print("All formal checkpoints uploaded with full resume state", flush=True) + + +def train_remaining(matrix_path, wait_pid): + import psutil + + matrix_path = Path(matrix_path) + matrix = json.loads(matrix_path.read_text()) + if wait_pid: + print(f"Waiting for current button_order controller PID {wait_pid}", flush=True) + try: + psutil.Process(wait_pid).wait() + except psutil.NoSuchProcess: + pass + button = next(t for t in matrix["tasks"] if t["task"] == "button_order") + button_root = Path(button["run_root"]) + final = button_root / "uniform32/checkpoints/pi05_franka_uniform32_baseline/button-order" / str(FORMAL_BUDGET["steps"]) + evaluation = button_root / "uniform32-evaluation.json" + if not (final / "_CHECKPOINT_METADATA").exists() or not evaluation.exists(): + raise RuntimeError("button_order training/evaluation must finish before the remaining tasks start") + if not json.loads(evaluation.read_text())["all_outputs_finite"]: + raise RuntimeError("button_order final evaluation failed") + for task in matrix["tasks"]: + if task["task"] == "button_order": + continue + dataset = Path(task["dataset"]) + if not (dataset / "dataset.json").exists(): + raise RuntimeError(f"Prepared dataset is not ready: {dataset}") + print(f"Starting both settings for {task['task']}", flush=True) + with (matrix_path.parent / f"{task['task']}-controller.log").open("a") as log: + subprocess.run([ + sys.executable, "-m", "integrations.robomme.franka_release", "run", + "--dataset", str(dataset), "--run-root", task["run_root"], + ], stdout=log, stderr=subprocess.STDOUT, check=True) + print("All task/settings finished training and evaluation; check upload receipts separately", flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=["archive", "train-remaining"]) + parser.add_argument("--matrix-path", type=Path, required=True) + parser.add_argument("--wait-pid", type=int, default=0) + args = parser.parse_args() + if args.command == "archive": + archive(args.matrix_path) + else: + train_remaining(args.matrix_path, args.wait_pid) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_partial.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_partial.py new file mode 100644 index 0000000000000000000000000000000000000000..f5145a275de4f1dc51aca313f93678d7f4619bb8 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_partial.py @@ -0,0 +1,226 @@ +"""Verified partial Cartesian supervision and the local four-GPU Franka recipe. + +Preparation reads converted HDF5 plus the saved Joy-edge/server evidence from +fm-dev/shulin_ws. It never reads ROS bags or infers commands from finger width. +""" +from __future__ import annotations + +import argparse +import dataclasses +import importlib.util +import json +import pickle +from pathlib import Path + +import h5py +import numpy as np + +from integrations.robomme.franka_baseline import BASE, WRIST, POSE, PROMPTS, canonical_pose, decode_image, window_starts + +PROMPT = PROMPTS["button_order"] + + +@dataclasses.dataclass(frozen=True) +class BoundedStateForTokenization: + stats: object + + def __call__(self, data): + low, high = np.asarray(self.stats.q01), np.asarray(self.stats.q99) + span = high - low + state = np.asarray(data["state"], dtype=np.float32) + bounded = 2 * (state - low) / np.where(span > 1e-6, span, 1) - 1 + return {**data, "state_for_tokenization": np.where( + span > 1e-6, np.clip(bounded, -1, 1), 0 + ).astype(np.float32)} + + +@dataclasses.dataclass(frozen=True) +class CartesianWeightLoader: + params_path: str + + def load(self, params): + from flax import traverse_util + from openpi.models import model + from openpi.training.weight_loaders import _merge_params + + loaded = model.restore_params(self.params_path, restore_type=np.ndarray) + # The base's padded joint-space heads do not represent Cartesian D8. + for key in ("action_in_proj", "action_out_proj", "state_proj"): + loaded.pop(key, None) + reference = traverse_util.flatten_dict(params, sep="/") + for key, value in traverse_util.flatten_dict(loaded, sep="/").items(): + if key in reference and value is not None and value.shape != reference[key].shape: + raise ValueError(f"Unexpected pretrained shape mismatch: {key}") + return _merge_params(loaded, params, missing_regex=".*") + + +def validate_actions(actions, mask): + if actions.shape != mask.shape or actions.shape[-1] != 8 or mask.dtype != bool: + raise ValueError("Partial action arrays require matching [H,8] targets and boolean masks") + if not np.isfinite(actions[mask]).all() or not np.isnan(actions[~mask]).all(): + raise ValueError("Known actions must be finite; unknown disk targets must be NaN") + if np.any(mask[..., 3:7] != mask[..., 3:4]): + raise ValueError("Quaternion validity must be all-or-none") + + +def read_h5_signals(path): + """Numeric signals from converted HDF5, with missing measurements left unknown.""" + with h5py.File(path, "r") as source: + keys = sorted(source) + stamps = np.array([source[k].attrs["timestamp"] for k in keys], dtype=np.int64) + state_pose = np.full((len(keys), 7), np.nan) + target_pose = np.full((len(keys), 7), np.nan) + width = np.full(len(keys), np.nan) + for i, key in enumerate(keys): + frame = source[key] + if POSE + "_position" in frame and POSE + "_orientation" in frame: + state_pose[i] = np.r_[frame[POSE + "_position"][:], frame[POSE + "_orientation"][:]] + if "_target_pose_position" in frame and "_target_pose_orientation" in frame: + target_pose[i] = np.r_[frame["_target_pose_position"][:], frame["_target_pose_orientation"][:]] + if "_franka_gripper_joint_states/position" in frame: + width[i] = frame["_franka_gripper_joint_states/position"][:].sum() / .08 + return stamps, state_pose, target_pose, width + + +def prepare(source, reference, split_manifest, output, features, task="button_order"): + from openpi.shared import normalize + + source, reference, output = Path(source), Path(reference), Path(output) + manifest = json.loads(Path(split_manifest).read_text()) + entries = manifest["episodes"] + available = {p.stem: p for p in (source / task).glob("*.h5")} + if {e["raw_episode_id"] for e in entries} != set(available): + raise ValueError(f"Split must cover exactly the converted {task} episodes") + # Reuse the user's reviewed event/clock logic, never its older bootstrap. + evidence_source = reference / "scripts/build_franka_baseline_dataset.py" + module_spec = importlib.util.spec_from_file_location("franka_evidence", evidence_source) + evidence = importlib.util.module_from_spec(module_spec) + module_spec.loader.exec_module(evidence) + commands, server_counts = evidence.parse_server_commands(reference / "evidence/remote_gripper_server_events.log") + output.mkdir(parents=True, exist_ok=False) + (output / "features").symlink_to(Path(features).resolve(), target_is_directory=True) + counts = {"train": 0, "validation": 0, "test": 0} + for split in counts: + (output / split / "data").mkdir(parents=True) + (output / split / "meta").mkdir() + (output / split / "features").symlink_to("../features", target_is_directory=True) + # Feature IDs follow the original sorted converted inventory, not split order. + all_files = sorted(source.glob("*/*.h5")) + records, state_rows, action_rows = [], [], [] + for entry in entries: + name, split = entry["raw_episode_id"], entry["split"] + path = available[name] + episode_id = all_files.index(path) + qc_path = reference / "data/qc_state" / f"{task}__{name}.npz" + if qc_path.exists(): + with np.load(qc_path) as qc: + stamps = qc["ts"].copy() + state_pose = np.c_[qc["ee_pos"], qc["ee_quat"]] + target_pose = np.c_[qc["tgt_pos"], qc["tgt_quat"]] + width = qc["grip_pos"].sum(axis=1) / 0.08 + else: + stamps, state_pose, target_pose, width = read_h5_signals(path) + n = len(stamps) + state = np.full((n, 8), np.nan, dtype=np.float32) + actions = np.full((n, 8), np.nan, dtype=np.float32) + state_finite = np.isfinite(state_pose).all(axis=1) & np.isfinite(width) + pose_finite = np.isfinite(target_pose).all(axis=1) + state[state_finite, :7] = canonical_pose(state_pose[state_finite]) + state[state_finite, 7] = width[state_finite] + actions[pose_finite, :7] = canonical_pose(target_pose[pose_finite]) + joy_path = reference / "evidence/joy_edges" / task / f"{name}.json" + verified = [] + if joy_path.exists(): + verified, _ = evidence.verified_commands(json.loads(joy_path.read_text()), commands) + actions[:, 7] = [np.nan if (v := evidence.command_at(int(t), verified)) is None else v for t in stamps] + mask = np.isfinite(actions) + # Keep the local 40 ms stream tolerance and 100 ms gap filter. Missing + # command evidence removes one component, not the known pose targets. + obs_valid = state_finite.copy() + target_synced = np.zeros(n, dtype=bool) + with h5py.File(path, "r") as h5: + keys = sorted(h5) + if len(keys) != n: + raise ValueError(f"QC/HDF5 frame count differs: {name}") + for i, key in enumerate(keys): + frame = h5[key] + if int(frame.attrs["timestamp"]) != int(stamps[i]): + raise ValueError(f"QC/HDF5 timestamp differs: {name}/{key}") + if POSE + "_position" in frame: + np.testing.assert_array_equal(frame[POSE + "_position"][:], state_pose[i, :3]) + sync = frame["sync_quality"].attrs + obs_valid[i] &= BASE in frame and WRIST in frame and all( + abs(sync.get(k, np.inf)) <= 40_000_000 + for k in (WRIST, POSE, "_franka_gripper_joint_states") + ) + target_synced[i] = abs(sync.get("_target_pose", np.inf)) <= 40_000_000 + starts = window_starts(stamps, pose_finite & target_synced, 20) + starts = starts[obs_valid[starts]] + if entry.get("exclude_reason"): + starts = starts[:0] + for i in starts: + frame = h5[keys[i]] + row = { + "image": decode_image(frame[BASE]), "wrist_image": decode_image(frame[WRIST]), + "state": state[i], "actions": actions[i:i + 20], + "action_component_valid_mask": mask[i:i + 20], "prompt": PROMPTS[task], + "epis_idx": np.asarray(episode_id), "step_idx": np.asarray(i), + "exec_start_idx": np.asarray(0), "timestamp_ns": stamps[i], + } + validate_actions(row["actions"], row["action_component_valid_mask"]) + with (output / split / "data" / f"{counts[split]}.pkl").open("xb") as stream: + pickle.dump(row, stream, protocol=pickle.HIGHEST_PROTOCOL) + counts[split] += 1 + if split == "train" and not entry.get("exclude_reason"): + state_rows.append(state[obs_valid]) + # Fit once per original known source frame, avoiding window overlap weighting. + action_rows.append(actions[pose_finite & target_synced]) + records.append({ + "episode": name, "episode_id": episode_id, "task": task, "split": split, + "frames": n, "samples": len(starts), "known_gripper_frames": int(mask[:, 7].sum()), + "verified_commands": len(verified), + "exclude_reason": entry.get("exclude_reason"), + }) + print(json.dumps(records[-1]), flush=True) + stats, valid_counts = {}, {} + for key, arrays in (("state", state_rows), ("actions", action_rows)): + values = np.concatenate(arrays).astype(np.float64) + known = [v[np.isfinite(v)] for v in values.T] + valid_counts[key] = [len(v) for v in known] + if any(len(v) == 0 for v in known[:7]) or (key == "state" and not len(known[7])): + raise ValueError(f"No training evidence for one or more {key} components") + # A wholly unobserved action-gripper dimension uses the physical unit + # coordinate (identity normalization), not invented fitted statistics. + # Its labels stay NaN/false and its output is explicitly unsupervised. + stats[key] = normalize.NormStats( + mean=np.array([v.mean() if len(v) else 0 for v in known]), + std=np.array([v.std() if len(v) else 1 for v in known]), + q01=np.array([np.quantile(v, .01) if len(v) else 0 for v in known]), + q99=np.array([np.quantile(v, .99) if len(v) else 1 for v in known]), + ) + normalize.save(output / "assets/franka", stats) + for split, count in counts.items(): + (output / split / "meta/stats.json").write_text(json.dumps({"total_samples": count})) + spec = { + "source": str(source), "task": task, "action_horizon": 20, + "prompts": {task: PROMPTS[task]}, + "partial_action_supervision": True, "normalization": "train-only known-component STD", + "representation": "absolute flange xyz, unit xyzw with qx positive, commanded gripper open in [0,1]", + "gripper": "full-rate Joy edges matched to saved server requests; unknown=NaN/mask false; no bootstrap", + "split_manifest": str(split_manifest), "command_evidence_source": str(evidence_source), + "sync_tolerance_ms": 40, "max_window_gap_ms": 100, + "current_state_tokens": "train q01/q99 bounded [-1,1], constant spans map to zero", + "server_evidence_counts": server_counts, "episodes": records, "counts": counts, + "normalization_valid_counts": valid_counts, + "unsupervised_action_components": [i for i,n in enumerate(valid_counts["actions"]) if n == 0], + } + (output / "dataset.json").write_text(json.dumps(spec, indent=2)) + print(json.dumps(counts), flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + for name in ("source", "reference", "split-manifest", "output", "features"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--task", choices=list(PROMPTS), default="button_order") + prepare(**vars(parser.parse_args())) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_release.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_release.py new file mode 100644 index 0000000000000000000000000000000000000000..5c1cfd85dc6b47cc2f9184880406e81554b0929c --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_release.py @@ -0,0 +1,420 @@ +"""Evaluate final Franka policies and publish portable model bundles to fm-dev.""" +from __future__ import annotations + +import argparse +import importlib.metadata +import json +import os +from pathlib import Path +import pickle +import shutil +import subprocess +import sys +import time + +import numpy as np + +from integrations.robomme.franka_baseline import FORMAL_BUDGET, load_policy, model_repo_id + + +def training_settings(metadata, spec, checkpoint_step): + recipe = metadata["training_recipe"] + history = metadata.get("history", {}) + return { + "model": "pi0.5", "task": spec["task"], "fine_tuning": "LoRA", + "setting": f"uniform{history['frames']}" if history else "baseline", + "checkpoint_step": checkpoint_step, "target_steps": metadata["target_steps"], + "global_batch_size": recipe["global_batch_size"], + "per_gpu_batch_size": recipe["global_batch_size"] // recipe["gpus"], + "num_gpus": recipe["gpus"], "gpu_model": "NVIDIA RTX A6000", + "gradient_accumulation_steps": recipe["gradient_accumulation"], + "parallelism": "JAX data parallel", "fsdp_devices": recipe["fsdp_devices"], + "samples_seen": checkpoint_step * recipe["global_batch_size"], + "reference_budget": {"batch_size": recipe["reference_global_batch"], "steps": recipe["reference_steps"]}, + "optimizer": {"name": "AdamW", "beta1": .9, "beta2": .95, "epsilon": 1e-8, + "weight_decay": 1e-10, "clip_gradient_norm": 1.0}, + "lr_schedule": {"name": "cosine", "warmup_steps": recipe["warmup_steps"], + "peak_lr": recipe["peak_lr"], "decay_steps": recipe["decay_steps"], + "final_lr": recipe["decay_lr"]}, + "ema_decay": recipe["ema_decay"], "seed": 42, "data_loader_workers": 4, + "lora_backbones": ["gemma_2b_lora", "gemma_300m_lora"], "lora_rank": 32, + "trainable": recipe["method"], + "compute_dtype": "bfloat16", "trainable_parameter_dtype": "float32", + "action_dim": recipe["action_dim"], "action_horizon": recipe["action_horizon"], + "state_tokens": {"enabled": True, "max_token_len": recipe["max_token_len"], + "normalization": "bounded train q01/q99; constant spans map to0"}, + "history": {**history, "history_tokens": history.get("frames", 0) * history.get("tokens_per_frame", 0)}, + "normalization": "train-only known-component STD", "dataset_sample_counts": spec["counts"], + "checkpoint_save_steps": [5000, metadata["target_steps"]], + "full_resume_state_included": True, + "unsupervised_action_components": spec.get("unsupervised_action_components", []), + "gpu_allocator": metadata.get("gpu_allocator", "default"), + } + + +def evaluate(dataset, checkpoint, output, per_episode=25): + from picmem.data.semantic_transition.sampling import even_sampling_indices + + dataset, checkpoint = Path(dataset), Path(checkpoint) + spec = json.loads((dataset / "dataset.json").read_text()) + policy = load_policy(checkpoint) + history = (checkpoint / "assets/history_config.yaml").exists() + offsets = {"validation": 0, "test": 0} + collected = {split: {"position_l2_m": [], "quaternion_angle_rad": [], "gripper_mae": []} for split in offsets} + records = [] + for episode in spec["episodes"]: + split = episode["split"] + if split not in offsets: + continue + count = episode["samples"] + indices = np.unique(np.linspace(0, count - 1, min(count, per_episode), dtype=int)) if count else [] + for local_index in indices: + with (dataset / split / "data" / f"{offsets[split] + local_index}.pkl").open("rb") as stream: + sample = pickle.load(stream) + if history: + # Offline samples provide their own complete frame features and + # sample key. Keep the encoder/position tables, clear only history. + policy.mem_buffer._history_feats.clear() + step, episode_id = int(sample["step_idx"]), int(sample["epis_idx"]) + for index in even_sampling_indices(step, policy._metadata["history"]["frames"]): + feature = dataset / "features" / f"episode_{episode_id}" / f"token_emb_{index}.npy" + policy.mem_buffer._history_feats[index] = np.load(feature, allow_pickle=True).item() + policy.step_idx = step + obs = {key: sample[key] for key in ("image", "wrist_image", "state", "prompt")} + obs["sample_key"] = [split, episode["episode"], int(sample["step_idx"]), 42] + pred = policy.infer(obs)["actions"] + if pred.shape != (20, 8) or not np.isfinite(pred).all(): + raise ValueError("Invalid restored policy output") + target, mask = sample["actions"], sample["action_component_valid_mask"] + position_mask, quat_mask = mask[:, :3].all(-1), mask[:, 3:7].all(-1) + position = np.linalg.norm(pred[position_mask, :3] - target[position_mask, :3], axis=-1) + dot = np.sum(pred[quat_mask, 3:7] * target[quat_mask, 3:7], axis=-1) + angle = 2 * np.arccos(np.clip(np.abs(dot), 0, 1)) + gripper = np.abs(pred[mask[:, 7], 7] - target[mask[:, 7], 7]) + for name, values in zip(collected[split], (position, angle, gripper), strict=True): + collected[split][name].extend(values.tolist()) + records.append({"split": split, "episode": episode["episode"], "frame": int(sample["step_idx"])}) + offsets[split] += count + print(f"Evaluated {split}/{episode['episode']}: {len(indices)} observations", flush=True) + report = { + "checkpoint": str(checkpoint.resolve()), "optimizer_step": int(checkpoint.name), + "all_outputs_finite": True, "action_shape": [20, 8], "per_episode": per_episode, + "scope": "Held-out offline H20 action error; no physical robot rollout or success-rate claim", + "splits": {split: {name: {"count": len(v), "mean": float(np.mean(v)) if v else None} + for name, v in metrics.items()} for split, metrics in collected.items()}, + "observations": records, + } + Path(output).write_text(json.dumps(report, indent=2, allow_nan=False)) + print(json.dumps(report["splits"]), flush=True) + + +def publish(dataset, checkpoint, evaluation, output, repo_id, intermediate=False): + from huggingface_hub import HfApi + + dataset, checkpoint, output = Path(dataset), Path(checkpoint), Path(output) + metadata = json.loads((checkpoint / "assets/policy_metadata.json").read_text()) + report = json.loads(Path(evaluation).read_text()) if evaluation is not None else None + target_steps = FORMAL_BUDGET["steps"] + checkpoint_step = int(checkpoint.name) + if intermediate: + if (checkpoint_step != 5000 or metadata["target_steps"] != target_steps + or not (checkpoint / "_CHECKPOINT_METADATA").exists()): + raise ValueError("Intermediate upload requires the completed 5,000-step checkpoint") + elif (checkpoint_step != target_steps or metadata["target_steps"] != target_steps + or report is None or report["optimizer_step"] != target_steps or not report["all_outputs_finite"] + or Path(report["checkpoint"]).resolve() != checkpoint.resolve()): + raise ValueError(f"Only the evaluated {target_steps}-update model can be published") + if not repo_id.startswith("fm-dev/"): + raise ValueError("This task publishes only to the authorized fm-dev namespace") + # Controllers started before the user's rename request still pass legacy IDs. + # Resolve those IDs before any Hub write, preserving running trainers. + history_frames = metadata.get("history", {}).get("frames", 0) + task_slug = metadata["task"].replace("_", "-") + legacy = f"fm-dev/pi05-{task_slug}-{'uniform32-' if history_frames else ''}lora{'-5000' if intermediate else ''}" + destination = model_repo_id(metadata["task"], history_frames, checkpoint_step) + if repo_id not in {legacy, destination}: + raise ValueError(f"Model name must identify this task, setting and checkpoint: {destination}") + repo_id = destination + output.mkdir(parents=True, exist_ok=True) + shutil.copyfile(dataset / "dataset.json", output / "dataset_manifest.json") + # Publish serving weights and the complete optimizer/RNG/sampler resume state. + for directory in ("params", "assets", "resume_state"): + if not (output / directory).exists(): + shutil.copytree(checkpoint / directory, output / directory, copy_function=os.link) + shutil.copyfile(checkpoint / "_CHECKPOINT_METADATA", output / "_CHECKPOINT_METADATA") + if evaluation is not None: + shutil.copyfile(evaluation, output / "evaluation.json") + (output / "checkpoint_info.json").write_text(json.dumps({ + "optimizer_step": checkpoint_step, "target_steps": target_steps, + "sample_exposures": checkpoint_step * 4, + "evaluation_status": "pending" if intermediate else "completed", + "resume_state_included": True, + }, indent=2)) + root = Path(__file__).resolve().parents[2] + for directory in ("integrations", "src", "robomme/src", "robomme/packages/openpi-client/src"): + for source in (root / directory).rglob("*"): + if source.is_file() and source.suffix in {".py", ".yaml", ".yml", ".json"}: + dest = output / "code" / source.relative_to(root) + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, dest) + for directory in ("", "robomme"): + for name in ("LICENSE", "pyproject.toml"): + source = root / directory / name + if source.exists(): + dest = output / "code" / directory / name + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, dest) + requirements = [] + for dist in importlib.metadata.distributions(): + name = dist.metadata["Name"] + if name.lower().replace("_", "-") in {"picmem-dev", "openpi", "openpi-client", "flash-attn-jax"}: + continue + requirements.append(f"{name}=={dist.version}") + (output / "requirements.txt").write_text( + "--extra-index-url https://download.pytorch.org/whl/cu126\n" + "\n".join(sorted(set(requirements))) + "\n" + ) + (output / "load_model.py").write_text( + 'from pathlib import Path\nimport sys\n' + 'ROOT = Path(__file__).resolve().parent\n' + 'for path in ("code", "code/src", "code/robomme/src", "code/robomme/packages/openpi-client/src"):\n' + ' sys.path.insert(0, str(ROOT / path))\n' + 'from integrations.robomme.franka_baseline import load_policy, observe\n' + 'def load():\n return load_policy(ROOT)\n' + ) + spec = json.loads((dataset / "dataset.json").read_text()) + uniform = "history" in metadata + (output / "training_config.json").write_text(json.dumps(training_settings(metadata, spec, checkpoint_step), indent=2)) + frames = metadata.get("history", {}).get("frames", 0) + task = spec["task"] + instruction = metadata.get("prompt") or spec["prompts"][task] + split_episodes = {s: sum(e["split"] == s for e in spec["episodes"]) for s in ("train", "validation", "test")} + gripper_evidence = {s: sum(e["known_gripper_frames"] for e in spec["episodes"] if e["split"] == s) + for s in split_episodes} + (output / "README.md").write_text(f'''--- +base_model: physical-intelligence/pi05_base +tags: [robotics, pi05, franka, lora] +--- + +# {repo_id.split('/')[-1]} + +Trained locally for **{checkpoint_step:,} optimizer updates** on four NVIDIA RTX A6000s. +Global batch4 ×{checkpoint_step:,}updates ={checkpoint_step * 4:,} training examples. +The complete run targets6,250updates =25,000examples, matching the sample +budget of the reference single-GPU batch1 ×25,000-update experiment. +{'This 5k checkpoint is uploaded immediately at the user request while training continues. Held-out evaluation of this intermediate checkpoint is pending.' if intermediate else 'This final checkpoint has completed the held-out offline evaluation below.'} +This repository contains full EMA serving weights, normalization and history +assets, inference source and exact installed dependency versions. +{'An offline evaluation report is included.' if not intermediate else 'No policy-quality evaluation is claimed for this intermediate upload.'} +The complete optimizer, non-EMA parameters, RNG and sampler cursor are included +under `resume_state/`; `params/` contains EMA serving weights. This is a +Cartesian8 LoRA adaptation of π0.5. + +Input: base and wrist RGB images, current flange xyz + unit XYZW quaternion +(positive qx chart), measured finger opening divided by0.08, and task text. +Output:20 absolute target flange poses and gripper commands (0closed,1open). +Numeric state/actions use train-only STD normalization. Current-state tokens +use a separate train-q01/q99 bounded view, max128tokens. Task prompt: +`{instruction}` + +History: {f'{frames} uniformly spaced frames over the entire inclusive observed prefix [0,t], base camera only,16 pooled spatial tokens/frame, modulation; short prefixes use masked padding.' if uniform else 'Current observations only.'} +No Writer, Status head, subgoal, or semantic-memory inputs are used. + +Training: LoRA Gemma2B and300M; fresh Cartesian projections and optional history +modules trainable; pretrained backbones and time MLPs frozen. AdamW, global +batch4 (one/GPU), no accumulation,250-step warmup, cosine5e-5→5e-6 through +step6,250. EMA0.999^4 =0.996005996001 preserves the reference per-sample +smoothing timescale. Checkpoints saved at5,000 and6,250updates. +Episode splits:{split_episodes}; accepted train/validation/test windows:{spec['counts']}. +The original40ms synchronization and100ms maximum-gap filters are retained. + +Gripper command labels require saved full-rate Joy edges matched to server +requests and clock bounds. Unknown targets are NaN/false on disk and masked +in both flow conditioning and loss. Measured width is state only. Source-frame +gripper evidence counts by split:{gripper_evidence}. Entirely unsupervised +action components:{spec.get('unsupervised_action_components', [])}. +{'Button Order has only closed training gripper targets; this does not establish a learned open/close policy.' if task == 'button_order' else ''} +{'Shuffle gripper commands have no verified evidence and are not supervised. Its gripper output must not be interpreted as a learned command.' if not gripper_evidence['train'] else ''} +Metrics with no known labels are null, not zero. +Evaluation reports known-component offline errors, not robot success rates. + +## Load + +Use Python3.10 and a CUDA12 GPU environment. Download this repository, then: + +```bash +python -m pip install -r requirements.txt +``` + +```python +from load_model import load, observe +policy = load() +# Arrays: RGB uint8 images, float32 state[8]. Resized to224 with aspect padding. +observe(policy, base_rgb, state) # Append every observed frame for the history model. +result = policy.infer({{ + "image": base_rgb, "wrist_image": wrist_rgb, "state": state, + "prompt": {instruction!r}, +}}) +actions = result["actions"] # (20,8) +``` + +For the history model, call `observe(policy, base_rgb, state)` for every original +observation frame, including the current one, and `policy.reset()` between +episodes. It uses the checkpoint's frozen vision encoder and appends frame +indices in order; the policy samples{frames} across the full prefix. `observe` is a +no-op for the model without history. The offline evaluator in +`code/integrations/robomme/franka_release.py` demonstrates this with cached +features. This bundle does not include demonstration images or private raw +workspace evidence. Robot control must use the same Cartesian frame and tool +convention as the training data. +''') + # Exercise the packaged source and online history path before publishing. + # A separate process avoids retaining GPU allocations in the upload worker. + if not intermediate: + check_packaged_inference(output) + api = HfApi() + api.create_repo(repo_id, repo_type="model", private=False, exist_ok=True) + commit = api.upload_folder(repo_id=repo_id, repo_type="model", folder_path=output, + commit_message=f"Upload {'intermediate' if intermediate else 'evaluated'} {checkpoint_step}-step Franka pi05 model") + remote = {f.path: f.size for f in api.list_repo_tree(repo_id, repo_type="model", recursive=True) + if hasattr(f, "size")} + for local in output.rglob("*"): + if local.is_file() and ".cache" not in local.relative_to(output).parts: + name = local.relative_to(output).as_posix() + if remote.get(name) != local.stat().st_size: + raise RuntimeError(f"Remote model file missing or wrong size: {name}") + receipt = {"repo_id": repo_id, "optimizer_step": checkpoint_step, "commit": commit.oid, + "verified_files": len(remote)} + print(json.dumps(receipt), flush=True) + return receipt + + +def check_packaged_inference(output): + smoke = subprocess.run( + [sys.executable, "-c", ''' +import json +import numpy as np +from load_model import load, observe +policy = load() +image = np.zeros((224, 224, 3), dtype=np.uint8) +state = np.array([.45, 0, .15, .7, -.7, 0, 0, 0], dtype=np.float32) +observe(policy, image, state) +actions = policy.infer({"image": image, "wrist_image": image, "state": state, + "prompt": policy._metadata["prompt"]})["actions"] +assert actions.shape == (20, 8) and np.isfinite(actions).all() +print(json.dumps({"packaged_inference": "passed", "shape": list(actions.shape)})) +'''], cwd=output, capture_output=True, text=True, check=True, + env={**os.environ, "PYTHONPATH": str(output), "JAX_PLATFORMS": "cuda", "CUDA_VISIBLE_DEVICES": "0"}, + ) + (output / "packaged-inference-check.txt").write_text(smoke.stdout.splitlines()[-1] + "\n") + + +def upload_5k(dataset, run_root): + """Upload each 5k model as soon as Orbax finishes saving, without using GPUs.""" + root = Path(run_root) + task = json.loads((Path(dataset) / "dataset.json").read_text())["task"] + slug = task.replace("_", "-") + for variant, name in (("baseline", "pi05_franka_baseline"), ("uniform32", "pi05_franka_uniform32_baseline")): + checkpoint = root / variant / "checkpoints" / name / slug / "5000" + receipt_path = root / f"{variant}-5000-upload.json" + if receipt_path.exists(): + continue + print(f"Waiting for committed checkpoint: {checkpoint}", flush=True) + while not (checkpoint / "_CHECKPOINT_METADATA").exists(): + time.sleep(5) + repo_id = model_repo_id(task, 32 if variant == "uniform32" else 0, 5000) + print(f"Uploading 5k checkpoint to {repo_id}", flush=True) + receipt = publish(dataset, checkpoint, None, root / f"{variant}-5000-export", repo_id, intermediate=True) + receipt_path.write_text(json.dumps(receipt, indent=2)) + + +def wait_for_baseline(pid, root): + """Attach a new controller to a baseline trainer that is already running.""" + import psutil + + root = Path(root).resolve() + final = root / "baseline/checkpoints/pi05_franka_baseline/button-order" / str(FORMAL_BUDGET["steps"]) + try: + process = psutil.Process(pid) + command = process.cmdline() + if ("integrations.robomme.franka_baseline" not in command + or str(root / "baseline") not in command): + raise ValueError("The existing process is not this run's baseline trainer") + print(f"Waiting for existing baseline trainer PID {pid}; next model is Uniform32", flush=True) + process.wait() + except psutil.NoSuchProcess: + pass + if not (final / "_CHECKPOINT_METADATA").exists(): + raise RuntimeError("Existing baseline trainer exited without its final complete checkpoint") + + +def run(dataset, run_root, wait_baseline_pid=0): + """Durable sequential train → evaluate → publish, each model uses all four GPUs.""" + root = Path(run_root) + root.mkdir(parents=True, exist_ok=True) + task = json.loads((Path(dataset) / "dataset.json").read_text())["task"] + slug = task.replace("_", "-") + if wait_baseline_pid: + wait_for_baseline(wait_baseline_pid, root) + for history, variant in ((False, "baseline"), (True, "uniform32")): + run = root / variant + name = "pi05_franka_uniform32_baseline" if history else "pi05_franka_baseline" + checkpoints = run / "checkpoints" / name / slug + final = checkpoints / str(FORMAL_BUDGET["steps"]) + command = [sys.executable, "-m", "integrations.robomme.franka_baseline", "train", + "--dataset", str(dataset), "--run-root", str(run), "--exp-name", slug] + if history: + command.extend(["--uniform-history", "--history-frames", "32"]) + if checkpoints.exists() and any(p.is_dir() and p.name.isdigit() for p in checkpoints.iterdir()): + command.append("--resume") + if not final.exists(): + with (root / f"{variant}-train.log").open("a") as log: + subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True) + report = root / f"{variant}-evaluation.json" + with (root / f"{variant}-evaluation.log").open("a") as log: + subprocess.run([sys.executable, "-m", "integrations.robomme.franka_release", "evaluate", + "--dataset", str(dataset), "--checkpoint", str(final), "--output", str(report)], + stdout=log, stderr=subprocess.STDOUT, check=True, + env={**os.environ, "CUDA_VISIBLE_DEVICES": "0"}) + repo_id = model_repo_id(task, 32 if history else 0, FORMAL_BUDGET["steps"]) + (root / f"{variant}-trained.json").write_text(json.dumps({ + "steps": FORMAL_BUDGET["steps"], "evaluation": str(report), "repo_id": repo_id, + })) + with (root / f"{variant}-upload.log").open("a") as log: + publication = subprocess.run([ + sys.executable, "-m", "integrations.robomme.franka_release", "publish", + "--dataset", str(dataset), "--checkpoint", str(final), "--evaluation", str(report), + "--output", str(root / f"{variant}-export"), "--repo-id", repo_id, + ], stdout=log, stderr=subprocess.STDOUT, check=False, + env={**os.environ, "JAX_PLATFORMS": "cpu"}) + if publication.returncode: + print(f"Upload pending for {repo_id}; training queue continues. See {variant}-upload.log", flush=True) + continue + (root / f"{variant}-complete.json").write_text(json.dumps({ + "steps": FORMAL_BUDGET["steps"], "sample_exposures": FORMAL_BUDGET["sample_exposures"], + "repo_id": repo_id, + })) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + evaluation = commands.add_parser("evaluate") + for name in ("dataset", "checkpoint", "output"): + evaluation.add_argument("--" + name, type=Path, required=True) + evaluation.add_argument("--per-episode", type=int, default=25) + publication = commands.add_parser("publish") + for name in ("dataset", "checkpoint", "output"): + publication.add_argument("--" + name, type=Path, required=True) + publication.add_argument("--evaluation", type=Path) + publication.add_argument("--repo-id", required=True) + publication.add_argument("--intermediate", action="store_true") + early = commands.add_parser("upload-5k") + early.add_argument("--dataset", type=Path, required=True) + early.add_argument("--run-root", type=Path, required=True) + runner = commands.add_parser("run") + runner.add_argument("--dataset", type=Path, required=True) + runner.add_argument("--run-root", type=Path, required=True) + runner.add_argument("--wait-baseline-pid", type=int, default=int(os.environ.get("FRANKA_WAIT_BASELINE_PID", "0"))) + args = vars(parser.parse_args()) + command = args.pop("command") + {"evaluate": evaluate, "publish": publish, "run": run, "upload-5k": upload_5k}[command](**args) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round.py new file mode 100644 index 0000000000000000000000000000000000000000..66019eaceea2ec29d8a3806a8e8a449e637d387d --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round.py @@ -0,0 +1,103 @@ +"""Settings and upload-aware local retention for the second Franka training round.""" +from __future__ import annotations + +import json +import dataclasses +from pathlib import Path +import shutil + +TARGET_STEPS = 12_500 +SAVE_INTERVAL = 1_000 +MILESTONE_STEPS = (5_000, 10_000, TARGET_STEPS) +BACKUP_REPO_ID = "fm-dev/pi05-checkpoint-backups" + + +def training_options(): + # Keep every periodic checkpoint until the uploader verifies its remote copy. + # make_train_config sets keep_period to save_interval; pruning happens below. + return {"steps": TARGET_STEPS, "save_interval": SAVE_INTERVAL, + "warmup_steps": 250, "decay_steps": TARGET_STEPS} + + +def checkpoint_steps(): + return [*range(SAVE_INTERVAL, TARGET_STEPS, SAVE_INTERVAL), TARGET_STEPS] + + +def model_repo_id(task, setting, step): + if setting not in {"status_d", "baseline", "uniform32"} or step not in checkpoint_steps(): + raise ValueError("Unknown second-round model setting or checkpoint step") + return f"fm-dev/pi05-{task.replace('_', '-')}-{setting.replace('_', '-')}-lora-gbs4-pgb1-gpu4-r2-step{step}" + + +def checkpoint_storage(task, setting, step): + """Keep milestones as models and other full checkpoints in archive folders.""" + model_id = model_repo_id(task, setting, step) + if step in MILESTONE_STEPS: + return model_id, "model", "" + return BACKUP_REPO_ID, "dataset", f"checkpoints/r2/{task}/{setting}/step{step}" + + +def make_config(dataset, run_root, setting, **overrides): + from integrations.robomme.franka_baseline import make_train_config + + if setting not in {"status_d", "baseline", "uniform32"}: + raise ValueError(f"Unsupported setting: {setting}") + dataset = Path(dataset).resolve() + spec = json.loads((dataset / "dataset.json").read_text()) + cfg = make_train_config(dataset, run_root, uniform_history=setting != "baseline", + history_frames=32, exp_name=spec["task"].replace("_", "-"), + **(training_options() | overrides)) + metadata = {**cfg.policy_metadata, "training_round": 2, "training_setting": setting, + "action_supervision": spec["action_supervision"], + "checkpoint_retention": {"save_interval": SAVE_INTERVAL, "local_latest": 3, + "milestones": [5000, 10000, TARGET_STEPS], "remote": "all"}, + "training_recipe": {**cfg.policy_metadata["training_recipe"], + "reference_steps": TARGET_STEPS * 4, + "reference_global_batch": 1}} + if setting == "status_d": + history = dataset / "assets/history_status_d.yaml" + if not history.is_file(): + raise FileNotFoundError(f"Prepare the Status/Writer data before training: {history}") + cfg = dataclasses.replace( + cfg, name="pi05_franka_status_d", + model=dataclasses.replace(cfg.model, history_config=str(history), max_token_len=256), + data=dataclasses.replace(cfg.data, disable_context_gripper_command=True), + aux_dataset_path=str(dataset / "status/train"), aux_dataset_fraction=.10, + ) + metadata.update( + disable_context_gripper_command=True, + status_context="48-step causal pose-command and measured-state context; command-gripper feature disabled", + writer_schedule=json.loads((dataset / "writer/dataset-index.json").read_text())["writer_schedule"], + history={**metadata["history"], "keyframe_slots": 1, "tokens": 528, "use_historical_state": False}, + ) + metadata["training_recipe"]["max_token_len"] = 256 + metadata["training_recipe"]["status_auxiliary_fraction"] = .10 + return dataclasses.replace(cfg, policy_metadata=metadata) + + +def prune_uploaded_checkpoints(checkpoint_root, export_root, receipt_root): + """Keep the newest three and milestones; never delete an unverified upload.""" + checkpoint_root, export_root, receipt_root = map(Path, (checkpoint_root, export_root, receipt_root)) + committed = sorted( + (p for p in checkpoint_root.iterdir() + if p.name.isdigit() and not p.is_symlink() and (p / "_CHECKPOINT_METADATA").is_file()), + key=lambda p: int(p.name), + ) + protected = {p.name for p in committed[-3:]} | {"5000", "10000", str(TARGET_STEPS)} + removed = [] + for checkpoint in committed: + receipt = receipt_root / f"{checkpoint.name}.json" + if checkpoint.name in protected or not receipt.is_file(): + continue + record = json.loads(receipt.read_text()) + if (record.get("full_bundle_verified") is not True + or record.get("checkpoint") != str(checkpoint.resolve())): + continue + export = export_root / checkpoint.name + if export.is_symlink(): + raise ValueError(f"Export directory must not be a symlink: {export}") + if export.exists(): + shutil.rmtree(export) + shutil.rmtree(checkpoint) + removed.append(int(checkpoint.name)) + return removed diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_evaluate.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..b33420eedf01240a46c2135bcb7e2b5747aece0a --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_evaluate.py @@ -0,0 +1,147 @@ +"""Offline action/Status checks with the exported model's real Writer and history inputs.""" +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +from pathlib import Path +import pickle + +import numpy as np + +from integrations.robomme.franka_baseline import canonical_pose, load_policy +from integrations.robomme.franka_partial import read_h5_signals +from integrations.robomme.franka_status_data import causal_context +from picmem.data.semantic_transition.sampling import even_sampling_indices +from picmem.data.semantic_transition.scheduled_writer import ScheduledWriterReader +from picmem.training.transition_metrics import evaluate_transition_predictions + + +def status_metrics(rows): + metrics = {} + for name, target, probability in ( + ("span", "span_target", "p_transition_span"), + ("conditional_last_span", "last_span_target", "p_transition_last_given_span"), + ): + valid = np.array([name == "span" or (r["span_target"] == 1 and r["last_span_valid"]) for r in rows]) + metrics[name] = evaluate_transition_predictions( + span_target=np.array([r[target] for r in rows]), status_valid=valid, + span_probability=np.array([r[probability] for r in rows]), + ) if valid.any() else None + return metrics + + +def evaluate(dataset, checkpoint, output, per_episode=25): + dataset, checkpoint, output = map(Path, (dataset, checkpoint, output)) + spec = json.loads((dataset / "dataset.json").read_text()) + policy = load_policy(checkpoint) + status = policy.metadata.get("training_setting") == "status_d" + writer = ScheduledWriterReader(dataset / "writer", expected_schedule="status") if status else None + offsets = {"validation": 0, "test": 0} + labels, status_paths = {}, defaultdict(list) + status_predictions = {split: [] for split in offsets} + if status: + labels = {(r["global_episode_id"], r["step_idx"]): r + for r in json.loads((dataset / "status/labels.json").read_text())} + for split in offsets: + for path in sorted((dataset / "status" / split / "data").glob("*.pkl")): + with path.open("rb") as stream: + row = pickle.load(stream) + status_paths[int(row["epis_idx"])].append(path.resolve()) + errors = {s: {"position_l2_m": [], "quaternion_angle_rad": [], "gripper_mae": []} for s in offsets} + horizon_errors = {s: [] for s in offsets} + observations, predictions = [], [] + for episode in spec["episodes"]: + split = episode["split"] + if split not in offsets: + continue + count = episode["samples"] + indices = np.unique(np.linspace(0, count - 1, min(count, per_episode), dtype=int)) if count else [] + action_paths = [(dataset / split / "data" / f"{offsets[split] + index}.pkl").resolve() for index in indices] + paths = list(dict.fromkeys([*action_paths, *status_paths[episode["episode_id"]]])) + if status and paths: + stamps, state_pose, target_pose, widths = read_h5_signals(Path(spec["source"]) / spec["task"] / f"{episode['episode']}.h5") + states = np.c_[state_pose, widths].astype(np.float32) + finite = np.isfinite(states[:, :7]).all(-1) + states[finite, :7] = canonical_pose(states[finite, :7]) + poses = target_pose.astype(np.float32) + finite = np.isfinite(poses).all(-1) + poses[finite] = canonical_pose(poses[finite]) + for path in paths: + with path.open("rb") as stream: + row = pickle.load(stream) + frame, episode_id = int(row["step_idx"]), int(row["epis_idx"]) + obs = {k: row[k] for k in ("image", "wrist_image", "state", "prompt")} + if policy.mem_buffer is not None: + selected = even_sampling_indices(frame, 32) + if writer is not None: + snapshot = writer.snapshot_for(global_episode_id=episode_id, frame_index=frame, task_instruction=row["prompt"]) + obs.update(history_keyframe_index=snapshot.keyframe_frame_index, current_subgoal=snapshot.current_subgoal) + if snapshot.keyframe_frame_index is not None: + selected.append(snapshot.keyframe_frame_index) + obs.update(causal_context(stamps, states, poses, frame).as_numpy()) + policy.mem_buffer._history_feats.clear() + for selected_frame in set(selected): + feature_path = dataset / "features" / f"episode_{episode_id}" / f"token_emb_{selected_frame}.npy" + policy.mem_buffer._history_feats[selected_frame] = np.load(feature_path, allow_pickle=True).item() + policy.step_idx = frame + obs["sample_key"] = [split, episode["episode"], frame, 42] + result = policy.infer(obs) + actions = result["actions"] + if actions.shape != (20, 8) or not np.isfinite(actions).all(): + raise ValueError("Restored model produced invalid actions") + target, mask = row["actions"], row["action_component_valid_mask"] + position = np.linalg.norm(actions[:, :3] - target[:, :3], axis=-1) + angle = 2 * np.arccos(np.clip(np.abs(np.sum(actions[:, 3:7] * target[:, 3:7], axis=-1)), 0, 1)) + if path in action_paths: + errors[split]["position_l2_m"].extend(position[mask[:, :3].all(-1)].tolist()) + errors[split]["quaternion_angle_rad"].extend(angle[mask[:, 3:7].all(-1)].tolist()) + errors[split]["gripper_mae"].extend(np.abs(actions[mask[:, 7], 7] - target[mask[:, 7], 7]).tolist()) + horizon_errors[split].append(position) + observations.append({"split": split, "episode": episode["episode"], "frame": frame}) + predictions.append({"split": split, "episode": episode["episode"], "frame": frame, + "actions": actions.tolist(), "position_l2_m": position.tolist(), + "action_evaluation_sample": path in action_paths, + "transition_status": result.get("transition_status")}) + if status and any(not np.isfinite(v) or not 0 <= v <= 1 for v in result["transition_status"].values()): + raise ValueError("Restored model produced invalid Status probabilities") + label = labels.get((episode_id, frame)) + if label is not None: + if label["split"] != split: + raise ValueError("Status label split does not match its observation") + status_predictions[split].append({**label, **result["transition_status"]}) + offsets[split] += count + print(f"Evaluated {split}/{episode['episode']}: {len(indices)} action samples, {len(paths)} total observations", flush=True) + report = { + "checkpoint": str(checkpoint.resolve()), "optimizer_step": int(checkpoint.name), + "all_outputs_finite": True, "action_shape": [20, 8], "per_episode": per_episode, + "scope": "Held-out offline action error; Status-D uses causal expert-history Writer projections, not a physical or closed-loop success-rate evaluation", + "splits": {s: {k: {"count": len(v), "mean": float(np.mean(v)) if v else None, + "p90": float(np.quantile(v, .9)) if v else None} for k, v in metrics.items()} + for s, metrics in errors.items()}, + "position_by_horizon": {s: {str(n): {"mean_m": float(np.mean(np.stack(v)[:, :n])), + "p90_m": float(np.quantile(np.stack(v)[:, :n], .9))} + for n in (1, 4, 16, 20)} for s, v in horizon_errors.items() if v}, + "observations": observations, + } + if status: + report["status_evaluation"] = { + "scope": "All labeled held-out windows; agent/model-reviewed labels, not human ground truth. " + "Unreviewed endpoints stay masked. Small, positive-enriched label sets do not establish " + "online trigger reliability. A split with no negatives cannot estimate false-positive rate.", + "splits": {split: status_metrics(rows) for split, rows in status_predictions.items()}, + "predictions": status_predictions, + } + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(json.dumps(report, indent=2, allow_nan=False)) + output.with_name(output.stem + "-predictions.json").write_text(json.dumps(predictions, allow_nan=False)) + print(json.dumps(report["splits"]), flush=True) + return report + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + for name in ("dataset", "checkpoint", "output"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--per-episode", type=int, default=25) + evaluate(**vars(parser.parse_args())) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_finish.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_finish.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1e39d3e3d49e629756afe1e63e2ae661395d25 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_finish.py @@ -0,0 +1,97 @@ +"""Evaluate a completed round-two model and attach its reports to the public final checkpoint.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time + +from integrations.robomme.franka_round import TARGET_STEPS, model_repo_id +from integrations.robomme.franka_round_evaluate import evaluate + + +def finish(round_root, task, setting): + from huggingface_hub import HfApi + + root = Path(round_root) + run = root / "runs" / task / setting + name = {"status_d": "pi05_franka_status_d", "baseline": "pi05_franka_baseline", "uniform32": "pi05_franka_uniform32_baseline"}[setting] + checkpoint = run / "checkpoints" / name / task.replace("_", "-") / str(TARGET_STEPS) + while not (checkpoint / "_CHECKPOINT_METADATA").is_file(): + time.sleep(10) + report = run / "evaluation.json" + if not report.exists(): + evaluate(root / "datasets" / task, checkpoint, report) + import gc + import jax + + jax.clear_caches() + gc.collect() + result = json.loads(report.read_text()) + if (result["optimizer_step"] != TARGET_STEPS or not result["all_outputs_finite"] + or Path(result["checkpoint"]).resolve() != checkpoint.resolve()): + raise ValueError("Final checkpoint evaluation did not pass") + receipt = run / "receipts" / f"{TARGET_STEPS}.json" + while not receipt.exists(): + time.sleep(10) + exported = run / "exports" / str(TARGET_STEPS) + check = exported / "packaged-inference-check.txt" + if not check.exists(): + code = ''' +import json +import numpy as np +from load_model import load, observe +policy = load() +image = np.zeros((224,224,3),dtype=np.uint8) +state = np.array([.45,0,.15,.7,-.7,0,0,0],dtype=np.float32) +observe(policy,image,state) +obs = {"image":image,"wrist_image":image,"state":state,"prompt":policy.metadata["prompt"]} +if policy.metadata.get("training_setting")=="status_d": + from mme_vla_suite.training.semantic_transition_reader import runtime_only_zero_transition_metadata + obs.update({k:v for k,v in runtime_only_zero_transition_metadata().items() if k.startswith("transition_context_")}) + obs.update(history_keyframe_index=None,current_subgoal=None) +result = policy.infer(obs) +assert result["actions"].shape==(20,8) and np.isfinite(result["actions"]).all() +print(json.dumps({"packaged_inference":"passed","shape":[20,8],"status":result.get("transition_status")})) +''' + smoke = subprocess.run([sys.executable, "-c", code], cwd=exported, capture_output=True, text=True, check=True, + env={**os.environ, "PYTHONPATH": str(exported), "CUDA_VISIBLE_DEVICES": "0"}) + check.write_text(smoke.stdout.splitlines()[-1] + "\n") + shutil.copyfile(report, exported / "evaluation.json") + info_path = exported / "checkpoint_info.json" + info = json.loads(info_path.read_text()) + info["evaluation_status"] = "completed" + info_path.write_text(json.dumps(info, indent=2)) + card_path = exported / "README.md" + card = card_path.read_text() + note = "\nFinal checkpoint checks: offline evaluation completed; packaged-source inference and finite-output checks passed. See `evaluation.json` and `packaged-inference-check.txt`; no physical robot success-rate claim.\n" + card = card.replace("Final checkpoint validation: held-out offline evaluation and packaged-source inference passed.", + "Final checkpoint checks: offline evaluation completed; packaged-source inference and finite-output checks passed.") + if note not in card: + card += note + card_path.write_text(card) + repo = model_repo_id(task, setting, TARGET_STEPS) + api = HfApi() + commit = api.upload_folder(repo_id=repo, folder_path=exported, repo_type="model", + allow_patterns=["evaluation.json", "checkpoint_info.json", "packaged-inference-check.txt", "README.md"], + commit_message="Add final offline evaluation and packaged inference validation") + remote = {f.rfilename: f.size for f in api.model_info(repo, files_metadata=True).siblings} + for filename in ("evaluation.json", "checkpoint_info.json", "packaged-inference-check.txt", "README.md"): + if remote.get(filename) != (exported / filename).stat().st_size: + raise RuntimeError(f"Final report missing or wrong size on Hub: {filename}") + complete = {"task": task, "setting": setting, "steps": TARGET_STEPS, "sample_exposures": TARGET_STEPS * 4, + "repo_id": repo, "evaluation": str(report), "packaged_inference": "passed", "commit": commit.oid} + (run / "complete.json").write_text(json.dumps(complete, indent=2)) + print(json.dumps(complete), flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--round-root", type=Path, required=True) + parser.add_argument("--task", choices=("button_order", "pick3", "shuffle"), required=True) + parser.add_argument("--setting", choices=("status_d", "baseline", "uniform32"), required=True) + finish(**vars(parser.parse_args())) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_run.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_run.py new file mode 100644 index 0000000000000000000000000000000000000000..b4b87f6dbc20bdd3237d362f77a3c0cc3a407d6b --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_round_run.py @@ -0,0 +1,249 @@ +"""Train and archive the second Franka round, preserving every uploaded 1k checkpoint.""" +from __future__ import annotations + +import argparse +import dataclasses +import importlib.metadata +import json +import os +from pathlib import Path +import shutil +import sys +import time + +from integrations.robomme.franka_round import TARGET_STEPS, checkpoint_steps, checkpoint_storage, make_config, model_repo_id, prune_uploaded_checkpoints + + +def train(dataset, run_root, setting, resume=False): + os.environ.setdefault("XLA_PYTHON_CLIENT_ALLOCATOR", "platform") + cfg = make_config(dataset, run_root, setting, resume=resume) + cfg = dataclasses.replace(cfg, policy_metadata={**cfg.policy_metadata, "gpu_allocator": "platform"}) + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "robomme/scripts")) + import train as trainer + + trainer.main(cfg) + + +def export_bundle(dataset, checkpoint, output, setting): + from integrations.robomme.franka_release import training_settings + + dataset, checkpoint, output = map(Path, (dataset, checkpoint, output)) + metadata = json.loads((checkpoint / "assets/policy_metadata.json").read_text()) + spec = json.loads((dataset / "dataset.json").read_text()) + if (metadata.get("training_round") != 2 or metadata.get("training_setting") != setting + or metadata.get("target_steps") != TARGET_STEPS or metadata.get("task") != spec["task"]): + raise ValueError("Only the matching formal second-round run may use this model name") + if setting == "status_d" and "pinned_writer" not in metadata: + raise ValueError("Status-D serving export requires the actual Writer provenance") + step = int(checkpoint.name) + repo = model_repo_id(spec["task"], setting, step) + output.mkdir(parents=True, exist_ok=True) + for folder in ("params", "assets", "resume_state"): + for source in (checkpoint / folder).rglob("*"): + if not source.is_file(): + continue + target = output / source.relative_to(checkpoint) + target.parent.mkdir(parents=True, exist_ok=True) + if target.exists() and target.stat().st_size != source.stat().st_size: + target.unlink() + if not target.exists(): + os.link(source, target) + shutil.copyfile(checkpoint / "_CHECKPOINT_METADATA", output / "_CHECKPOINT_METADATA") + shutil.copyfile(dataset / "dataset.json", output / "dataset_manifest.json") + config = training_settings(metadata, spec, step) + config.update(setting=setting, checkpoint_save_steps=checkpoint_steps(), training_round=2, + action_supervision=spec["action_supervision"], frame_coordinates=spec["frame_coordinates"], + checkpoint_retention=metadata["checkpoint_retention"]) + if setting == "status_d": + config["history"]["history_tokens"] = 528 + config["status_context"] = metadata["status_context"] + config["writer_schedule"] = metadata["writer_schedule"] + shutil.copyfile(dataset / "status/summary.json", output / "status_supervision_summary.json") + projection = json.loads((dataset / "writer/dataset-index.json").read_text()) + original_writer = json.loads((Path(projection["source_annotations"]) / "dataset-index.json").read_text()) + fields = ("writer_model", "writer_models_by_context", "writer_prompt_version", "writer_system_prompt", + "writer_evidence", "writer_api", "sampling_parameters", "dataset_version") + provenance = {k: original_writer[k] for k in fields if k in original_writer} + provenance.update(writer_schedule=projection["writer_schedule"], deployment_writer_model=projection["deployment_writer_model"]) + if "task_definition_correction" in projection: + provenance["task_definition_correction"] = projection["task_definition_correction"] + (output / "writer_provenance.json").write_text(json.dumps(provenance, indent=2)) + (output / "training_config.json").write_text(json.dumps(config, indent=2)) + (output / "checkpoint_info.json").write_text(json.dumps({ + "optimizer_step": step, "target_steps": TARGET_STEPS, "sample_exposures": step * 4, + "full_resume_state_included": True, "evaluation_status": "pending", "training_round": 2, + }, indent=2)) + code_root = Path(__file__).resolve().parents[2] + for directory in ("integrations", "src", "robomme/src", "robomme/packages/openpi-client/src"): + for source in (code_root / directory).rglob("*"): + if source.is_file() and source.suffix in {".py", ".yaml", ".yml", ".json"}: + target = output / "code" / source.relative_to(code_root) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + for directory in ("", "robomme"): + for filename in ("LICENSE", "pyproject.toml"): + source = code_root / directory / filename + if source.is_file(): + target = output / "code" / directory / filename + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + excluded = {"picmem-dev", "openpi", "openpi-client", "flash-attn-jax"} + requirements = sorted({f"{d.metadata['Name']}=={d.version}" for d in importlib.metadata.distributions() + if d.metadata["Name"].lower().replace("_", "-") not in excluded}) + (output / "requirements.txt").write_text("--extra-index-url https://download.pytorch.org/whl/cu126\n" + "\n".join(requirements) + "\n") + (output / "load_model.py").write_text( + 'from pathlib import Path\nimport sys\nROOT = Path(__file__).resolve().parent\n' + 'for path in ("code", "code/src", "code/robomme/src", "code/robomme/packages/openpi-client/src"):\n' + ' sys.path.insert(0, str(ROOT / path))\n' + 'from integrations.robomme.franka_baseline import load_policy, observe\n' + 'def load():\n return load_policy(ROOT)\n' + ) + method = ( + "Status-D: 32 uniformly sampled frames over the complete observed episode prefix [0,t], " + "plus one nullable Writer keyframe (528 visual tokens total), and a held Writer current subgoal. " + "The Writer initializes at execution start and subsequently updates at Status events. " + "Offline Writer timing is projected using coarse event estimates; this is teacher conditioning, " + "not a claim of an online predicted-Status rollout. Status span positives use supported event brackets; " + "endpoint and negative supervision comes only from explicitly reviewed windows. Unreviewed labels " + "remain masked. Review provenance is agent/model review, not human ground truth. " + "The 48-step Status context uses recorded pose commands and measured state. Its command-gripper " + "feature is disabled consistently in training and inference; no missing gripper command is invented. " + "Historical state embeddings are disabled." + if setting == "status_d" else + "Uniform32: 32 uniformly sampled frames over the complete observed episode prefix [0,t], " + "512 visual tokens, including demonstration history. Historical state embeddings are disabled." + if setting == "uniform32" else "No-history baseline: current base/wrist images, state and task instruction." + ) + (output / "README.md").write_text(f'''--- +tags: [robotics, pi05, franka, lora] +--- + +# {repo.split('/')[-1]} + +Second-round π0.5 LoRA fine-tuning for **{spec['task']}**, checkpoint **{step:,}**. +Trained locally on **4 RTX A6000 GPUs**, **global batch 4**, **per-GPU batch 1**, +without gradient accumulation. This checkpoint represents **{step * 4:,} sample exposures**; +the run targets **12,500 optimizer updates / 50,000 sample exposures**. +Checkpoints are saved every **1,000** updates and at the final **12,500**. +Steps **5,000**, **10,000**, and **12,500** have standalone model repositories. +Other complete checkpoints are retained in the +[backup archive](https://huggingface.co/datasets/fm-dev/pi05-checkpoint-backups/tree/main/checkpoints/r2) +under `task/method/stepN/` with the same loading files and full resume state. +`r2` keeps these artifacts separate from the original 6,250-step experiment. + +Warmup: **250** updates to **5e-5**; cosine decay to **5e-6** at step **12,500**. +EMA: **0.999^4 = 0.996005996001**. AdamW, LoRA rank32, seed42. +Full settings are in `training_config.json`. + +{method} + +Only robot execution rows supervise actions. Demonstration images, features and +original episode/frame coordinates remain available as history; execution start +does not reset the visual history. Episode splits and normalization use the +training split only. The recorded Cartesian end-effector/tool pose convention +must match the collection controller; do not apply an extra tool/flange offset. +Outputs have shape `(20,8)`: absolute xyz, unit XYZW quaternion in the positive-qx +chart, and gripper command in [0,1]. Numeric state/actions use STD normalization; +state tokens use a separate bounded train-q01/q99 view. + +Unknown action components remain NaN/false in the training dataset and are masked +in both flow conditioning and loss. Entirely unsupervised components: +**{spec.get('unsupervised_action_components', [])}**. In particular, Shuffle's +gripper output has no command supervision and must not be interpreted as learned +gripper control. Button Order has only limited verified closed-command labels. + +This repository includes EMA serving weights, normalization/history assets, +inference source, exact dependency versions, and full non-EMA/optimizer/RNG/sampler +resume state. Intermediate publication is not a policy-quality evaluation. +Offline evaluation, when included, does not establish real-robot success rate. + +Load with `from load_model import load, observe; policy = load()` from this bundle. +For history models call `observe(policy, base_rgb, state)` for every observed frame, +including demonstrations, and reset between episodes. Status-D additionally requires +explicit `history_keyframe_index` (an observed frame or None), `current_subgoal`, +and causal `transition_context_*` inputs in `policy.infer(...)`; its output includes +`transition_status`. Use the exported Writer schedule and matching control frame. +''') + return repo + + +def archive(round_root, settings): + from huggingface_hub import HfApi + from huggingface_hub.hf_api import RepoFile + + root = Path(round_root) + names = {"status_d": "pi05_franka_status_d", "baseline": "pi05_franka_baseline", "uniform32": "pi05_franka_uniform32_baseline"} + jobs = [(task, setting, step) for setting in settings for task in ("button_order", "pick3", "shuffle") for step in checkpoint_steps()] + api = HfApi() + while jobs: + for task, setting, step in jobs[:]: + run = root / "runs" / task / setting + checkpoints = run / "checkpoints" / names[setting] / task.replace("_", "-") + checkpoint, export = checkpoints / str(step), run / "exports" / str(step) + receipts = run / "receipts" + receipt = receipts / f"{step}.json" + if receipt.exists(): + record = json.loads(receipt.read_text()) + if record.get("full_bundle_verified") is not True: + raise ValueError(f"Incomplete upload receipt: {receipt}") + jobs.remove((task, setting, step)) + continue + if not (checkpoint / "_CHECKPOINT_METADATA").is_file(): + continue + model_id = export_bundle(root / "datasets" / task, checkpoint, export, setting) + repo, repo_type, path_in_repo = checkpoint_storage(task, setting, step) + prefix = f"{path_in_repo}/" if path_in_repo else "" + try: + api.create_repo(repo, private=False, repo_type=repo_type, exist_ok=True) + commit = api.upload_folder(repo_id=repo, folder_path=export, repo_type=repo_type, + path_in_repo=path_in_repo or None, + ignore_patterns=[".cache/**", "**/__pycache__/**"], + commit_message=f"Upload full round2 {step}-step checkpoint") + info = api.repo_info(repo, repo_type=repo_type) + if info.private: + api.update_repo_settings(repo_id=repo, repo_type=repo_type, private=False) + info = api.repo_info(repo, repo_type=repo_type) + remote = {f.path: f.size for f in api.list_repo_tree( + repo, repo_type=repo_type, path_in_repo=path_in_repo or None, recursive=True + ) if isinstance(f, RepoFile)} + for path in checkpoint.rglob("*"): + if path.is_file() and remote.get(prefix + path.relative_to(checkpoint).as_posix()) != path.stat().st_size: + raise RuntimeError(f"Source checkpoint file missing remotely: {repo}/{path.relative_to(checkpoint)}") + files = [p for p in export.rglob("*") if p.is_file() and not {".cache", "__pycache__"}.intersection(p.relative_to(export).parts)] + for path in files: + if remote.get(prefix + path.relative_to(export).as_posix()) != path.stat().st_size: + raise RuntimeError(f"Remote file missing or wrong size: {repo}/{path.relative_to(export)}") + receipts.mkdir(parents=True, exist_ok=True) + temporary = receipt.with_suffix(".tmp") + temporary.write_text(json.dumps({"checkpoint": str(checkpoint.resolve()), "repo_id": repo, + "repo_type": repo_type, "path_in_repo": path_in_repo, + "model_id": model_id, + "step": step, "full_bundle_verified": True, "commit": commit.oid, + "files": len(files), "public": not info.private}, indent=2)) + temporary.replace(receipt) + jobs.remove((task, setting, step)) + print(f"Verified {repo_type}:{repo}/{path_in_repo}", flush=True) + removed = prune_uploaded_checkpoints(checkpoints, run / "exports", receipts) + if removed: + print(f"Pruned verified local checkpoints {task}/{setting}: {removed}", flush=True) + except Exception as error: + print(f"Upload retry pending {repo}: {type(error).__name__}: {error}", flush=True) + time.sleep(30) + if jobs: + time.sleep(10) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + training = commands.add_parser("train") + training.add_argument("--dataset", type=Path, required=True) + training.add_argument("--run-root", type=Path, required=True) + training.add_argument("--setting", choices=("status_d", "baseline", "uniform32"), required=True) + training.add_argument("--resume", action="store_true") + uploading = commands.add_parser("archive") + uploading.add_argument("--round-root", type=Path, required=True) + uploading.add_argument("--settings", nargs="+", choices=("status_d", "baseline", "uniform32"), default=["status_d"]) + args = vars(parser.parse_args()) + command = args.pop("command") + {"train": train, "archive": archive}[command](**args) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_data.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ace4e916a6d62aac270914cd07be25c740c0c7ad --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_data.py @@ -0,0 +1,227 @@ +"""Bind real Franka observations, partial Status labels, and causal Writer projections.""" +from __future__ import annotations + +from collections import Counter +import hashlib +import json +from pathlib import Path +import pickle + +import numpy as np +import polars as pl +import yaml + +from integrations.robomme.franka_baseline import canonical_pose +from integrations.robomme.franka_partial import read_h5_signals +from picmem.data.semantic_transition.canonical import canonical_json_sha256 +from picmem.data.semantic_transition.pinned_keyframe import parse_pinned_episode +from picmem.data.semantic_transition.scheduled_writer import EVIDENCE_POLICY, INDEX_SCHEMA_VERSION, project_writer_episode, teacher_status_triggers +from picmem.data.semantic_transition.sequence_targets import ( + TransitionRowKey, TransitionSequence, TransitionSequenceManifest, TransitionSourceRow, + TransitionStatusRowTarget, _sequence_identity_payload, write_transition_sequence_manifest, +) +from picmem.data.semantic_transition.training_materializer import build_realized_transition_context + + +def event_records(annotations, task): + result = {} + for version in ("events-astra-v2", "events-astra-refinements-v3"): + for path in sorted((Path(annotations) / version / task).glob("episode_*/candidate_*/annotation.json")): + record = json.loads(path.read_text()) + result[record["raw_episode_id"], record["candidate_id"]] = record + return list(result.values()) + + +def prepare_writer(dataset, annotations): + dataset, annotations = Path(dataset), Path(annotations) + spec = json.loads((dataset / "dataset.json").read_text()) + output = dataset / "writer" + if output.exists(): + return json.loads((output / "dataset-index.json").read_text()) + output.mkdir() + records = event_records(annotations, spec["task"]) + version = "writer-astra-real-v2" if spec["task"] == "button_order" else "writer-astra-real-v1" + source_root = annotations / version / spec["task"] + source_index = json.loads((source_root / "dataset-index.json").read_text()) + schedule = {"mode": "status", "initialization": "episode_start", "period_frames": None, + "evidence": EVIDENCE_POLICY} + selected, summaries = [], [] + for episode in spec["episodes"]: + if episode["split"] == "excluded": + continue + source_path = source_root / f"episode_{episode['writer_episode_id']:06d}.json" + source = json.loads(source_path.read_text()) + for name in ("inference_backend", "native_backend"): + source.pop(name, None) + source["episode_id"] = episode["episode_id"] + parse_pinned_episode(source) + events = [r["event"] for r in records if r["raw_episode_id"] == episode["episode"] + and r["result"]["verdict"] == "observed" and r.get("event") is not None] + mapping = {"episode_id": str(episode["episode_id"]), "total_frames": episode["frames"], + "unit_mappings": [{"unit_id": e["event_id"], "phase": "execution", "semantic_transition": True, + "action_start_frame": e["action_start_frame"], "action_end_frame": e["action_end_frame"]} + for e in events]} + triggers, queries = teacher_status_triggers(mapping, execution_start_frame=episode["execution_start"], + task_name=f"franka_{spec['task']}") + for trigger in triggers: + trigger["trigger_source"] = "franka_coarse_event_teacher_controller" + projected = project_writer_episode(source, triggers, schedule=schedule, + dataset_version=f"franka-{spec['task']}-status-d-r2") + (output / f"episode_{episode['episode_id']:06d}.json").write_text(json.dumps(projected, indent=2)) + trace = {"source_episode": str(source_path), "global_episode_id": episode["episode_id"], + "source_episode_id": episode["writer_episode_id"], "raw_episode_id": episode["episode"], + "teacher_scope": "coarse event estimates used only for Writer timing; not certified negative Status labels", + "queries": queries, "triggers": triggers} + (output / f"teacher-{episode['episode_id']:06d}.json").write_text(json.dumps(trace, indent=2)) + selected.append(episode["episode_id"]) + summaries.append({"episode_id": episode["episode_id"], "updates": len(projected["updates"])}) + index = {"schema_version": INDEX_SCHEMA_VERSION, "complete": True, "selected_episode_ids": sorted(selected), + "episode_count": len(selected), "dataset_version": f"franka-{spec['task']}-status-d-r2", + "writer_schedule": schedule, "source_annotations": str(source_root.resolve()), + "source_dataset_version": source_index["dataset_version"], + "annotation_writer": {k: source_index[k] for k in ("writer_model", "writer_models_by_context", "writer_prompt_version", "writer_evidence")}, + "deployment_writer_model": "gemini-3.7-flash", "episodes": summaries, + "teacher_scope": "coarse interval teacher projection; source own-bank labels may differ from sparse online Writer"} + (output / "dataset-index.json").write_text(json.dumps(index, indent=2)) + return index + + +def causal_context(stamps, states, poses, target): + """Use the last contiguous observed history; the command-gripper feature is disabled.""" + first = target + for previous in range(target - 1, max(-1, target - 49), -1): + if (not np.isfinite(states[previous:previous + 2]).all() or not np.isfinite(poses[previous]).all() + or not 0 < stamps[previous + 1] - stamps[previous] <= 100_000_000): + break + first = previous + command_features = np.zeros((target - first + 1, 8), dtype=np.float32) + command_features[:-1, :7] = poses[first:target] + return build_realized_transition_context(actions=command_features, states=states[first:target + 1], + target_index=target - first) + + +def prepare_status(dataset, canonical, reviews, version="v1"): + dataset, canonical, reviews = map(Path, (dataset, canonical, reviews)) + spec = json.loads((dataset / "dataset.json").read_text()) + output = dataset / f"status-{version}" + output.mkdir(exist_ok=False) + episodes = {e["episode_id"]: e for e in spec["episodes"]} + labels = {(r["global_episode_id"], r["step_idx"]): r + for r in json.loads((reviews / f"{spec['task']}-coarse-positive-spans.json").read_text())["labels"]} + for path in reviews.rglob("*-reviewed.json"): + record = json.loads(path.read_text()) + if record.get("task") != spec["task"]: + continue + for label in record["labels"]: + key = record["global_episode_id"], label["step_idx"] + if not set(range(key[1], key[1] + 17)) <= set(label["observed_frames"]): + raise ValueError(f"Reviewed labels require complete consecutive observations: {key}") + if key in labels and labels[key]["span_target"] != label["span_target"]: + raise ValueError(f"Review contradicts a coarse-positive target; resolve explicitly: {key}") + labels[key] = {**label, "global_episode_id": key[0], "split": episodes[key[0]]["split"], + "source_review": str(path.resolve())} + inputs, input_values = {}, {} + for split in ("train", "validation", "test"): + for path in (dataset / split / "data").glob("*.pkl"): + with path.open("rb") as stream: + row = pickle.load(stream) + key = int(row["epis_idx"]), int(row["step_idx"]) + inputs[key], input_values[key] = path, row + sequences, bindings, context_rows = {s: [] for s in ("train", "validation", "test")}, [], [] + for split in sequences: + (output / split / "data").mkdir(parents=True) + (output / split / "meta").mkdir() + (output / split / "features").symlink_to(dataset / "features", target_is_directory=True) + current_episode, frames, signals = None, None, None + source_rows = {} + for key, label in sorted(labels.items()): + episode_id, step = key + episode = episodes[episode_id] + split = episode["split"] + if key not in inputs: + raise ValueError(f"Status query lacks an accepted model input: {key}") + if current_episode != episode_id: + frames = pl.read_parquet(canonical / "data/chunk-000" / f"episode_{episode['writer_episode_id']:06d}.parquet") + stamps, state_pose, target_pose, widths = read_h5_signals(Path(spec["source"]) / spec["task"] / f"{episode['episode']}.h5") + states = np.c_[state_pose, widths].astype(np.float32) + finite = np.isfinite(states[:, :7]).all(-1) + states[finite, :7] = canonical_pose(states[finite, :7]) + poses = target_pose.astype(np.float32) + finite = np.isfinite(poses).all(-1) + poses[finite] = canonical_pose(poses[finite]) + signals = stamps, states, poses + current_episode = episode_id + context = causal_context(*signals, step) + bound = [] + for frame in range(step, step + 17): + source_key = episode_id, frame + if source_key not in source_rows: + if source_key in inputs: + path = inputs[source_key] + data = path.read_bytes() + kind = "accepted_model_input" + else: + observation = frames.row(frame, named=True) + if int(observation["frame_index"]) != frame: + raise ValueError("Canonical observation/frame index mismatch") + data = pickle.dumps(observation, protocol=pickle.HIGHEST_PROTOCOL) + path = output / "observations" / f"{episode_id}-{frame}.pkl" + path.parent.mkdir(exist_ok=True) + path.write_bytes(data) + kind = "canonical_result_observation_only" + source_rows[source_key] = TransitionSourceRow( + TransitionRowKey(f"franka_{spec['task']}", episode_id, frame), hashlib.sha256(data).hexdigest()) + bindings.append({"key": source_rows[source_key].key.to_dict(), "file": str(path.resolve()), + "kind": kind, "sha256": source_rows[source_key].row_sha256}) + bound.append(source_rows[source_key]) + target = TransitionStatusRowTarget( + source_row=bound[0], chunk_index=0, candidate_observation_steps=tuple(range(step + 1, step + 17)), + candidate_observation_row_sha256=tuple(r.row_sha256 for r in bound[1:]), + transition_span_target=label["span_target"], transition_last_span_target=label["last_span_target"], + transition_status_valid=True, transition_last_span_valid=label["last_span_valid"], + realized_transition_context=context, + ) + annotation_sha = canonical_json_sha256(label) + identity = _sequence_identity_payload(start_key=target.source_row.key, annotation_sha256=annotation_sha, + reviewed_through_step=step + 16, rows=[target]) + sequence = TransitionSequence(canonical_json_sha256(identity), target.source_row.key, annotation_sha, + tuple(range(step + 1, step + 49)), step + 16, (target,)) + index = len(sequences[split]) + (output / split / "data" / f"{index}.pkl").symlink_to(inputs[key].resolve()) + sequences[split].append(sequence) + if split == "train": + values = context.as_numpy() + array = np.c_[values["transition_context_action_delta"], values["transition_context_state_delta"], values["transition_context_relative_age"]] + context_rows.extend(array[values["transition_context_valid_mask"]]) + summary = {"task": spec["task"], "counts": {}, "manifest_sha256": {}, "context_disabled_action_components": [7]} + for split, values in sequences.items(): + manifest = TransitionSequenceManifest(canonical_json_sha256(bindings), canonical_json_sha256(list(labels.values())), tuple(values)) + digest = write_transition_sequence_manifest(output / split / "transition-sequence-manifest.json", manifest) + (output / split / "meta/stats.json").write_text(json.dumps({"total_samples": len(values)})) + summary["manifest_sha256"][split] = digest + summary["counts"][split] = dict(Counter( + "negative" if not s.rows[0].transition_span_target else "positive_final" if s.rows[0].transition_last_span_valid and s.rows[0].transition_last_span_target else "positive" + for s in values)) + context_matrix = np.stack(context_rows) + mean, std = context_matrix.mean(0), context_matrix.std(0) + mean[7], std[7] = 0, 1 + std = np.where(std > 1e-6, std, 1) + summary["context_input_mean"], summary["context_input_std"] = mean.tolist(), std.tolist() + (output / "source-bindings.json").write_text(json.dumps(bindings, indent=2)) + (output / "labels.json").write_text(json.dumps(list(labels.values()), indent=2)) + (output / "summary.json").write_text(json.dumps(summary, indent=2)) + history_source = Path(__file__).resolve().parents[2] / "robomme/src/mme_vla_suite/models/config/robomme/perceptual-uniform32-status-d-modul.yaml" + history = yaml.safe_load(history_source.read_text()) + history["use_state_emb"] = False + history["pinned_keyframe"]["annotation_dir"] = str((dataset / "writer").resolve()) + history["transition_status"].update( + training_manifest_path=str((output / "train/transition-sequence-manifest.json").resolve()), + training_manifest_sha256=summary["manifest_sha256"]["train"], + context_input_mean=mean.tolist(), context_input_std=std.tolist(), + ) + (dataset / "assets/history_status_d.yaml").write_text(yaml.safe_dump(history, sort_keys=False)) + status_link = dataset / "status" + if status_link.is_symlink(): + status_link.unlink() + status_link.symlink_to(output.name, target_is_directory=True) + return summary diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_labels.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..7d546894fad112be5f2b2999244095f4281ceaef --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_labels.py @@ -0,0 +1,48 @@ +"""Use accepted coarse events only as certain positive spans; leave endpoint/negative targets unknown.""" +from __future__ import annotations + +import json +from pathlib import Path +import pickle + + +def positive_span_labels(dataset, annotations): + dataset, annotations = Path(dataset), Path(annotations) + spec = json.loads((dataset / "dataset.json").read_text()) + episodes = {e["episode"]: e for e in spec["episodes"]} + available = {} + for split in ("train", "validation", "test"): + for path in (dataset / split / "data").glob("*.pkl"): + with path.open("rb") as stream: + row = pickle.load(stream) + available.setdefault(int(row["epis_idx"]), []).append(int(row["step_idx"])) + events = {} + for version in ("events-astra-v2", "events-astra-refinements-v3"): + for path in sorted((annotations / version / spec["task"]).glob("episode_*/candidate_*/annotation.json")): + record = json.loads(path.read_text()) + events[record["raw_episode_id"], record["candidate_id"]] = (path, record) + labels, omitted = [], [] + for (raw_episode, candidate), (path, record) in sorted(events.items()): + if record["result"]["verdict"] != "observed" or record.get("event") is None: + continue + episode = episodes[raw_episode] + window = record["event"]["observable_window"] + earliest, latest = window["earliest_frame"], window["latest_frame"] + # A whole supported change bracket must lie among this chunk's resulting + # observations. No exact action endpoint or negative coverage is inferred. + starts = [t for t in available.get(episode["episode_id"], []) if t < earliest <= latest <= t + 16] + if not starts: + omitted.append({"episode": raw_episode, "candidate_id": candidate, + "reason": "No valid policy input window contains the full observable bracket"}) + continue + start = min(starts, key=lambda t: (abs(t - ((earliest + latest) / 2 - 8)), t)) + labels.append({ + "task": spec["task"], "global_episode_id": episode["episode_id"], + "raw_episode_id": raw_episode, "split": episode["split"], "step_idx": start, + "span_target": 1, "last_span_target": 0, "last_span_valid": False, + "source_annotation": str(path.resolve()), "candidate_id": candidate, + "observable_bracket": [earliest, latest], + "supervision_scope": "accepted coarse positive span only; endpoint and negatives unsupervised", + "human_ground_truth": False, + }) + return {"task": spec["task"], "labels": labels, "omitted": omitted} diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_review.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_review.py new file mode 100644 index 0000000000000000000000000000000000000000..d7da728ea71548b3a256eb7875d091d96295fa7e --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/franka_status_review.py @@ -0,0 +1,55 @@ +"""Render consecutive observed frames for targeted Status review; never assign labels automatically.""" +from __future__ import annotations + +import argparse +import io +import json +from pathlib import Path + +from PIL import Image, ImageDraw, ImageOps +import polars as pl + + +def render(canonical, output, episode_id, starts): + canonical, output = Path(canonical), Path(output) + source = canonical / "data/chunk-000" / f"episode_{episode_id:06d}.parquet" + indices = sorted({i for start in starts for i in range(max(0, start - 2), start + 19)}) + frames = pl.read_parquet(source, columns=["frame_index", "image", "wrist_image"]) + if min(starts) < 0 or max(starts) + 16 >= frames.height: + raise ValueError("Each review must include all 16 resulting observations") + selected = frames.filter(pl.col("frame_index").is_in(indices)).sort("frame_index") + tiles = [] + for row in selected.iter_rows(named=True): + for column, label in (("image", "FRONT DETAIL"), ("wrist_image", "WRIST")): + tile = Image.new("RGB", (256, 280), "black") + draw = ImageDraw.Draw(tile) + draw.text((5, 5), f"TP {row['frame_index']} {label}", fill="white") + value = row[column] + if value is None or not value.get("bytes"): + draw.text((20, 120), "MISSING VIEW", fill="red") + else: + image = Image.open(io.BytesIO(value["bytes"])).convert("RGB") + if column == "image": + image = image.crop((560, 0, min(1280, image.width), min(720, image.height))) + image = ImageOps.contain(image, (256, 256)) + tile.paste(image, ((256 - image.width) // 2, 24 + (256 - image.height) // 2)) + tiles.append(tile) + sheet = Image.new("RGB", (2048, ((len(tiles) + 7) // 8) * 280), "black") + for i, tile in enumerate(tiles): + sheet.paste(tile, ((i % 8) * 256, (i // 8) * 280)) + output.parent.mkdir(parents=True, exist_ok=True) + sheet.save(output, quality=92) + metadata = {"source": str(source), "episode_id": episode_id, "query_starts": starts, + "observed_frames": selected["frame_index"].to_list(), "review_status": "pending", + "image_size": list(sheet.size)} + output.with_suffix(".json").write_text(json.dumps(metadata, indent=2)) + return metadata + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--canonical", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--episode-id", type=int, required=True) + parser.add_argument("--starts", type=int, nargs="+", required=True) + print(json.dumps(render(**vars(parser.parse_args())))) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/manifest.json b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8be72049aed82368609535e533566a33edfb9143 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/manifest.json @@ -0,0 +1,182 @@ +{ + "schema_version": "picmem_robomme_phase_a_overlay_v6", + "base": { + "repository": "git@github.com:shulin16/wam_dev.git", + "branch": "main", + "commit": "8b1a6f7512c839b67449254535fc564db0876593", + "source_root": "robomme_policy_learning", + "source_files": { + "src/mme_vla_suite/shared/mem_buffer.py": { + "path": "robomme_policy_learning/src/mme_vla_suite/shared/mem_buffer.py", + "sha256": "ed37406c663cc9be9035cbadb2b961ad2babcc26d7fb8883535aaff1698efef7" + }, + "src/mme_vla_suite/training/dataset.py": { + "path": "robomme_policy_learning/src/mme_vla_suite/training/dataset.py", + "sha256": "435df6266d4fbc3c1c8ca1c3e7b72c7f53f398f929a62f7488daa64cdcecfa48" + } + } + }, + "target": { + "repository": "git@github.com:shulin16/wam_dev.git", + "branch": "feat/robomme-mme-vla-pipeline", + "commit": "8aeb20dc5be051606618aae4b379f97af8cc407d", + "workspace_root": "picmem" + }, + "paths": [ + { + "path": "src/mme_vla_suite/shared/mem_buffer.py", + "base_sha256": "ed37406c663cc9be9035cbadb2b961ad2babcc26d7fb8883535aaff1698efef7", + "target_preimage_sha256": "ed37406c663cc9be9035cbadb2b961ad2babcc26d7fb8883535aaff1698efef7", + "overlay_sha256": "f1f3eb94b9423eb39065322cb1751a176a2bca7778bf2e4cb878b892119e088b" + }, + { + "path": "src/mme_vla_suite/training/picmem_phase_a.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "771b71fbcf5e7f7482ab40fc1acbba2a19c24c6259a081f467e0dc946eb6062b" + }, + { + "path": "src/mme_vla_suite/training/picmem_phase_a_full_state.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "e8b165aeec8d023b9df72a956ee6b1c227a44e71e2dc7114fd383ecfc9e7fe30" + }, + { + "path": "src/mme_vla_suite/training/picmem_phase_a_reader.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "75015051b775c12e07f8d6f8b893108cba1951ecbe4a445f33a3e490d524a4aa" + }, + { + "path": "src/mme_vla_suite/training/picmem_phase_a_runtime.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "5b218f15545dd1ee75ccb7271300ef985a2b46fcaaedaf74170f638c702ae43c" + }, + { + "path": "src/mme_vla_suite/training/dataset.py", + "base_sha256": "435df6266d4fbc3c1c8ca1c3e7b72c7f53f398f929a62f7488daa64cdcecfa48", + "target_preimage_sha256": "62f867c89b0073f484ba15ff1e3a5f5554ec520bcae00b06cdcff3f19fbf0d3b", + "overlay_sha256": "e60d8f245dc20c1c805014690297a2a00f5a4fb6e18f09280d743847edab2c68" + }, + { + "path": "src/mme_vla_suite/models/representation/phase_a_reader.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "1bf7794d8acc8c478b39654894b36d6451669283f261aac41461ea034cfe8ad9" + }, + { + "path": "src/mme_vla_suite/models/config/robomme/perceptual-picmem-phase-a-modul.yaml", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "735b2c4f49a7b94c460153a8b72177a07d72dd8b224200a93c7867e8abebe286" + }, + { + "path": "scripts/picmem_phase_a_dataset_smoke.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "44b3c7e6eb99c322b76f84c121ebc8954b665a84100894049b18bf24a32a3a54" + }, + { + "path": "scripts/picmem_phase_a_checkpoint_probe.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "bf21aea49ca166db2e2c0fa788725a0bf1a52025594363d56467d3ef665012fe" + }, + { + "path": "scripts/picmem_phase_a_full_state_train.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "8aea4aa5d8a7540e42003ceceeb5a696a8f78bd8795dbee13ffba825ae764cea" + }, + { + "path": "scripts/picmem_phase_a_full_state_smoke.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "cd6e16b048b5ff1f11fa358fd571956d57d45ca78a7303dc859eb9943a4b640b" + }, + { + "path": "scripts/run_20260731_picmem_phase_a_8gpu.sh", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "b5ef128664eb1c480afb30c5b10678a1dcc5bcdc9d19e6c5c300abfa9b09170b" + }, + { + "path": "scripts/run_20260731_picmem_phase_a_h200.sh", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "b2ea492ea5e847270888a33887e560fce82474a70bf6d6ea1ce78321090f394b" + }, + { + "path": "src/mme_vla_suite/policies/picmem_phase_a_rollout.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "b429681ec30d6bf68d419bfc3ef401362656e543cec6b9d5d38b584ece09d18b" + }, + { + "path": "examples/robomme/picmem_phase_a_rollout.py", + "base_sha256": null, + "target_preimage_sha256": null, + "overlay_sha256": "ecc19b94db23699eb4143fab50349c43196e2528bda2cd4724580ef77de48b8e" + } + ], + "patches": [ + { + "path": "patches/phase_a_reader_host.patch", + "sha256": "eb00053c9db76e980f04a1d243ac2a68785535f05fa0b8034c5dd976236de31c", + "files": [ + { + "path": "src/mme_vla_suite/models/integration/history_observation.py", + "target_preimage_sha256": "e510f75496770d418d770f3e2a56f6ddc9d972a5ff68b6cd14b7a15665ec39a8", + "patched_sha256": "1823a44a223e648dee481ca0c625d21ac77117cfb70da2ebd118789a515c8087" + }, + { + "path": "src/mme_vla_suite/models/integration/history_pi0.py", + "target_preimage_sha256": "9192bfc229ac1386a3d36835c6d1e220617431d44b462016b062bc3df07a337f", + "patched_sha256": "2f7a490ac70cddcbaefb721d9ff83d52266adcb61bb01d4691cc739b2824a524" + }, + { + "path": "src/mme_vla_suite/models/representation/percep_mem.py", + "target_preimage_sha256": "39ef28ef3ee30f302b57a306351be9ae6f8cc18100a460d2e61a4f5dd1dc986f", + "patched_sha256": "a70618d50a65fcd5f50c5bccd11806e8170c0f207fab449252b367c447ed833c" + }, + { + "path": "src/mme_vla_suite/policies/robomme_policy.py", + "target_preimage_sha256": "78dbf3393bac91a16096d02b17239ca0e14c38be7ce32042d88f96b1e89e35e2", + "patched_sha256": "747a2ed2ebb7dfa83d8dd255c3b77e0367ef5dec82c041e0f1c6427c9103c12b" + }, + { + "path": "src/mme_vla_suite/training/config.py", + "target_preimage_sha256": "47041573dae2c48b99b56035763f4fd611f6cc5395e7875849dd6017227ce247", + "patched_sha256": "75580e400a350ab6535840ed2a8d99d25767c7955bd1fd2abdadde25399d9097" + }, + { + "path": "src/mme_vla_suite/training/dataloader.py", + "target_preimage_sha256": "48d7c121120bddd98f37733924519eb40c9bd7375e9dc38815f9e68c435e7cb7", + "patched_sha256": "be402665224b060e4ff762b65e27cb42658b5dfa3b717169a2c9f288d9481139" + } + ] + }, + { + "path": "patches/phase_a_rollout_host.patch", + "sha256": "859d80ccdaaf297975902182968d6881b45b942a2cea7e40b585180790ec6ca2", + "files": [ + { + "path": "examples/robomme/eval.py", + "target_preimage_sha256": "2b51b942af18f7a3412814b66eca67a0fc4ff374794bceac5f44d87e1e367c41", + "patched_sha256": "90b846c40da2593d5985c3c22fa915ba7e9f2d104f0463547193a7413e16dd28" + }, + { + "path": "src/mme_vla_suite/policies/policy.py", + "target_preimage_sha256": "dc31fce752172e1861de4840445b6c300dfa2a675a797dedbee1b108f7f4e20d", + "patched_sha256": "dae90802dcb7e14b2a5de58b636439ad7228a1289462f2e03812d26e89ddae83" + }, + { + "path": "src/mme_vla_suite/serving/websocket_policy_server.py", + "target_preimage_sha256": "7f145fb4633a0f10fc6f545e0104d2c4aeffecfd86689983ce7ddd691f89a107", + "patched_sha256": "8a8de436fe8a8c8f3664223687f1e3211035d9fee38651eed5774d41e6839c7a" + } + ] + } + ] +} diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_checkpoint_probe.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_checkpoint_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..dbfc13ba4566b176ec6f9a256acf278f048eb51d --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_checkpoint_probe.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python3 +"""Paired real-checkpoint action probe for the pinned Phase-A cohort.""" + +from __future__ import annotations + +import argparse +import dataclasses +import hashlib +import json +import os +import pickle +import re +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +import numpy as np + + +def require(condition: bool, message: str) -> None: + if not condition: + raise RuntimeError(message) + + +def load_json(path: Path, label: str) -> dict[str, Any]: + require(path.is_file(), f"missing {label}: {path}") + value = json.loads(path.read_text(encoding="utf-8")) + require(isinstance(value, dict), f"{label} must be a JSON object") + return value + + +def scalar_int(value: Any, name: str) -> int: + value = value.item() if hasattr(value, "item") else value + require(not isinstance(value, bool) and isinstance(value, int) and value >= 0, f"bad {name}: {value!r}") + return int(value) + + +def array_hash(value: Any) -> str: + array = np.ascontiguousarray(np.asarray(value)) + digest = hashlib.sha256(f"{array.dtype}:{array.shape}".encode()) + digest.update(array.tobytes()) + return digest.hexdigest() + + +def byte_exact(left: Any, right: Any) -> bool: + left_array = np.ascontiguousarray(np.asarray(left)) + right_array = np.ascontiguousarray(np.asarray(right)) + return bool( + left_array.dtype == right_array.dtype + and left_array.shape == right_array.shape + and left_array.tobytes() == right_array.tobytes() + ) + + +def observation_hashes(observation: Any, jax: Any) -> dict[str, str | None]: + result: dict[str, str | None] = {} + + def visit(name: str, value: Any) -> None: + if value is None: + result[name] = None + elif isinstance(value, Mapping): + for key in sorted(value): + visit(f"{name}.{key}", value[key]) + else: + result[name] = array_hash(jax.device_get(value)) + + for field in dataclasses.fields(observation): + if field.name != "static_image_emb": + visit(field.name, getattr(observation, field.name)) + return result + + +def load_frame(dataset: Path, episode: int, frame: int, token_per_image: int) -> tuple[Path, np.ndarray]: + path = dataset / "features" / f"episode_{episode}" / f"token_emb_{frame}.npy" + require(path.is_file(), f"missing frame feature: {path}") + payload = np.load(path, allow_pickle=True).item() + tokens = np.asarray(payload["image_emb_4x4"]) + require(tokens.shape == (1, token_per_image, 2048), f"bad feature shape: {tokens.shape}") + return path, tokens.reshape(token_per_image, 2048) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", required=True, type=Path) + parser.add_argument("--dataset", required=True, type=Path) + parser.add_argument("--sidecar-dir", required=True, type=Path) + parser.add_argument("--history-config", required=True, type=Path) + parser.add_argument("--cohort", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--subset-manifest", required=True, type=Path) + parser.add_argument("--subset-manifest-sha256", required=True) + parser.add_argument("--replacement-manifest", required=True, type=Path) + parser.add_argument("--replacement-manifest-sha256", required=True) + parser.add_argument("--best-visible-manifest", required=True, type=Path) + parser.add_argument("--best-visible-manifest-sha256", required=True) + args = parser.parse_args() + for name in ( + "checkpoint", + "dataset", + "sidecar_dir", + "history_config", + "cohort", + "output", + "subset_manifest", + ): + setattr(args, name, getattr(args, name).expanduser().resolve()) + for name in ("replacement_manifest", "best_visible_manifest"): + # Preserve the final component so package-root symlinks fail closed. + setattr(args, name, getattr(args, name).expanduser().absolute()) + for name in ( + "subset_manifest_sha256", + "replacement_manifest_sha256", + "best_visible_manifest_sha256", + ): + require( + re.fullmatch(r"[0-9a-f]{64}", getattr(args, name)) is not None, + f"{name} must be a lowercase SHA-256 digest", + ) + return args + + +def main() -> int: + args = parse_args() + require( + args.subset_manifest.is_file() and not args.subset_manifest.is_symlink(), + f"missing regular subset manifest: {args.subset_manifest}", + ) + for path in (args.replacement_manifest, args.best_visible_manifest): + require( + path.is_dir() and not path.is_symlink(), + f"missing completed frozen package root: {path}", + ) + cohort = load_json(args.cohort, "probe cohort") + require( + cohort.get("schema_version") == "picmem_phase_a_run084_checkpoint_probe_cohort_v1", + "unsupported probe cohort schema", + ) + geometry = cohort["memory_geometry"] + token_budget = scalar_int(geometry["token_budget"], "token budget") + token_per_image = scalar_int(geometry["token_per_image"], "token_per_image") + frame_budget = scalar_int(geometry["frame_capacity"], "frame capacity") + require((token_budget, token_per_image, frame_budget) == (512, 16, 32), "cohort geometry drift") + + batch_size = 64 + task = cohort["task"] + episode = scalar_int(cohort["target"]["episode"], "target episode") + step = scalar_int(cohort["target"]["step"], "target step") + cohort_evidence_frame = scalar_int( + cohort["target"]["evidence_frame"], + "cohort evidence frame", + ) + donor_episode = scalar_int(cohort["donor"]["episode"], "donor episode") + donor_frame = scalar_int(cohort["donor"]["frame"], "donor frame") + instruction = cohort["instruction"] + seed = scalar_int(cohort["sampling"]["seed"], "seed") + noise_seed = scalar_int(cohort["sampling"]["noise_seed"], "noise seed") + num_steps = scalar_int(cohort["sampling"]["num_steps"], "sampling steps") + action_tolerance = float(cohort["acceptance"]["action_tolerance"]) + margin = float(cohort["acceptance"]["margin"]) + require( + num_steps > 0, + "invalid cohort batch/sampling values", + ) + + os.environ["PICMEM_PHASE_A_SIDECAR_DIR"] = str(args.sidecar_dir) + os.environ["PICMEM_PHASE_A_SUBSET_MANIFEST"] = str(args.subset_manifest) + os.environ["PICMEM_PHASE_A_SUBSET_MANIFEST_SHA256"] = args.subset_manifest_sha256 + os.environ["PICMEM_PHASE_A_REPLACEMENT_MANIFEST"] = str(args.replacement_manifest) + os.environ["PICMEM_PHASE_A_REPLACEMENT_MANIFEST_SHA256"] = args.replacement_manifest_sha256 + os.environ["PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST"] = str(args.best_visible_manifest) + os.environ["PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST_SHA256"] = args.best_visible_manifest_sha256 + + import jax + import jax.numpy as jnp + import openpi.models.model as openpi_model + import openpi.shared.nnx_utils as nnx_utils + from mme_vla_suite.training import config as train_config + from mme_vla_suite.training.dataloader import create_data_loader + from mme_vla_suite.training.picmem_phase_a import load_episode_sidecar, selected_frame_read + from omegaconf import OmegaConf + + from picmem.memory.causal import paired_action_effect + from picmem.provenance.frozen_reader import FrozenSelectionReader + from picmem.provenance.run084 import replay_sidecar + from picmem.sampling.run084_sampler import Run084TaskBalancedSampler + + reader = FrozenSelectionReader.load_formal( + subset_manifest_path=args.subset_manifest, + subset_manifest_sha256=args.subset_manifest_sha256, + replacement_manifest_path=args.replacement_manifest, + replacement_manifest_sha256=args.replacement_manifest_sha256, + best_visible_manifest_path=args.best_visible_manifest, + best_visible_manifest_sha256=args.best_visible_manifest_sha256, + ) + candidates = tuple( + row + for row in reader.subset.records + if ( + row.task_id, + row.global_episode_id, + row.step_idx, + row.instruction, + ) + == (task, episode, step, instruction) + ) + require( + len(candidates) == 1, + f"cohort must resolve exactly one corrected sample identity, got {len(candidates)}", + ) + frozen_row = candidates[0] + dataset_index = frozen_row.new_sample_idx + loader_seed = int(reader.replacements.seed) + locator = Run084TaskBalancedSampler( + reader.subset, + batch_size=batch_size, + seed=loader_seed, + auto_advance=False, + ) + sampler_epoch, batch_cursor, batch_row = locator.locate_sample_identity( + frozen_row.sample_identity_sha256 + ) + locator.set_position(epoch=sampler_epoch, batch_cursor=batch_cursor) + sampler_state = locator.state_dict() + require( + locator.next_batch_indices()[batch_row] == dataset_index + and locator.next_batch_sample_ids()[batch_row] == frozen_row.sample_identity_sha256, + "sampler locator did not bind the exact corrected sample identity", + ) + + params_dir = args.checkpoint / "params" + assets_dir = args.checkpoint / "assets" + norm_stats = assets_dir / "robomme" / "norm_stats.json" + raw_path = args.dataset / "data" / f"{dataset_index}.pkl" + for path in (params_dir, norm_stats, raw_path, args.history_config): + require(path.exists(), f"missing probe input: {path}") + + with raw_path.open("rb") as stream: + raw = pickle.load(stream) + raw_episode = scalar_int(raw.get("epis_idx"), "raw episode") + raw_step = scalar_int(raw.get("step_idx"), "raw step") + raw_exec_start = scalar_int(raw.get("exec_start_idx"), "raw exec start") + require((raw_episode, raw_step, raw.get("prompt")) == (episode, step, instruction), "cohort row drift") + reader.subset.validate_raw_sample(dataset_index, raw) + + target_sidecar_path, _ = load_episode_sidecar( + args.sidecar_dir, + episode_id=episode, + instruction=instruction, + ) + read = selected_frame_read( + args.sidecar_dir, + episode_id=episode, + step=step, + raw_exec_start=raw_exec_start, + instruction=instruction, + frame_budget=frame_budget, + recent_anchor_count=4, + expected_task_id=frozen_row.task_id, + expected_sidecar_sha256=frozen_row.sidecar_sha256, + ) + replacement = reader.record_for(frozen_row, current_step=step) + + donor_sidecar_path, donor_sidecar = load_episode_sidecar( + args.sidecar_dir, + episode_id=donor_episode, + instruction=instruction, + ) + donor_exec_start = scalar_int(donor_sidecar.get("exec_start_step"), "donor exec start") + donor_read = replay_sidecar( + donor_sidecar, + donor_exec_start, + budget=frame_budget, + recent=4, + ) + require(donor_read.contract_id == read.contract_id, "donor contract mismatch") + require(donor_frame in donor_read.valid_indices(), "donor frame is not retained evidence") + require(donor_read.value != read.value, "donor and target memory values are equal") + + history = OmegaConf.load(args.history_config) + require( + ( + str(history.representation_type), + str(history.perceptual_memory.type), + str(history.perceptual_memory.frame_selection.type), + int(history.budget), + int(history.token_per_image), + int(history.num_views), + int(history.streaming_obs_horizon), + str(history.pool_type), + bool(history.use_pos_emb), + bool(history.use_state_emb), + str(history.memory_feature.img.net), + int(history.memory_feature.img.input_dim), + int(history.memory_feature.pos.input_dim), + int(history.memory_feature.pos.hidden_dim), + int(history.memory_feature.state.input_dim), + int(history.memory_feature.state.hidden_dim), + str(history.integration_type), + int(history.memory_token_dim), + int(history.perceptual_memory.frame_selection.frame_budget), + int(history.perceptual_memory.frame_selection.recent_anchor_count), + str(history.perceptual_memory.frame_selection.selection_mode), + str(history.perceptual_memory.frame_selection.metadata_mode), + str(history.perceptual_memory.frame_selection.reader_mode), + str(history.perceptual_memory.frame_selection.manager_mode), + ) + == ( + "perceptual", + "frame_sampling", + "picmem_phase_a", + token_budget, + token_per_image, + 1, + 16, + "mean", + True, + False, + "identity", + 2048, + 768, + 768, + 8, + 512, + "modulation", + 1024, + frame_budget, + 4, + "relevant", + "correct", + "fixed16", + "full_evolving", + ), + "history config drift", + ) + read = reader.render( + read, + replacement, + str(history.perceptual_memory.frame_selection.selection_mode), + ) + selected_frames = tuple(read.valid_indices()) + evidence_slots = tuple(read.evidence_slots) + require( + len(evidence_slots) == 1, + f"the pinned relevant checkpoint cohort requires one evidence slot, got {evidence_slots}", + ) + evidence_slot = evidence_slots[0] + evidence_frame = int(read.frame_indices[evidence_slot]) + require( + evidence_frame == cohort_evidence_frame, + "frozen relevant manifest changed the pinned semantic evidence frame", + ) + + target_feature, target_tokens = load_frame( + args.dataset, + episode, + evidence_frame, + token_per_image, + ) + donor_feature, donor_tokens = load_frame( + args.dataset, + donor_episode, + donor_frame, + token_per_image, + ) + require(target_tokens.dtype == donor_tokens.dtype, "target/donor feature dtype mismatch") + require(not np.array_equal(target_tokens, donor_tokens), "target/donor visual evidence is identical") + + base = train_config.get_config("mme_vla_suite") + data_factory = dataclasses.replace( + base.data, + assets=dataclasses.replace(base.data.assets, assets_dir=str(assets_dir)), + ) + config = dataclasses.replace( + base, + exp_name="picmem_phase_a_checkpoint_probe", + model=dataclasses.replace(base.model, history_config=history), + data=data_factory, + dataset_path=str(args.dataset), + batch_size=batch_size, + num_workers=0, + seed=seed, + sampler_seed=loader_seed, + wandb_enabled=False, + ) + data_config = config.data.create(config.assets_dirs, config.model) + require(data_config.norm_stats is not None, "checkpoint norm stats were not loaded") + loader = create_data_loader( + config.dataset_path, + data_config, + history_config=history, + action_horizon=config.model.action_horizon, + batch_size=batch_size, + shuffle=False, + num_batches=1, + num_workers=0, + seed=loader_seed, + sampler_epoch=sampler_epoch, + ) + loader.load_sampler_state_dict(sampler_state) + require( + loader.sampler_state_dict()["next_sample_ids"] == sampler_state["next_sample_ids"], + "host loader changed the restored next sample identities", + ) + observation, targets = next(iter(loader)) + require(observation is not None and targets is not None, "cohort batch is unavailable") + require(int(config.model.action_horizon) == 20, "action horizon drift") + require(int(config.model.action_dim) == 32, "action dimension drift") + require(tuple(targets.shape) == (batch_size, 20, 32), "action target shape drift") + require(tuple(observation.static_image_emb.shape) == (batch_size, token_budget, 2048), "memory shape drift") + require(tuple(observation.static_mask.shape) == (batch_size, token_budget), "memory mask shape drift") + + correct_static = np.array(jax.device_get(observation.static_image_emb), copy=True) + correct_mask = np.array(jax.device_get(observation.static_mask), copy=True) + selected = correct_static[batch_row].reshape(frame_budget, token_per_image, 2048) + frame_mask = correct_mask[batch_row].reshape(frame_budget, token_per_image) + require(np.all(frame_mask == frame_mask[:, :1]), "one frame has a partial token mask") + require(np.array_equal(frame_mask[:, 0], np.asarray(read.valid_mask)), "loader/Read mask mismatch") + require(np.array_equal(selected[evidence_slot], target_tokens), "loader/Read evidence mismatch") + shared_hashes = observation_hashes(observation, jax) + + params = openpi_model.restore_params(params_dir, dtype=jnp.bfloat16) + model = config.model.load(params) + model.eval() + sample_actions = nnx_utils.module_jit(model.sample_actions) + noise = jax.random.normal(jax.random.key(noise_seed), tuple(targets.shape)) + full_actions: list[np.ndarray] = [] + + def policy(request: Mapping[str, Any], policy_seed: int) -> np.ndarray: + visual = np.asarray(request["memory_visual"]) + mask = np.asarray(request["memory_mask"]) + require(visual.shape == (frame_budget, token_per_image, 2048), "probe visual shape drift") + require(mask.shape == (frame_budget,) and mask.dtype == np.bool_, "probe frame mask drift") + require( + np.array_equal(np.repeat(mask, token_per_image), correct_mask[batch_row]), + "probe attempted to change the memory mask", + ) + static = correct_static.copy() + static[batch_row] = visual.reshape(token_budget, 2048) + arm = observation.replace(static_image_emb=jnp.asarray(static)) + require(shared_hashes == observation_hashes(arm, jax), "a non-memory observation field changed") + actions = sample_actions( + jax.random.key(policy_seed), + arm, + num_steps=num_steps, + noise=noise, + ) + actions.block_until_ready() + full_actions.append(np.array(jax.device_get(actions), copy=True)) + return np.array(full_actions[-1][batch_row], dtype=np.float64, copy=True) + + effect = paired_action_effect( + policy, + observation={}, + read=read, + selected_visual=selected, + counterfactual_evidence=donor_tokens[None], + ground_truth_actions=np.asarray(jax.device_get(targets[batch_row])), + seed=seed, + margin=margin, + action_tolerance=action_tolerance, + ) + require(len(full_actions) == 2, f"paired probe made {len(full_actions)} full-batch policy calls") + unaffected_rows = tuple(row for row in range(batch_size) if row != batch_row) + unaffected_rows_byte_exact = all( + byte_exact(full_actions[0][row], full_actions[1][row]) for row in unaffected_rows + ) + mse_delta = effect.action_mse_delta + passed = bool( + effect.applicable + and effect.input_changed + and effect.action_changed + and effect.policy_calls == 2 + and effect.changed_slots == (evidence_slot,) + and unaffected_rows_byte_exact + and mse_delta is not None + and mse_delta > 0.0 + ) + report = { + "schema_version": "picmem_phase_a_checkpoint_probe_v2", + "status": "PASS" if passed else "FAIL", + "passed": passed, + "checkpoint": str(args.checkpoint), + "checkpoint_assets": str(assets_dir), + "cohort": str(args.cohort), + "dataset_index": dataset_index, + "target_sidecar": str(target_sidecar_path), + "donor_sidecar": str(donor_sidecar_path), + "target_feature": str(target_feature), + "donor_feature": str(donor_feature), + "changed_slots": list(effect.changed_slots), + "selected_frames": list(selected_frames), + "sample_identity_sha256": frozen_row.sample_identity_sha256, + "replacement_record_sha256": replacement.sha256, + "action_changed": effect.action_changed, + "action_l2": effect.action_l2, + "intervened_batch_row": batch_row, + "unaffected_rows": list(unaffected_rows), + "unaffected_rows_byte_exact": unaffected_rows_byte_exact, + "correct_action_mse": effect.correct_action_mse, + "negative_action_mse": effect.negative_action_mse, + "negative_minus_correct_mse": mse_delta, + "margin": margin, + "margin_loss": effect.margin_loss, + "target_visual_sha256": array_hash(target_tokens), + "donor_visual_sha256": array_hash(donor_tokens), + "action_sha256": list(effect.action_sha256 or ()), + "full_batch_action_sha256": [array_hash(value) for value in full_actions], + "noise_sha256": array_hash(jax.device_get(noise)), + "sampling": { + "policy_seed": seed, + "noise_seed": noise_seed, + "loader_seed": loader_seed, + "sampler_epoch": sampler_epoch, + "batch_cursor": batch_cursor, + "batch_row": batch_row, + "next_sample_ids": sampler_state["next_sample_ids"], + "diffusion_steps": num_steps, + }, + "shared_observation_field_hashes": shared_hashes, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps(report, sort_keys=True)) + return 0 if passed else 3 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_dataset_smoke.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_dataset_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..78a13349d988d1de1476d46be4a8a35d2370fbda --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_dataset_smoke.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""CPU smoke for the real RoboMME Phase-A dataset/config contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +TOKEN_BUDGET = 512 +TOKEN_PER_IMAGE = 16 +FRAME_BUDGET = 32 +NEUTRAL_HOST_FIELDS = ( + "picmem_token_features", + "picmem_token_mask", + "picmem_typed_role_ids", + "picmem_typed_categorical_ids", + "picmem_typed_numeric_values", + "picmem_typed_numeric_mask", + "picmem_typed_age_confidence", + "picmem_typed_contract_indices", + "picmem_typed_token_mask", + "_picmem_typed_task_index", +) + + +def require(condition: bool, message: str) -> None: + if not condition: + raise RuntimeError(message) + + +def scalar_int(value: Any, name: str) -> int: + value = value.item() if hasattr(value, "item") else value + require(not isinstance(value, bool) and isinstance(value, int) and value >= 0, f"bad {name}: {value!r}") + return int(value) + + +def load_object(path: Path, label: str) -> dict[str, Any]: + require(path.is_file(), f"missing {label}: {path}") + + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + value: dict[str, Any] = {} + for key, item in pairs: + require(key not in value, f"duplicate {label} key: {key}") + value[key] = item + return value + + value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=reject_duplicates) + require(isinstance(value, dict), f"{label} must be a JSON object: {path}") + return value + + +def fake_data_config(np: Any) -> Any: + def stats(dim: int) -> Any: + return SimpleNamespace( + mean=np.zeros(dim, dtype=np.float32), + std=np.ones(dim, dtype=np.float32), + q01=-np.ones(dim, dtype=np.float32), + q99=np.ones(dim, dtype=np.float32), + ) + + return SimpleNamespace( + norm_stats={"state": stats(8), "actions": stats(32)}, + use_quantile_norm=False, + ) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dataset", required=True, type=Path) + parser.add_argument("--sidecar-dir", required=True, type=Path) + parser.add_argument("--config", required=True, type=Path) + parser.add_argument("--cohort", required=True, type=Path) + parser.add_argument("--subset-manifest", required=True, type=Path) + parser.add_argument("--subset-manifest-sha256", required=True) + parser.add_argument("--replacement-manifest", required=True, type=Path) + parser.add_argument("--replacement-manifest-sha256", required=True) + parser.add_argument("--best-visible-manifest", required=True, type=Path) + parser.add_argument("--best-visible-manifest-sha256", required=True) + parser.add_argument("--arm-manifest", type=Path) + parser.add_argument("--arm-manifest-sha256") + parser.add_argument("--calibration-manifest", type=Path) + parser.add_argument("--calibration-manifest-sha256") + args = parser.parse_args() + for name in ( + "dataset", + "sidecar_dir", + "config", + "cohort", + "subset_manifest", + ): + setattr(args, name, getattr(args, name).expanduser().resolve()) + for name in ("replacement_manifest", "best_visible_manifest"): + # Preserve the final component so package-root symlinks fail closed. + setattr(args, name, getattr(args, name).expanduser().absolute()) + for name in ("arm_manifest", "calibration_manifest"): + value = getattr(args, name) + if value is not None: + # Preserve the final component so a manifest symlink cannot be + # hidden by Path.resolve() before the trust-boundary check. + setattr(args, name, value.expanduser().absolute()) + for name in ( + "subset_manifest_sha256", + "replacement_manifest_sha256", + "best_visible_manifest_sha256", + "arm_manifest_sha256", + "calibration_manifest_sha256", + ): + if getattr(args, name) is None: + continue + require( + re.fullmatch(r"[0-9a-f]{64}", getattr(args, name)) is not None, + f"{name} must be a lowercase SHA-256 digest", + ) + return args + + +def main() -> int: + args = parse_args() + require(args.dataset.is_dir(), f"missing dataset: {args.dataset}") + require(args.sidecar_dir.is_dir(), f"missing sidecar directory: {args.sidecar_dir}") + require( + args.subset_manifest.is_file() and not args.subset_manifest.is_symlink(), + f"missing regular subset manifest: {args.subset_manifest}", + ) + for path in (args.replacement_manifest, args.best_visible_manifest): + require( + path.is_dir() and not path.is_symlink(), + f"missing completed frozen package root: {path}", + ) + cohort = load_object(args.cohort, "checkpoint cohort") + require( + cohort.get("schema_version") == "picmem_phase_a_run084_checkpoint_probe_cohort_v1", + "unsupported checkpoint cohort schema", + ) + + os.environ["PICMEM_PHASE_A_SIDECAR_DIR"] = str(args.sidecar_dir) + os.environ["PICMEM_PHASE_A_SUBSET_MANIFEST"] = str(args.subset_manifest) + os.environ["PICMEM_PHASE_A_SUBSET_MANIFEST_SHA256"] = args.subset_manifest_sha256 + os.environ["PICMEM_PHASE_A_REPLACEMENT_MANIFEST"] = str(args.replacement_manifest) + os.environ["PICMEM_PHASE_A_REPLACEMENT_MANIFEST_SHA256"] = args.replacement_manifest_sha256 + os.environ["PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST"] = str(args.best_visible_manifest) + os.environ["PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST_SHA256"] = args.best_visible_manifest_sha256 + + import numpy as np + from mme_vla_suite.training.dataset import RoboMMEDataset + from mme_vla_suite.training.picmem_phase_a import ( + MemoryInvariantError, + load_episode_sidecar, + selected_frame_read, + ) + from mme_vla_suite.training.picmem_phase_a_reader import ( + OBSERVATION_FIELDS, + PhaseATokenMetadata, + materialize_phase_a_read, + ) + from omegaconf import OmegaConf + + from picmem.memory.contracts import ArmManifest + from picmem.ops.calibration_manifest import load_calibration_manifest + from picmem.provenance.manifest_builder import iter_formal_read_requirements + + history = OmegaConf.load(args.config) + geometry = cohort.get("memory_geometry", {}) + require(str(history.representation_type) == "perceptual", "Phase-A must use perceptual memory") + require(str(history.perceptual_memory.type) == "frame_sampling", "Phase-A must retain frame_sampling") + selection = history.perceptual_memory.frame_selection + require(str(selection.type) == "picmem_phase_a", "wrong Phase-A frame selector") + require(bool(selection.require_explicit_factors), "formal Phase-A factors must be explicit") + actual_factors = ( + str(selection.selection_mode), + str(selection.metadata_mode), + str(selection.reader_mode), + str(selection.manager_mode), + ) + launch_kind = os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND", "") + training_manifest_kind = os.environ.get("PICMEM_TRAINING_MANIFEST_KIND", "") + arm_pair = (args.arm_manifest is not None, args.arm_manifest_sha256 is not None) + calibration_pair = ( + args.calibration_manifest is not None, + args.calibration_manifest_sha256 is not None, + ) + require(arm_pair[0] == arm_pair[1], "arm manifest path/hash must be supplied together") + require( + calibration_pair[0] == calibration_pair[1], + "calibration manifest path/hash must be supplied together", + ) + if launch_kind in {"formal", "sku_smoke"}: + require( + arm_pair[0] != calibration_pair[0], + "formal/sku-smoke dataset validation requires exactly one training manifest path/hash", + ) + expected_kind = "arm_v3" if launch_kind == "formal" else "sku_calibration_v1" + require( + training_manifest_kind == expected_kind, + "training manifest kind disagrees with the Phase-A launch kind", + ) + else: + require( + not arm_pair[0] and not calibration_pair[0] and not training_manifest_kind, + "non-training dataset smoke cannot carry a training manifest", + ) + + training_manifest_id = "diagnostic-smoke" + training_manifest_sha256 = "" + expected_global_batch = None + if training_manifest_kind == "arm_v3": + require(arm_pair[0] and not calibration_pair[0], "arm_v3 requires only the arm manifest path/hash") + assert args.arm_manifest is not None and args.arm_manifest_sha256 is not None + require( + args.arm_manifest.is_file() and not args.arm_manifest.is_symlink(), + f"missing regular arm manifest: {args.arm_manifest}", + ) + require( + hashlib.sha256(args.arm_manifest.read_bytes()).hexdigest() == args.arm_manifest_sha256, + "arm manifest content hash drift", + ) + arm = ArmManifest.from_mapping(load_object(args.arm_manifest, "arm manifest")) + training_manifest_id = arm.arm_id + training_manifest_sha256 = args.arm_manifest_sha256 + expected_factors = ( + arm.selection_mode.value, + arm.metadata_mode.value, + arm.reader_mode.value, + arm.manager_mode.value, + ) + require(arm.global_batch == 64 and arm.gpu_count == 8, "arm launch geometry drift") + expected_global_batch = arm.global_batch + elif training_manifest_kind == "sku_calibration_v1": + require( + calibration_pair[0] and not arm_pair[0], + "sku_calibration_v1 requires only the calibration manifest path/hash", + ) + assert args.calibration_manifest is not None and args.calibration_manifest_sha256 is not None + require( + args.calibration_manifest.is_file() and not args.calibration_manifest.is_symlink(), + f"missing regular calibration manifest: {args.calibration_manifest}", + ) + calibration = load_calibration_manifest( + args.calibration_manifest, + expected_sha256=args.calibration_manifest_sha256, + ).manifest + training_manifest_id = calibration.calibration_id + training_manifest_sha256 = args.calibration_manifest_sha256 + expected_factors = ( + calibration.factors.selection_mode.value, + calibration.factors.metadata_mode.value, + calibration.factors.reader_mode.value, + calibration.factors.manager_mode.value, + ) + require( + calibration.runtime.gpu_count == 8 + and calibration.runtime.world_size == 8 + and calibration.sample_order.global_batch == calibration.runtime.global_batch, + "calibration launch geometry drift", + ) + require( + calibration.lineage.artifact_schema_version == "picmem_run084_artifact_hashes_v2" + and calibration.lineage.dataset_version == "run084-phasea-identity-v2-source-digest-platform-v9-20260801" + and calibration.lineage.source_digest_rows == 104_046 + and calibration.lineage.source_digest_bytes == 41_155_470_172, + "calibration manifest does not bind the full build_c Run084-v2 artifact", + ) + calibration_environment = { + "source_digest_manifest_sha256": "PICMEM_SOURCE_DIGEST_SHA256", + "source_digest_tree_sha256": "PICMEM_SOURCE_DIGEST_TREE_SHA256", + "source_digest_rows": "PICMEM_SOURCE_DIGEST_ROWS", + "source_digest_bytes": "PICMEM_SOURCE_DIGEST_BYTES", + } + for field, environment_name in calibration_environment.items(): + require( + str(getattr(calibration.lineage, field)) == os.environ.get(environment_name), + f"calibration {field} differs from {environment_name}", + ) + require( + calibration.runtime.gpu_class.value == os.environ.get("PICMEM_EXPECTED_GPU_CLASS") + and calibration.runtime.profile_id == os.environ.get("PICMEM_RUNTIME_PROFILE_ID") + and calibration.runtime.candidate_id == os.environ.get("PICMEM_RUNTIME_CANDIDATE_ID") + and calibration.runtime.policy_sha256 == os.environ.get("PICMEM_RUNTIME_POLICY_SHA256") + and calibration.runtime.plan_sha256 == os.environ.get("PICMEM_RUNTIME_PLAN_SHA256"), + "calibration runtime identity differs from the reviewed process environment", + ) + require( + calibration.sample_order.manifest_path == os.environ.get("PICMEM_SAMPLE_ORDER_MANIFEST") + and calibration.sample_order.manifest_sha256 == os.environ.get("PICMEM_SAMPLE_ORDER_MANIFEST_SHA256") + and calibration.sample_order.sample_order_sha256 == os.environ.get("PICMEM_SAMPLE_ORDER_SHA256"), + "calibration sample-order lineage differs from the process environment", + ) + expected_global_batch = calibration.runtime.global_batch + else: + require( + not os.environ.get("PICMEM_FORMAL_LAUNCH") and launch_kind not in {"formal", "sku_smoke"}, + "formal/sku-smoke dataset validation requires a training manifest", + ) + expected_factors = actual_factors + if expected_global_batch is not None: + require( + os.environ.get("BATCH_SIZE") == str(expected_global_batch), + "training manifest global batch differs from BATCH_SIZE", + ) + require( + actual_factors == expected_factors, + f"formal Phase-A factor drift: config={actual_factors}, manifest={expected_factors}", + ) + require( + ( + int(history.budget), + int(history.token_per_image), + int(history.num_views), + int(selection.frame_budget), + int(selection.recent_anchor_count), + ) + == (TOKEN_BUDGET, TOKEN_PER_IMAGE, 1, FRAME_BUDGET, 4), + "Phase-A config geometry drift", + ) + require( + ( + int(geometry.get("token_budget", -1)), + int(geometry.get("token_per_image", -1)), + int(geometry.get("num_views", -1)), + int(geometry.get("frame_capacity", -1)), + ) + == (TOKEN_BUDGET, TOKEN_PER_IMAGE, 1, FRAME_BUDGET), + "cohort/config geometry mismatch", + ) + + dataset = RoboMMEDataset( + str(args.dataset), + fake_data_config(np), + history, + action_horizon=20, + ) + require(dataset.phase_a_enabled, "dataset did not enable the Phase-A selector") + require(dataset.phase_a_sidecar_dir == args.sidecar_dir, "dataset did not bind the requested sidecars") + reader = dataset.phase_a_selection_reader + require(reader is not None, "dataset did not bind the frozen selection manifests") + require( + reader.subset.manifest_sha256 == args.subset_manifest_sha256 + and reader.replacements.sha256 == args.replacement_manifest_sha256 + and reader.best_visible.sha256 == args.best_visible_manifest_sha256, + "dataset frozen-manifest lineage drift", + ) + completeness = reader.validate_formal_completeness( + iter_formal_read_requirements( + reader=reader, + dataset_root=args.dataset, + sidecar_dir=args.sidecar_dir, + manager_mode=reader.replacements.manager_mode, + ) + ) + + dataset_index = scalar_int(cohort.get("dataset", {}).get("index"), "cohort dataset index") + require(dataset_index < len(dataset), f"cohort index {dataset_index} is outside the dataset") + raw = dataset.dataset[dataset_index] + episode = scalar_int(raw.get("epis_idx"), "epis_idx") + step = scalar_int(raw.get("step_idx"), "step_idx") + exec_start = scalar_int(raw.get("exec_start_idx"), "exec_start_idx") + instruction = raw.get("prompt") + require( + (episode, step, instruction) + == ( + scalar_int(cohort.get("target", {}).get("episode"), "cohort target episode"), + scalar_int(cohort.get("target", {}).get("step"), "cohort target step"), + cohort.get("instruction"), + ), + "cohort/raw sample identity drift", + ) + + sidecar_path, annotation = load_episode_sidecar( + args.sidecar_dir, + episode_id=episode, + instruction=instruction, + ) + frozen_row = reader.subset.validate_raw_sample(dataset_index, raw) + base_read = selected_frame_read( + args.sidecar_dir, + episode_id=episode, + step=step, + raw_exec_start=exec_start, + instruction=instruction, + expected_task_id=frozen_row.task_id, + expected_sidecar_sha256=frozen_row.sidecar_sha256, + ) + replacement = reader.record_for( + frozen_row, + current_step=step, + ) + read = reader.render(base_read, replacement, dataset.phase_a_factors.selection_mode) + plan = materialize_phase_a_read( + read, + dataset.phase_a_factors, + metadata_seed=dataset.phase_a_metadata_seed, + selection_applied=dataset.phase_a_factors.selection_mode, + ) + indices = tuple(read.valid_indices()) + require(tuple(read.valid_indices()) == indices, "Read metadata/frame-plan drift") + require(indices == tuple(sorted(set(indices))), "adapter returned a non-canonical frame plan") + require( + indices and indices[-1] <= step and len(indices) == min(FRAME_BUDGET, step + 1), + "adapter returned a non-causal or short frame plan", + ) + + sample = dataset[dataset_index] + for name in NEUTRAL_HOST_FIELDS: + require(name in sample and sample[name] is None, f"non-neutral host compatibility field: {name}") + for name in OBSERVATION_FIELDS: + require(name in sample and sample[name] is not None, f"missing Phase-A observation field: {name}") + arrays = { + "static_image_emb": np.asarray(sample["static_image_emb"]), + "static_pos_emb": np.asarray(sample["static_pos_emb"]), + "static_state_emb": np.asarray(sample["static_state_emb"]), + "static_mask": np.asarray(sample["static_mask"]), + } + expected_shapes = { + "static_image_emb": (512, 2048), + "static_pos_emb": (512, 768), + "static_state_emb": (512, 8), + "static_mask": (512,), + } + for name, value in arrays.items(): + require(value.shape == expected_shapes[name], f"{name} shape drift: {value.shape}") + require(np.isfinite(value).all(), f"{name} contains NaN/Inf") + require(arrays["static_mask"].dtype == np.bool_, "static_mask must be boolean") + expected_observation = plan.metadata.to_observation() + expected_mask = expected_observation["phase_a_valid_mask"] + require(np.array_equal(arrays["static_mask"], expected_mask), "token mask does not match Phase-A Read") + metadata = {name: np.asarray(sample[name]) for name in OBSERVATION_FIELDS} + recovered_metadata = PhaseATokenMetadata.from_observation( + metadata, + metadata_mode=str(selection.metadata_mode), + ) + for name, value in recovered_metadata.to_observation().items(): + require(np.array_equal(value, metadata[name]), f"observation roundtrip drift: {name}") + require(metadata["phase_a_frame_indices"].shape == (TOKEN_BUDGET,), "frame-index shape drift") + require(metadata["phase_a_capture_steps"].shape == (TOKEN_BUDGET,), "capture-step shape drift") + require(metadata["phase_a_time_values"].shape == (TOKEN_BUDGET, 3), "time shape drift") + require(metadata["phase_a_time_mask"].shape == (TOKEN_BUDGET, 3), "time-mask shape drift") + for name in OBSERVATION_FIELDS: + require(np.isfinite(metadata[name]).all(), f"{name} contains NaN/Inf") + require( + np.array_equal(metadata["phase_a_valid_mask"], arrays["static_mask"]), + "visual/metadata valid-mask drift", + ) + for name in OBSERVATION_FIELDS: + require( + np.array_equal(metadata[name], expected_observation[name]), + f"{name} differs from the arm-aware reader plan", + ) + + spatial_keys = {4: "2x2", 16: "4x4", 64: "8x8"} + token_offset = 0 + for frame, is_valid, token_count in zip(read.frame_indices, read.valid_mask, plan.token_counts, strict=True): + token_count = int(token_count) + if not is_valid: + token_offset += token_count + continue + feature_path = args.dataset / "features" / f"episode_{episode}" / f"token_emb_{frame}.npy" + require(feature_path.is_file(), f"missing selected feature: {feature_path}") + feature = np.load(feature_path, allow_pickle=True).item() + expected = np.asarray(feature[f"image_emb_{spatial_keys[token_count]}"]).reshape(token_count, 2048) + start = token_offset + require( + np.array_equal(arrays["static_image_emb"][start : start + token_count], expected), + f"loader/Read mismatch at frame {frame}", + ) + token_offset += token_count + require(token_offset == TOKEN_BUDGET, "arm reader token budget is not exactly 512") + + try: + selected_frame_read( + args.sidecar_dir, + episode_id=episode, + step=step, + raw_exec_start=exec_start, + instruction=f"{instruction} [wrong]", + expected_task_id=frozen_row.task_id, + expected_sidecar_sha256=frozen_row.sidecar_sha256, + ) + except MemoryInvariantError: + pass + else: + raise RuntimeError("instruction mismatch did not fail closed") + + sidecar_exec_start = scalar_int(annotation.get("exec_start_step"), "sidecar exec_start_step") + if sidecar_exec_start > 0: + try: + selected_frame_read( + args.sidecar_dir, + episode_id=episode, + step=step, + raw_exec_start=sidecar_exec_start - 1, + instruction=instruction, + expected_task_id=frozen_row.task_id, + expected_sidecar_sha256=frozen_row.sidecar_sha256, + ) + except MemoryInvariantError: + pass + else: + raise RuntimeError("negative alignment offset did not fail closed") + + print( + json.dumps( + { + "schema_version": "picmem_phase_a_dataset_smoke_v2", + "status": "PASS", + "training_manifest_kind": training_manifest_kind or "none", + "training_manifest_id": training_manifest_id, + "training_manifest_sha256": training_manifest_sha256, + "dataset_index": dataset_index, + "sample_identity_sha256": frozen_row.sample_identity_sha256, + "episode": episode, + "step": step, + "sidecar": str(sidecar_path), + "replacement_record_sha256": replacement.sha256, + "selection_mode": dataset.phase_a_factors.selection_mode.value, + "metadata_mode": dataset.phase_a_factors.metadata_mode.value, + "reader_mode": dataset.phase_a_factors.reader_mode.value, + "manager_mode": dataset.phase_a_factors.manager_mode.value, + "token_counts": [int(value) for value in plan.token_counts], + "selected_frames": list(indices), + "valid_tokens": int(arrays["static_mask"].sum()), + "frozen_completeness": completeness, + }, + sort_keys=True, + ) + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_smoke.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..60aa21c6b23f98dc5574a893072f9ba8185a3456 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_smoke.py @@ -0,0 +1,919 @@ +#!/usr/bin/env python3 +"""CPU Orbax round-trip smoke for the Phase-A full-state host contract.""" + +from __future__ import annotations + +import argparse +import dataclasses +import hashlib +import json +import multiprocessing +import os +import shutil +import signal +import tempfile +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import jax +import jax.numpy as jnp +import numpy as np +from mme_vla_suite.training.picmem_phase_a_full_state import ( + SMOKE_SUBSET_SHA256, + ContinuityEmitter, + PhaseAContract, + PhaseASmokeRandomSampler, + _validate_bound_arm, + _validate_bound_training_manifest, + _validate_phase_a_factor_contract, + initialize_phase_a_checkpoint_dir, + materialize_phase_a_contract, + restore_phase_a_checkpoint, + save_phase_a_checkpoint, + validate_phase_a_topology, +) +from openpi.shared import normalize as _normalize + +from picmem.ops.checkpoint import CheckpointError, path_sha256, validate_checkpoint +from picmem.ops.registry import RUN084_BUILD_C_LINEAGE +from picmem.ops.watchdog import ( + FailureOrigin, + RemoteState, + RemoteStatus, + WatchAction, + run_once, +) + +_DIGESTS = { + "config_sha256": "11" * 32, + "dataset_sha256": SMOKE_SUBSET_SHA256, + "cohort_sha256": "33" * 32, + "sidecar_sha256": "44" * 32, + "feature_sha256": "55" * 32, + "source_metadata_sha256": "66" * 32, + "source_digest_sha256": RUN084_BUILD_C_LINEAGE["source_digest_manifest_sha256"], + "artifact_identity_sha256": "77" * 32, + "artifact_hashes_sha256": "88" * 32, + "replacement_manifest_sha256": "aa" * 32, + "best_visible_manifest_sha256": "bb" * 32, + "sample_order_manifest_sha256": "dd" * 32, + "sample_order_sha256": "ee" * 32, + "training_manifest_sha256": "cc" * 32, + "overlay_sha256": "99" * 32, + "runtime_policy_sha256": "12" * 32, + "runtime_plan_sha256": "13" * 32, + "runtime_matrix_sha256": "14" * 32, + "runtime_calibration_sha256": "15" * 32, + "optimizer_sha256": "16" * 32, + "learning_rate_schedule_sha256": "17" * 32, +} + + +@dataclasses.dataclass(frozen=True) +class TinyState: + step: Any + params: Any + ema_params: Any + opt_state: Any + + +class TinyLoader: + def __init__(self, sampler: PhaseASmokeRandomSampler): + self.sampler = sampler + stats = _normalize.NormStats( + mean=np.asarray([0.0], dtype=np.float32), + std=np.asarray([1.0], dtype=np.float32), + q01=np.asarray([-1.0], dtype=np.float32), + q99=np.asarray([1.0], dtype=np.float32), + ) + self._data_config = SimpleNamespace(norm_stats={"actions": stats}, asset_id="robomme") + + def data_config(self) -> Any: + return self._data_config + + def sampler_state_dict(self) -> dict[str, Any]: + return self.sampler.state_dict() + + def load_sampler_state_dict(self, state: dict[str, Any]) -> None: + self.sampler.load_state_dict(state) + + +def _contract( + root: Path, + *, + generation: int, + parent: str | None, +) -> PhaseAContract: + continuity_request_id = "initial-g0" if generation == 0 else "d" * 64 + return PhaseAContract( + launch_kind="synthetic_smoke", + experiment="phase-a-smoke", + job="phase-a-smoke-job", + run_id="phase-a-smoke-r1", + generation=generation, + gpu_class="h200", + checkpoint_root=root, + interface_commit="a" * 40, + code_commit="b" * 40, + sample_order_path=Path(__file__).resolve(), + training_manifest_kind="synthetic_smoke_v1", + runtime_profile_id="synthetic-smoke-profile", + runtime_candidate_id="synthetic-smoke-candidate", + global_batch_size=64, + micro_batch_per_device=8, + gradient_accumulation_steps=1, + dataloader_workers=1, + prefetch_factor=2, + xla_preallocate=True, + xla_memory_fraction="0.9", + nccl_collective_channel_cap=32, + nccl_p2p_channel_cap=32, + xla_flags="--xla_gpu_nccl_p2p_max_nchannels=32", + runtime_checkpoint_interval=250, + parent_metadata_sha256=parent, + continuity_mode="initial" if generation == 0 else "checkpoint_resume", + continuity_request_id=continuity_request_id, + watch_state_dir=root.parent / "watch", + continuity_path=root.parent / "watch" / f"continuity-{continuity_request_id}.json", + metrics_path=root.parent / "attempts" / f"generation-{generation}" / "metrics.tsv", + **_DIGESTS, + ) + + +def _config(root: Path) -> Any: + return SimpleNamespace( + checkpoint_dir=root, + exp_name="phase-a-smoke", + optimizer="tiny-adam", + lr_schedule="tiny-positive-schedule", + ema_decay=0.99, + seed=17, + sampler_seed=(1 << 40) + 9, + save_interval=250, + ) + + +def _schedule(step: Any) -> Any: + return jnp.asarray(1e-3 / (jnp.asarray(step, dtype=jnp.float32) + 1.0), dtype=jnp.float32) + + +def _state(step: int, offset: float) -> TinyState: + return TinyState( + step=jnp.asarray(step, dtype=jnp.int32), + params={"weight": jnp.asarray([offset + 1.0, offset + 2.0], dtype=jnp.float32)}, + ema_params={"weight": jnp.asarray([offset + 3.0, offset + 4.0], dtype=jnp.float32)}, + opt_state={ + "count": jnp.asarray(step, dtype=jnp.int32), + "moment": jnp.asarray([offset + 5.0, offset + 6.0], dtype=jnp.float32), + }, + ) + + +def _tree_equal(left: Any, right: Any) -> bool: + if jax.tree_util.tree_structure(left) != jax.tree_util.tree_structure(right): + return False + return all( + np.array_equal(np.asarray(jax.device_get(a)), np.asarray(jax.device_get(b))) + for a, b in zip(jax.tree_util.tree_leaves(left), jax.tree_util.tree_leaves(right), strict=True) + ) + + +def _expect_rejected(action: Any, label: str) -> None: + try: + action() + except (CheckpointError, ValueError): + return + raise AssertionError(f"unsafe smoke case was accepted: {label}") + + +def _expect_checkpoint_reopen_rejected(root: Path, label: str) -> None: + try: + unexpected_manager, _ = initialize_phase_a_checkpoint_dir( + root, + overwrite=False, + resume=True, + launch_kind="synthetic_smoke", + ) + except (CheckpointError, ValueError): + return + unexpected_manager.close() + raise AssertionError(f"unsafe cold checkpoint reopen was accepted: {label}") + + +def _topology_checks() -> None: + valid = { + "gpu_class": "h200", + "world_size": 8, + "local_device_count": 8, + "process_count": 1, + "fsdp_devices": 8, + "batch_size": 64, + "device_kinds": ("NVIDIA H200",) * 8, + } + validate_phase_a_topology(**valid) + validate_phase_a_topology(**(valid | {"gpu_class": "a100_40g", "batch_size": 8, "device_kinds": ("A100",) * 8})) + for label, replacement in ( + ("world", {"world_size": 4}), + ("fsdp", {"fsdp_devices": 4}), + ("batch", {"batch_size": 6}), + ("boolean-batch", {"batch_size": True}), + ("sku", {"device_kinds": ("NVIDIA A100",) * 8}), + ): + _expect_rejected(lambda replacement=replacement: validate_phase_a_topology(**(valid | replacement)), label) + + +def _mutate_state(checkpoint: Path) -> None: + candidates = [ + path for path in checkpoint.joinpath("resume_state").rglob("*") if path.is_file() and path.name != "_METADATA" + ] + if not candidates: + raise AssertionError("Orbax smoke checkpoint contains no mutable resume-state payload") + with candidates[0].open("ab") as stream: + stream.write(b"corruption") + + +def _arm_binding_checks(work_dir: Path) -> None: + arm_path = work_dir / "arm.json" + contract = dataclasses.replace( + _contract(work_dir / "arm-checkpoints", generation=0, parent=None), + launch_kind="formal", + training_manifest_kind="arm_v3", + ) + arm = { + "schema_version": "picmem_phase_a_arm_v3", + "arm_id": contract.job, + "parent_commit": contract.code_commit, + "parent_tree": "d" * 40, + "host_overlay_sha256": contract.overlay_sha256, + "dataset_sha256": contract.dataset_sha256, + "sidecar_sha256": contract.sidecar_sha256, + "feature_sha256": contract.feature_sha256, + "source_metadata_sha256": contract.source_metadata_sha256, + "artifact_identity_sha256": contract.artifact_identity_sha256, + "artifact_hashes_sha256": contract.artifact_hashes_sha256, + "replacement_manifest_sha256": contract.replacement_manifest_sha256, + "best_visible_manifest_sha256": contract.best_visible_manifest_sha256, + "sample_order_manifest_sha256": contract.sample_order_manifest_sha256, + "sample_order_sha256": contract.sample_order_sha256, + "selection_mode": "relevant", + "metadata_mode": "correct", + "reader_mode": "fixed16", + "manager_mode": "full_evolving", + "gpu_sku": "H200-141GB", + "gpu_count": 8, + "global_batch": 64, + "seed": 17, + "checkpoint_interval": 250, + "resume_lineage": "phase-a/arm-smoke", + "evaluation_cohort_sha256": contract.cohort_sha256, + } + raw = (json.dumps(arm, sort_keys=True, separators=(",", ":")) + "\n").encode() + arm_path.write_bytes(raw) + contract = dataclasses.replace( + contract, + training_manifest_sha256=hashlib.sha256(raw).hexdigest(), + ) + config = SimpleNamespace(seed=17, sampler_seed=17, save_interval=250) + environment = { + "PICMEM_PHASE_A_LAUNCH_KIND": "formal", + "PICMEM_TRAINING_MANIFEST_KIND": "arm_v3", + "PICMEM_ARM_MANIFEST": str(arm_path), + "PICMEM_ARM_MANIFEST_SHA256": contract.training_manifest_sha256, + "PICMEM_SOURCE_DIGEST_SHA256": contract.source_digest_sha256, + "PICMEM_CODE_TREE": arm["parent_tree"], + "PICMEM_RESUME_LINEAGE": arm["resume_lineage"], + "PICMEM_PHASE_A_SELECTION_MODE": arm["selection_mode"], + "PICMEM_PHASE_A_METADATA_MODE": arm["metadata_mode"], + "PICMEM_PHASE_A_READER_MODE": arm["reader_mode"], + "PICMEM_PHASE_A_MANAGER_MODE": arm["manager_mode"], + } + previous = { + name: os.environ.get(name) + for name in ( + *environment, + "PICMEM_CALIBRATION_MANIFEST", + "PICMEM_CALIBRATION_MANIFEST_SHA256", + ) + } + try: + os.environ.update({name: str(value) for name, value in environment.items()}) + os.environ.pop("PICMEM_CALIBRATION_MANIFEST", None) + os.environ.pop("PICMEM_CALIBRATION_MANIFEST_SHA256", None) + _validate_bound_arm(contract, config) + factors = { + "require_explicit_factors": True, + "selection_mode": arm["selection_mode"], + "metadata_mode": arm["metadata_mode"], + "reader_mode": arm["reader_mode"], + "manager_mode": arm["manager_mode"], + } + _validate_phase_a_factor_contract(factors) + alternatives = { + "selection_mode": "uniform", + "metadata_mode": "neutral", + "reader_mode": "variable64", + "manager_mode": "fifo", + } + for name, alternative in alternatives.items(): + drifted_factors = dict(factors) + drifted_factors[name] = alternative + _expect_rejected( + lambda drifted_factors=drifted_factors: _validate_phase_a_factor_contract(drifted_factors), + f"YAML {name} masquerade", + ) + missing_factors = dict(factors) + del missing_factors["reader_mode"] + _expect_rejected( + lambda: _validate_phase_a_factor_contract(missing_factors), + "YAML missing factor", + ) + unknown_factors = dict(factors) + unknown_factors["selection_mode"] = "unknown" + _expect_rejected( + lambda: _validate_phase_a_factor_contract(unknown_factors), + "YAML unknown factor", + ) + legacy_factors = dict(factors) + legacy_factors["require_explicit_factors"] = False + _expect_rejected( + lambda: _validate_phase_a_factor_contract(legacy_factors), + "YAML legacy factor defaults", + ) + + drifted = dict(arm) + drifted["seed"] = 18 + drifted_raw = (json.dumps(drifted, sort_keys=True, separators=(",", ":")) + "\n").encode() + arm_path.write_bytes(drifted_raw) + drifted_contract = dataclasses.replace( + contract, + training_manifest_sha256=hashlib.sha256(drifted_raw).hexdigest(), + ) + os.environ["PICMEM_ARM_MANIFEST_SHA256"] = drifted_contract.training_manifest_sha256 + _expect_rejected( + lambda: _validate_bound_arm(drifted_contract, config), + "training-process arm factor drift", + ) + + duplicate_raw = b'{"arm_id":"duplicate",' + raw[1:] + arm_path.write_bytes(duplicate_raw) + duplicate_contract = dataclasses.replace( + contract, + training_manifest_sha256=hashlib.sha256(duplicate_raw).hexdigest(), + ) + os.environ["PICMEM_ARM_MANIFEST_SHA256"] = duplicate_contract.training_manifest_sha256 + _expect_rejected( + lambda: _validate_bound_arm(duplicate_contract, config), + "training-process duplicate arm key", + ) + finally: + for name, value in previous.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + + +def _calibration_binding_checks(work_dir: Path) -> None: + manifest_path = work_dir / "calibration.json" + contract = dataclasses.replace( + _contract(work_dir / "calibration-checkpoints", generation=0, parent=None), + launch_kind="sku_smoke", + gpu_class="a100_40g", + training_manifest_kind="sku_calibration_v1", + runtime_profile_id="a100-40g-calibration-v1", + runtime_candidate_id="a100-40g-batch8-v1", + global_batch_size=8, + micro_batch_per_device=1, + runtime_checkpoint_interval=25, + ) + parent_tree = "d" * 40 + source_digest_tree = "18" * 32 + resume_lineage = "phase-a/calibration-smoke" + manifest = { + "schema_version": "picmem_phase_a_sku_calibration_manifest_v1", + "calibration_id": contract.job, + "purpose": "sku_runtime_calibration", + "scientific_eligible": False, + "formal_qualifying": False, + "lineage": { + "parent_commit": contract.code_commit, + "parent_tree": parent_tree, + "host_overlay_sha256": contract.overlay_sha256, + "artifact_schema_version": "picmem_run084_artifact_hashes_v2", + "dataset_version": "run084-v2-smoke", + "artifact_hashes_sha256": contract.artifact_hashes_sha256, + "dataset_sha256": contract.dataset_sha256, + "sidecar_sha256": contract.sidecar_sha256, + "feature_sha256": contract.feature_sha256, + "source_metadata_sha256": contract.source_metadata_sha256, + "source_digest_manifest_sha256": contract.source_digest_sha256, + "source_digest_tree_sha256": source_digest_tree, + "source_digest_rows": 104_046, + "source_digest_bytes": 41_155_470_172, + "artifact_identity_sha256": contract.artifact_identity_sha256, + "replacement_manifest_sha256": contract.replacement_manifest_sha256, + "best_visible_manifest_sha256": contract.best_visible_manifest_sha256, + "evaluation_cohort_sha256": contract.cohort_sha256, + }, + "sample_order": { + "binding_id": "run084-seed17-batch8", + "dataset_sha256": contract.dataset_sha256, + "seed": 17, + "global_batch": 8, + "manifest_path": str(contract.sample_order_path), + "manifest_sha256": contract.sample_order_manifest_sha256, + "sample_order_sha256": contract.sample_order_sha256, + }, + "factors": { + "selection_mode": "relevant", + "metadata_mode": "correct", + "reader_mode": "fixed16", + "manager_mode": "full_evolving", + }, + "runtime": { + "gpu_class": contract.gpu_class, + "gpu_sku": "A100-40GB", + "gpu_count": 8, + "profile_id": contract.runtime_profile_id, + "candidate_id": contract.runtime_candidate_id, + "policy_sha256": contract.runtime_policy_sha256, + "plan_sha256": contract.runtime_plan_sha256, + "world_size": 8, + "global_batch": contract.global_batch_size, + "micro_batch_per_device": contract.micro_batch_per_device, + "gradient_accumulation_steps": contract.gradient_accumulation_steps, + "dataloader_workers": contract.dataloader_workers, + "prefetch_factor": contract.prefetch_factor, + "xla_preallocate": contract.xla_preallocate, + "xla_memory_fraction": contract.xla_memory_fraction, + "xla_base_flags": [], + "nccl_collective_channel_cap": contract.nccl_collective_channel_cap, + "nccl_p2p_channel_cap": contract.nccl_p2p_channel_cap, + "checkpoint_interval": contract.runtime_checkpoint_interval, + "train_steps": 100, + }, + "resume_lineage": resume_lineage, + } + raw = (json.dumps(manifest, allow_nan=False, sort_keys=True, separators=(",", ":")) + "\n").encode() + manifest_path.write_bytes(raw) + contract = dataclasses.replace( + contract, + training_manifest_sha256=hashlib.sha256(raw).hexdigest(), + ) + config = SimpleNamespace( + seed=17, + sampler_seed=17, + save_interval=25, + num_train_steps=100, + ) + environment = { + "PICMEM_PHASE_A_LAUNCH_KIND": "sku_smoke", + "PICMEM_TRAINING_MANIFEST_KIND": "sku_calibration_v1", + "PICMEM_CALIBRATION_MANIFEST": str(manifest_path), + "PICMEM_CALIBRATION_MANIFEST_SHA256": contract.training_manifest_sha256, + "PICMEM_CODE_TREE": parent_tree, + "PICMEM_RESUME_LINEAGE": resume_lineage, + "PICMEM_ARTIFACT_SCHEMA_VERSION": manifest["lineage"]["artifact_schema_version"], + "PICMEM_DATASET_VERSION": manifest["lineage"]["dataset_version"], + "PICMEM_SOURCE_DIGEST_TREE_SHA256": source_digest_tree, + "PICMEM_SOURCE_DIGEST_ROWS": str(manifest["lineage"]["source_digest_rows"]), + "PICMEM_SOURCE_DIGEST_BYTES": str(manifest["lineage"]["source_digest_bytes"]), + "PICMEM_PHASE_A_SELECTION_MODE": "relevant", + "PICMEM_PHASE_A_METADATA_MODE": "correct", + "PICMEM_PHASE_A_READER_MODE": "fixed16", + "PICMEM_PHASE_A_MANAGER_MODE": "full_evolving", + } + previous = { + name: os.environ.get(name) for name in (*environment, "PICMEM_ARM_MANIFEST", "PICMEM_ARM_MANIFEST_SHA256") + } + try: + os.environ.update(environment) + os.environ.pop("PICMEM_ARM_MANIFEST", None) + os.environ.pop("PICMEM_ARM_MANIFEST_SHA256", None) + _validate_bound_training_manifest(contract, config) + drifted = dict(manifest) + drifted["runtime"] = dict(manifest["runtime"]) + drifted["runtime"]["global_batch"] = 64 + drifted_raw = (json.dumps(drifted, allow_nan=False, sort_keys=True, separators=(",", ":")) + "\n").encode() + manifest_path.write_bytes(drifted_raw) + drifted_contract = dataclasses.replace( + contract, + training_manifest_sha256=hashlib.sha256(drifted_raw).hexdigest(), + ) + os.environ["PICMEM_CALIBRATION_MANIFEST_SHA256"] = drifted_contract.training_manifest_sha256 + _expect_rejected( + lambda: _validate_bound_training_manifest(drifted_contract, config), + "calibration runtime batch drift", + ) + finally: + for name, value in previous.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + + +def _paused_resume_worker( + contract: PhaseAContract, + ready_queue: Any, + resume_gate: Any, + result_queue: Any, +) -> None: + """Exercise the real host continuity producer in one long-lived process.""" + + ready_sent = False + try: + contract.metrics_path.parent.mkdir(parents=True, exist_ok=True) + contract.metrics_path.write_text("step\n37\n", encoding="utf-8") + sampler = PhaseASmokeRandomSampler( + 256, + batch_size=64, + seed=(1 << 40) + 91, + epoch=2, + batch_cursor=3, + ) + train_rng = jax.random.key(321) + emitter = ContinuityEmitter(contract, contract.metrics_path) + emitter.capture_pending( + current_step=37, + sampler_state=sampler.state_dict(), + train_rng=train_rng, + ) + ready_queue.put({"pid": os.getpid(), "sampler": sampler.state_dict()}) + ready_sent = True + if not resume_gate.wait(timeout=30): + raise TimeoutError("paused-resume smoke did not receive the in-place resume signal") + + # This is the same process, RNG, sampler cursor, and live step that was + # suspended. The request did not exist at process startup. + emitter.capture_pending( + current_step=37, + sampler_state=sampler.state_dict(), + train_rng=train_rng, + ) + pending = emitter.pending + if pending is None: + raise AssertionError("live trainer did not capture the paused-resume request") + request_id = pending.request_id + report_path = emitter._report_path(pending) + with contract.metrics_path.open("a", encoding="utf-8") as stream: + stream.write("38\n") + stream.flush() + os.fsync(stream.fileno()) + emitter.after_metric(first_metric_step=38, learning_rate=1e-4) + if emitter.pending is not None: + raise AssertionError("continuity producer did not re-arm after the completed request") + emitter.capture_pending( + current_step=38, + sampler_state=sampler.state_dict(), + train_rng=train_rng, + ) + if emitter.pending is not None: + raise AssertionError("completed continuity request was captured a second time") + result_queue.put( + { + "pid": os.getpid(), + "request_id": request_id, + "report": str(report_path), + } + ) + except BaseException as exc: # propagated to the controlling smoke process + failure = {"error": f"{type(exc).__name__}: {exc}", "pid": os.getpid()} + if not ready_sent: + ready_queue.put(failure) + result_queue.put(failure) + raise + + +def _paused_resume_continuity_checks(work_dir: Path) -> dict[str, Any]: + checkpoint_root = work_dir / "pause-checkpoints" + checkpoint_root.mkdir() + contract = _contract(checkpoint_root, generation=0, parent=None) + contract.watch_state_dir.mkdir(parents=True) + + context = multiprocessing.get_context("spawn") + ready_queue = context.Queue() + result_queue = context.Queue() + resume_gate = context.Event() + process = context.Process( + target=_paused_resume_worker, + args=(contract, ready_queue, resume_gate, result_queue), + name="picmem-paused-resume-smoke", + ) + process.start() + stopped = False + try: + ready = ready_queue.get(timeout=30) + if "error" in ready: + raise AssertionError(f"paused-resume worker failed before ready: {ready['error']}") + if ready.get("pid") != process.pid: + raise AssertionError("paused-resume worker PID changed before suspension") + os.kill(process.pid, signal.SIGSTOP) + waited_pid, wait_status = os.waitpid(process.pid, os.WUNTRACED) + if waited_pid != process.pid or not os.WIFSTOPPED(wait_status): + raise AssertionError("long-lived trainer did not enter a suspended state") + stopped = True + + def resume_in_place(_decision: Any, experiment: str, job: str) -> None: + state = json.loads(contract.watch_state_dir.joinpath("state.json").read_text(encoding="utf-8")) + pending = state.get("pending_continuity") + if (experiment, job) != (contract.experiment, contract.job): + raise AssertionError("resume callback identity drifted") + if state.get("generation") != 0 or not isinstance(pending, dict): + raise AssertionError("paused handoff was not durable before resume") + if pending.get("mode") != "paused_resume": + raise AssertionError("paused handoff used the wrong continuity mode") + if pending.get("resume_step") is not None or pending.get("expected_sampler") is not None: + raise AssertionError("watchdog guessed a lagging paused checkpoint boundary") + os.kill(process.pid, signal.SIGCONT) + resume_gate.set() + + paused = RemoteStatus( + contract.experiment, + contract.job, + RemoteState.PAUSED, + FailureOrigin.NONE, + "", + 5, # deliberately lags the authoritative in-process live step 37 + "", + ) + first = run_once( + experiment=contract.experiment, + job=contract.job, + status=paused, + state_dir=contract.watch_state_dir, + checkpoint_root=checkpoint_root, + execute=resume_in_place, + admission_check=lambda _decision: { + "allowed": True, + "observed_at": "2026-08-01T00:00:00+00:00", + "reasons": [], + }, + ) + stopped = False + if first.action is not WatchAction.RESUME or first.next_state.generation != 0: + raise AssertionError("paused job did not resume in place at the same generation") + + result = result_queue.get(timeout=30) + if "error" in result: + raise AssertionError(result["error"]) + process.join(timeout=30) + if process.exitcode != 0: + raise AssertionError(f"paused-resume worker exited {process.exitcode}") + if result.get("pid") != ready.get("pid"): + raise AssertionError("resume launched a replacement process") + + report_path = Path(result["report"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + if report["request_id"] != result["request_id"]: + raise AssertionError("continuity report was not request-bound") + if (report["resume_step"], report["first_metric_step"]) != (37, 38): + raise AssertionError("continuity report did not use the authoritative live next step") + if report["sampler"] != ready["sampler"] or len(report["rng_sha256"]) != 64: + raise AssertionError("continuity report omitted sampler/RNG evidence") + if report["prior_metrics_reused"] is not False: + raise AssertionError("paused-resume report marked the prior trajectory as reused") + if contract.metrics_path.read_text(encoding="utf-8").splitlines() != ["step", "37", "38"]: + raise AssertionError("paused-resume smoke replayed or skipped the metric trajectory") + + running = RemoteStatus(contract.experiment, contract.job, RemoteState.RUNNING) + second = run_once( + experiment=contract.experiment, + job=contract.job, + status=running, + state_dir=contract.watch_state_dir, + checkpoint_root=checkpoint_root, + ) + if second.action is not WatchAction.NONE: + raise AssertionError("verified paused-resume continuity did not return to monitoring") + if second.next_state.pending_continuity is not None: + raise AssertionError("verified paused-resume continuity remained pending") + if second.next_state.last_resume_step != 37: + raise AssertionError("watchdog did not retain the authoritative live resume step") + return { + "pid": result["pid"], + "generation": second.next_state.generation, + "resume_step": report["resume_step"], + "first_metric_step": report["first_metric_step"], + "request_id": report["request_id"], + } + finally: + if process.is_alive(): + if stopped: + os.kill(process.pid, signal.SIGCONT) + resume_gate.set() + process.terminate() + process.join(timeout=10) + + +def run(work_dir: Path) -> dict[str, Any]: + _topology_checks() + _arm_binding_checks(work_dir) + _calibration_binding_checks(work_dir) + paused_resume = _paused_resume_continuity_checks(work_dir) + checkpoint_root = work_dir / "checkpoints" + save_manager, resuming = initialize_phase_a_checkpoint_dir( + checkpoint_root, + overwrite=False, + resume=False, + launch_kind="synthetic_smoke", + ) + if resuming: + raise AssertionError("fresh smoke checkpoint manager unexpectedly resumed") + + save_contract = _contract(checkpoint_root, generation=0, parent=None) + contract_path = materialize_phase_a_contract(save_contract, _config(checkpoint_root)) + sampler = PhaseASmokeRandomSampler( + 256, + batch_size=64, + seed=(1 << 40) + 9, + epoch=3, + batch_cursor=1, + ) + loader = TinyLoader(sampler) + train_rng = jax.random.key(123) + state500 = _state(500, 10.0) + info500 = save_phase_a_checkpoint( + save_manager, + state500, + loader, + 500, + contract=save_contract, + contract_path=contract_path, + train_rng=train_rng, + schedule=_schedule, + ) + sampler.mark_batch_consumed() + state501 = _state(501, 20.0) + info501 = save_phase_a_checkpoint( + save_manager, + state501, + loader, + 501, + contract=save_contract, + contract_path=contract_path, + train_rng=train_rng, + schedule=_schedule, + ) + sampler.mark_batch_consumed() + state502 = _state(502, 30.0) + info502 = save_phase_a_checkpoint( + save_manager, + state502, + loader, + 502, + contract=save_contract, + contract_path=contract_path, + train_rng=train_rng, + schedule=_schedule, + ) + save_manager.close() + if not all((info.path / "_COMPLETE").is_file() for info in (info500, info501, info502)): + raise AssertionError("full-state smoke did not publish _COMPLETE") + if not info500.path.is_dir(): + raise AssertionError("explicit Phase-A policy did not retain step 500") + if not info501.path.is_dir() or not info502.path.is_dir(): + raise AssertionError("explicit Phase-A policy did not retain the latest two checkpoints") + asset_component = info502.state_manifest.components.get("assets") + if asset_component is None or asset_component.path != "assets": + raise AssertionError("full-state smoke did not bind the complete assets tree") + if asset_component.sha256 != path_sha256(info502.path / "assets"): + raise AssertionError("full-state smoke assets digest drifted") + for relative in ( + Path("robomme/norm_stats.json"), + Path("picmem_phase_a_full_state_contract.json"), + ): + if not (info502.path / "assets" / relative).is_file(): + raise AssertionError(f"full-state smoke is missing immutable asset {relative}") + + cold_discovery_root = work_dir / "cold-discovery-negative" + shutil.copytree(checkpoint_root, cold_discovery_root) + incomplete_newest = cold_discovery_root / "502" + (incomplete_newest / "_COMPLETE").unlink() + _expect_checkpoint_reopen_rejected(cold_discovery_root, "incomplete newest numeric checkpoint") + + restore_manager, cold_resuming = initialize_phase_a_checkpoint_dir( + checkpoint_root, + overwrite=False, + resume=True, + launch_kind="synthetic_smoke", + ) + if not cold_resuming: + restore_manager.close() + raise AssertionError("freshly reopened checkpoint manager did not discover finalized state") + + restore_sampler = PhaseASmokeRandomSampler(256, batch_size=64, seed=(1 << 40) + 9) + restore_loader = TinyLoader(restore_sampler) + restore_contract = _contract( + checkpoint_root, + generation=1, + parent=info502.metadata_sha256, + ) + try: + restored, restored_rng, restored_sampler_state, restored_info = restore_phase_a_checkpoint( + restore_manager, + _state(0, -100.0), + restore_loader, + contract=restore_contract, + train_rng=jax.random.key(999), + schedule=_schedule, + step=502, + ) + finally: + restore_manager.close() + if int(np.asarray(jax.device_get(restored.step))) != 502: + raise AssertionError("authoritative step did not round-trip") + for name in ("params", "ema_params", "opt_state"): + if not _tree_equal(getattr(restored, name), getattr(state502, name)): + raise AssertionError(f"{name} did not round-trip") + if not np.array_equal(jax.random.key_data(restored_rng), jax.random.key_data(train_rng)): + raise AssertionError("JAX train RNG did not round-trip") + if restored_sampler_state != loader.sampler_state_dict(): + raise AssertionError("sampler state did not round-trip") + if restore_loader.sampler_state_dict() != loader.sampler_state_dict(): + raise AssertionError("restored sampler was not installed in the loader") + if restored_info.metadata_sha256 != info502.metadata_sha256: + raise AssertionError("restored checkpoint identity drifted") + + variants = work_dir / "negative" + missing_complete = variants / "missing-complete" + corrupt_metadata = variants / "corrupt-metadata" + mutated_state = variants / "mutated-state" + mutated_asset = variants / "mutated-asset" + added_asset = variants / "added-asset" + for destination in ( + missing_complete, + corrupt_metadata, + mutated_state, + mutated_asset, + added_asset, + ): + shutil.copytree(info502.path, destination) + (missing_complete / "_COMPLETE").unlink() + (corrupt_metadata / "picmem_full_state.json").write_text("not-json\n", encoding="utf-8") + _mutate_state(mutated_state) + with (mutated_asset / "assets" / "picmem_phase_a_full_state_contract.json").open("ab") as stream: + stream.write(b"corruption") + (added_asset / "assets" / "unexpected-runtime-asset.json").write_text( + "{}\n", + encoding="utf-8", + ) + _expect_rejected(lambda: validate_checkpoint(missing_complete), "missing _COMPLETE") + _expect_rejected(lambda: validate_checkpoint(corrupt_metadata), "corrupt metadata") + _expect_rejected(lambda: validate_checkpoint(mutated_state), "post-finalization state mutation") + _expect_rejected(lambda: validate_checkpoint(mutated_asset), "immutable asset mutation") + _expect_rejected(lambda: validate_checkpoint(added_asset), "unmanifested asset addition") + return { + "schema_version": "picmem_phase_a_full_state_smoke_v1", + "status": "PASS", + "saved_steps": [500, 501, 502], + "restored_step": 502, + "sampler": restored_sampler_state, + "milestone_retained": True, + "cold_reopen_restore": True, + "arm_binding_revalidated": True, + "paused_resume_continuity": paused_resume, + "negative_cases": [ + "missing_complete", + "corrupt_metadata", + "mutated_state", + "mutated_asset", + "added_asset", + "cold_reopen_incomplete_newest", + "wrong_world", + "wrong_fsdp", + "wrong_batch", + "wrong_sku", + "arm_factor_drift", + "duplicate_arm_key", + "yaml_selection_mode_drift", + "yaml_metadata_mode_drift", + "yaml_reader_mode_drift", + "yaml_manager_mode_drift", + "yaml_missing_factor", + "yaml_unknown_factor", + "yaml_legacy_defaults", + ], + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--work-dir", type=Path) + args = parser.parse_args() + if args.work_dir is None: + with tempfile.TemporaryDirectory(prefix="picmem-phase-a-full-state-") as temporary: + report = run(Path(temporary)) + else: + work_dir = args.work_dir.expanduser().resolve() + if work_dir.exists() or work_dir.is_symlink(): + raise FileExistsError(f"refusing to reuse smoke work directory: {work_dir}") + work_dir.mkdir(parents=True) + report = run(work_dir) + print(json.dumps(report, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_train.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_train.py new file mode 100644 index 0000000000000000000000000000000000000000..1ca987029473cc224868113403df5c6645fc6e1f --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/scripts/picmem_phase_a_full_state_train.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Dedicated eight-GPU Phase-A trainer with trajectory-complete resume.""" + +from __future__ import annotations + +import dataclasses +import functools +import importlib.util +import json +import logging +import math +import os +import sys +from pathlib import Path +from typing import Any + +import jax +import jax.numpy as jnp +import mme_vla_suite.training.config as _config +import numpy as np +import openpi.training.sharding as sharding +import openpi.training.utils as training_utils +from flax.training import common_utils +from mme_vla_suite.training.picmem_phase_a_full_state import ( + PHASE_A_HISTORY_CONFIG, + ContinuityEmitter, + PhaseAContract, + PhaseAMetricWriter, + create_phase_a_data_loader, + initialize_phase_a_checkpoint_dir, + materialize_phase_a_contract, + restore_phase_a_checkpoint, + save_phase_a_checkpoint, +) + +CANONICAL_TRAIN_STEPS = 80_000 +SKU_SMOKE_TRAIN_STEPS = 100 +SKU_SMOKE_SAVE_INTERVAL = 25 + + +def _load_host_train_module() -> Any: + path = Path(__file__).resolve().with_name("train.py") + spec = importlib.util.spec_from_file_location("picmem_phase_a_pinned_host_train", path) + if spec is None or spec.loader is None: + raise RuntimeError(f"cannot import pinned host trainer: {path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +_host_train = _load_host_train_module() +_ORIGINAL_POST_INIT = _config.TrainConfig.__post_init__ + + +def _is_phase_a_config(config: _config.TrainConfig) -> bool: + history = config.model.history_config + return ( + config.name == "mme_vla_suite" + and isinstance(history, str) + and Path(history).name == PHASE_A_HISTORY_CONFIG + and config.typed_stage is None + ) + + +def _launch_kind() -> str: + value = os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND", "") + if value not in {"formal", "sku_smoke"}: + raise ValueError("PICMEM_PHASE_A_LAUNCH_KIND must be formal or sku_smoke") + return value + + +def _runtime_positive_int(name: str) -> int: + value = os.environ.get(name, "") + if not value.isascii() or not value.isdigit() or value == "0" or str(int(value)) != value: + raise ValueError(f"{name} must be a canonical positive integer") + return int(value) + + +def _runtime_batch_size() -> int: + batch_size = _runtime_positive_int("BATCH_SIZE") + if batch_size % 4: + raise ValueError("BATCH_SIZE must be divisible by the four Run084 tasks") + return batch_size + + +def _validate_phase_a_config( + config: _config.TrainConfig, + *, + launch_kind: str | None = None, +) -> None: + launch_kind = _launch_kind() if launch_kind is None else launch_kind + if launch_kind not in {"formal", "sku_smoke"}: + raise ValueError("Phase-A launch_kind is unsupported") + if not _is_phase_a_config(config): + raise ValueError("dedicated Phase-A entry accepts only mme_vla_suite with the reviewed history config") + if not config.full_state_checkpoints: + raise ValueError("Phase-A training requires full_state_checkpoints") + runtime_batch_size = _runtime_batch_size() + if config.batch_size != runtime_batch_size: + raise ValueError(f"Phase-A TrainConfig batch differs from runtime BATCH_SIZE={runtime_batch_size}") + if config.fsdp_devices != 8: + raise ValueError("Phase-A training requires exactly eight FSDP devices") + expected_steps = CANONICAL_TRAIN_STEPS if launch_kind == "formal" else SKU_SMOKE_TRAIN_STEPS + if config.num_train_steps != expected_steps: + raise ValueError(f"Phase-A {launch_kind} must end at step {expected_steps}") + if config.ema_decay is None: + raise ValueError("Phase-A trajectory-complete state requires EMA parameters") + if config.overwrite or config.warm_start_checkpoint is not None: + raise ValueError("Phase-A formal training forbids overwrite and params-only warm start") + if config.resume != (config.resum_ckpt_id is not None): + raise ValueError("Phase-A resume and resum_ckpt_id must be supplied together") + if config.resum_ckpt_id is not None and not 0 < config.resum_ckpt_id < expected_steps: + raise ValueError("Phase-A resume checkpoint step must be within the selected launch kind") + if config.save_interval <= 0: + raise ValueError("Phase-A save_interval must be positive") + if config.keep_period != 5_000: + raise ValueError("Phase-A requires the reviewed 5,000-step milestone period") + if launch_kind == "formal" and any(step % config.save_interval for step in (500, 1_000, 2_000, 5_000, 10_000)): + raise ValueError("Phase-A save_interval must materialize every required early milestone") + if launch_kind == "sku_smoke" and config.save_interval != SKU_SMOKE_SAVE_INTERVAL: + raise ValueError(f"Phase-A sku_smoke save_interval must equal {SKU_SMOKE_SAVE_INTERVAL}") + if config.log_interval <= 0: + raise ValueError("Phase-A log_interval must be positive") + if config.metrics_path is None: + raise ValueError("Phase-A requires one exclusive generation metrics path") + + +def _phase_a_post_init(config: _config.TrainConfig) -> None: + bypass_typed_only_gate = _is_phase_a_config(config) and config.full_state_checkpoints + if not bypass_typed_only_gate: + _ORIGINAL_POST_INIT(config) + return + object.__setattr__(config, "full_state_checkpoints", False) + try: + _ORIGINAL_POST_INIT(config) + finally: + object.__setattr__(config, "full_state_checkpoints", True) + _validate_phase_a_config(config) + + +def _install_phase_a_config_gate() -> None: + if _config.TrainConfig.__post_init__ is not _phase_a_post_init: + _config.TrainConfig.__post_init__ = _phase_a_post_init + + +def _learning_rate(schedule: Any, step: int) -> float: + value = float(np.asarray(jax.device_get(schedule(step)))) + if not math.isfinite(value) or value <= 0: + raise ValueError(f"Phase-A learning rate must be finite and positive, got {value}") + return value + + +def capability_probe() -> int: + _install_phase_a_config_gate() + base = _config.get_config("mme_vla_suite") + model = dataclasses.replace(base.model, history_config=PHASE_A_HISTORY_CONFIG) + launch_kind = _launch_kind() + batch_size = _runtime_batch_size() + steps = CANONICAL_TRAIN_STEPS if launch_kind == "formal" else SKU_SMOKE_TRAIN_STEPS + save_interval = _runtime_positive_int("SAVE_INTERVAL") + candidate = dataclasses.replace( + base, + model=model, + exp_name=f"phase-a-{launch_kind}-capability-probe", + batch_size=batch_size, + fsdp_devices=8, + full_state_checkpoints=True, + num_train_steps=steps, + save_interval=save_interval, + keep_period=5_000, + metrics_path=f"probe/{launch_kind}/attempts/generation-0/metrics.tsv", + ) + _validate_phase_a_config(candidate, launch_kind=launch_kind) + print( + json.dumps( + { + "schema_version": "picmem_phase_a_host_capability_v2", + "status": "PASS", + "launch_kind": launch_kind, + "batch_size": batch_size, + "fsdp_devices": 8, + "full_state_checkpoints": True, + "num_train_steps": candidate.num_train_steps, + "save_interval": candidate.save_interval, + }, + sort_keys=True, + ) + ) + return 0 + + +def run(config: _config.TrainConfig) -> None: + launch_kind = _launch_kind() + if launch_kind == "formal" and os.environ.get("PICMEM_FORMAL_LAUNCH") != "1": + raise ValueError("formal Phase-A training requires PICMEM_FORMAL_LAUNCH=1") + if launch_kind == "sku_smoke" and os.environ.get("PICMEM_FORMAL_LAUNCH"): + raise ValueError("sku_smoke cannot carry the formal-launch authorization marker") + _validate_phase_a_config(config, launch_kind=launch_kind) + _host_train.init_logging() + logging.info("Phase-A TrainConfig: %s", config) + + jax.config.update( + "jax_compilation_cache_dir", + str(Path(f"~/.cache/jax_{config.exp_name}").expanduser()), + ) + rng = jax.random.key(config.seed) + train_rng, init_rng = jax.random.split(rng) + mesh = sharding.make_mesh(config.fsdp_devices) + data_sharding = jax.sharding.NamedSharding( + mesh, + jax.sharding.PartitionSpec(sharding.DATA_AXIS), + ) + replicated_sharding = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec()) + + checkpoint_manager, resuming = initialize_phase_a_checkpoint_dir( + config.checkpoint_dir, + overwrite=False, + resume=config.resume, + launch_kind=launch_kind, + ) + if resuming != config.resume: + raise ValueError("Phase-A requested resume state differs from the checkpoint manager") + contract = PhaseAContract.from_environment(config) + contract_path = materialize_phase_a_contract(contract, config) + _host_train.init_wandb(config, resuming=resuming, enabled=config.wandb_enabled) + + data_config = config.data.create(config.assets_dirs, config.model) + data_loader = create_phase_a_data_loader( + config.dataset_path, + data_config, + config.model.history_config, + config.model.action_horizon, + config.batch_size, + sharding=data_sharding, + num_workers=config.num_workers, + prefetch_factor=contract.prefetch_factor, + seed=config.sampler_seed if config.sampler_seed is not None else config.seed, + subset_manifest_sha256=contract.dataset_sha256, + sidecar_sha256=contract.sidecar_sha256, + sample_order_path=contract.sample_order_path, + sample_order_manifest_sha256=contract.sample_order_manifest_sha256, + sample_order_sha256=contract.sample_order_sha256, + ) + train_state, train_state_sharding = _host_train.init_train_state( + config, + init_rng, + mesh, + resume=False, + ) + schedule = config.lr_schedule.create() + if resuming: + train_state, train_rng, _, _ = restore_phase_a_checkpoint( + checkpoint_manager, + train_state, + data_loader, + contract=contract, + train_rng=train_rng, + schedule=schedule, + step=int(config.resum_ckpt_id), + ) + jax.block_until_ready(train_state) + start_step = int(np.asarray(jax.device_get(train_state.step))) + if start_step >= config.num_train_steps: + raise ValueError("Phase-A checkpoint is already at or beyond the canonical final step") + + continuity = ContinuityEmitter(contract, contract.metrics_path) + continuity.capture_pending( + current_step=start_step, + sampler_state=data_loader.sampler_state_dict(), + train_rng=train_rng, + ) + ptrain_step = jax.jit( + functools.partial(_host_train.train_step, config), + in_shardings=(replicated_sharding, train_state_sharding, data_sharding), + out_shardings=(train_state_sharding, replicated_sharding, replicated_sharding), + donate_argnums=(1,), + ) + + data_iter = iter(data_loader) + with PhaseAMetricWriter(contract.metrics_path) as metric_writer: + while int(np.asarray(jax.device_get(train_state.step))) < config.num_train_steps: + continuity.capture_pending( + current_step=int(np.asarray(jax.device_get(train_state.step))), + sampler_state=data_loader.sampler_state_dict(), + train_rng=train_rng, + ) + batch = next(data_iter) + previous_step = int(np.asarray(jax.device_get(train_state.step))) + with sharding.set_mesh(mesh): + train_state, info, stats = ptrain_step(train_rng, train_state, batch) + authoritative_step = int(np.asarray(jax.device_get(train_state.step))) + if authoritative_step != previous_step + 1: + raise RuntimeError("Phase-A train step did not advance exactly once") + learning_rate = _learning_rate(schedule, previous_step) + scalar_info = jax.device_get(jax.tree.map(jnp.mean, info)) + metric_writer.write( + step=authoritative_step, + learning_rate=learning_rate, + metrics=scalar_info, + ) + continuity.after_metric( + first_metric_step=authoritative_step, + learning_rate=learning_rate, + ) + if authoritative_step == start_step + 1 or authoritative_step % config.log_interval == 0: + _host_train.wandb.log(scalar_info, step=authoritative_step) + logging.info( + "Phase-A step=%d metrics=%s", + authoritative_step, + common_utils.stack_forest([scalar_info]), + ) + if stats: + jax.block_until_ready(stats) + if authoritative_step % config.save_interval == 0 or authoritative_step == config.num_train_steps: + logging.info("PICMEM_CHECKPOINT_SAVE_START step=%d", authoritative_step) + save_phase_a_checkpoint( + checkpoint_manager, + train_state, + data_loader, + authoritative_step, + contract=contract, + contract_path=contract_path, + train_rng=train_rng, + schedule=schedule, + ) + + checkpoint_manager.wait_until_finished() + final_step = int(np.asarray(jax.device_get(train_state.step))) + expected_final = CANONICAL_TRAIN_STEPS if launch_kind == "formal" else SKU_SMOKE_TRAIN_STEPS + if final_step != expected_final: + raise RuntimeError(f"Phase-A {launch_kind} stopped at unexpected step {final_step}") + logging.info("PICMEM_PHASE_A_TRAIN_COMPLETE kind=%s step=%d", launch_kind, final_step) + logging.info("Final state: %s", training_utils.array_tree_to_info(train_state.params)) + + +def main() -> int: + if sys.argv[1:] == ["--phase-a-capability-probe"]: + return capability_probe() + if "--phase-a-capability-probe" in sys.argv[1:]: + raise SystemExit("--phase-a-capability-probe cannot be combined with training arguments") + _install_phase_a_config_gate() + run(_config.cli()) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-phase-a-modul.yaml b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-phase-a-modul.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ecc6e508ec44a6dc87557c72df5bd8ccb968cc94 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-phase-a-modul.yaml @@ -0,0 +1,53 @@ +# Phase-A: task/status-conditioned evidence retention with the unchanged +# FrameSamp+Modul feature encoder. Structured memory remains control-plane +# only; the policy sees exactly 512 visual/position/state tokens. +budget: 512 +num_views: 1 +token_per_image: 16 +streaming_obs_horizon: 16 +pool_type: mean +use_pos_emb: true +use_state_emb: false +memory_feature: + img: + net: identity + input_dim: 2048 + pos: + input_dim: 768 + hidden_dim: 768 + state: + input_dim: 8 + hidden_dim: 512 +integration_type: modulation +memory_token_dim: 1024 +representation_type: perceptual +perceptual_memory: + type: frame_sampling + frame_selection: + type: picmem_phase_a + sidecar_dir: ${oc.env:PICMEM_PHASE_A_SIDECAR_DIR} + subset_manifest_path: ${oc.env:PICMEM_PHASE_A_SUBSET_MANIFEST} + subset_manifest_sha256: ${oc.env:PICMEM_PHASE_A_SUBSET_MANIFEST_SHA256} + replacement_manifest_path: ${oc.env:PICMEM_PHASE_A_REPLACEMENT_MANIFEST} + replacement_manifest_sha256: ${oc.env:PICMEM_PHASE_A_REPLACEMENT_MANIFEST_SHA256} + best_visible_manifest_path: ${oc.env:PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST} + best_visible_manifest_sha256: ${oc.env:PICMEM_PHASE_A_BEST_VISIBLE_MANIFEST_SHA256} + frame_budget: 32 + recent_anchor_count: 4 + # Formal factors are supplied by the hash-bound ArmManifest launcher. There + # are deliberately no defaults: missing environment bindings fail config + # resolution before dataset construction. + require_explicit_factors: true + selection_mode: ${oc.env:PICMEM_PHASE_A_SELECTION_MODE} + metadata_mode: ${oc.env:PICMEM_PHASE_A_METADATA_MODE} + reader_mode: ${oc.env:PICMEM_PHASE_A_READER_MODE} + manager_mode: ${oc.env:PICMEM_PHASE_A_MANAGER_MODE} + metadata_seed: 0 + phase_a_reader: + event_vocab_size: 4096 + event_ordinal_vocab_size: 128 + contract_vocab_size: 128 + status_vocab_size: 32 + categorical_embed_dim: 32 + numeric_hidden_dim: 128 + fusion_hidden_dim: 256 diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-transition-v1-modul.yaml b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-transition-v1-modul.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fc41e5c4d32d48ca08156d639451ee9d135ac029 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-transition-v1-modul.yaml @@ -0,0 +1,73 @@ +# PIC-Mem + conditional final-span semantic-transition Status Head (v2). +# +# Action proposal horizon remains 20 in HistoryPi0. The Status Head sees only +# the first 16 actions that the evaluator can actually execute. Its learned +# history is a single masked pooling operation over the latest 48 realized +# action/state deltas; it never changes the Action Head input. +budget: 64 +num_views: 1 +token_per_image: 16 +streaming_obs_horizon: 16 +pool_type: mean +use_pos_emb: false +use_state_emb: false +memory_feature: + img: + net: identity + input_dim: 2048 + pos: + input_dim: 768 + hidden_dim: 768 + state: + input_dim: 8 + hidden_dim: 512 +integration_type: modulation +memory_token_dim: 1024 +representation_type: perceptual +perceptual_memory: + type: picmem + hidden_dim: 256 + token_feature_dim: 12 + max_contracts: 8 + annotation_dir: ${oc.env:PICMEM_ANNOTATION_DIR,null} + # The launcher must validate a real sidecar root before training starts. + # Once that root is present, rows outside the four run084 prototypes may + # legitimately have no sidecar and receive an empty-memory tensor. + allow_missing_annotations: true + include_values: false + include_write_metadata: false + +static_semantic_memory: + enabled: true + annotation_dir: ${oc.env:PICMEM_STAGE4_ROOT,null} + +transition_status: + # v2 changes the checkpoint parameter tree from span_out[1] to status_out[2]. + # It must never be loaded as a v1 Status Head checkpoint. + schema_version: picmem_transition_status_v2 + enabled: true + # Stage-3 v1 provides reviewed coarse action intervals and their endpoints. + # The primary target remains chunk-level span membership; a small conditional + # endpoint loss lets the controller verify immediately after the final span. + objective: coarse_span_with_conditional_last + action_proposal_horizon: 20 + execution_horizon: 16 + context_horizon: 48 + robot_vector_dim: 8 + context_hidden_dim: 128 + span_loss_weight: 1.0 + last_span_loss_weight: 0.5 + # Shadow-mode identity calibration. Replace this with the held-out fitted + # temperature before authorizing writer commits. + status_temperature: 1.0 + # This is a shadow-mode default only. Before enabling Gemini commits, fit a + # temperature and choose the lowest held-out threshold reaching >=90% + # precision. If that precision is unreachable, remain in shadow mode. + span_threshold: 0.5 + last_span_threshold: 0.5 + confirmation_tail: 4 + cooldown_chunks: 1 + # Required by the training dataset only. The policy server is stateless and + # receives realized context arrays with each request. + training_manifest_path: ${oc.env:PICMEM_TRANSITION_MANIFEST,null} + training_manifest_sha256: ${oc.env:PICMEM_TRANSITION_MANIFEST_SHA256,null} diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-v2-stage4-hybrid-modul.yaml b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-v2-stage4-hybrid-modul.yaml new file mode 100644 index 0000000000000000000000000000000000000000..18da069ddef796f8509380b062d7c2e184ccd3af --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/config/robomme/perceptual-picmem-v2-stage4-hybrid-modul.yaml @@ -0,0 +1,54 @@ +# PICMem v2: Stage4-guided selection over the validated Hybrid-512 memory. +budget: 512 +num_views: 1 +token_per_image: 16 +streaming_obs_horizon: 16 +pool_type: mean +use_pos_emb: true +use_state_emb: true + +memory_feature: + img: + net: identity + input_dim: 2048 + pos: + input_dim: 768 + hidden_dim: 768 + state: + input_dim: 8 + hidden_dim: 512 + +integration_type: modulation +memory_token_dim: 1024 +representation_type: perceptual + +perceptual_memory: + type: hybrid + +latent_memory: + mode: hybrid + use_temporal_emb: true + +static_semantic_memory: + enabled: true + annotation_dir: ${oc.env:PICMEM_STAGE4_ROOT,null} + mode: ${oc.env:PICMEM_STAGE4_MEMORY_MODE,text_anchors} + +transition_status: + schema_version: picmem_transition_status_v2 + enabled: true + objective: coarse_span_with_conditional_last + action_proposal_horizon: 20 + execution_horizon: 16 + context_horizon: 48 + robot_vector_dim: 8 + context_hidden_dim: 128 + span_loss_weight: 1.0 + last_span_loss_weight: 0.5 + status_temperature: 1.0 + span_threshold: 0.5 + last_span_threshold: 0.5 + confirmation_tail: 4 + cooldown_chunks: 1 + training_manifest_path: ${oc.env:PICMEM_TRANSITION_MANIFEST,null} + training_manifest_sha256: ${oc.env:PICMEM_TRANSITION_MANIFEST_SHA256,null} diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/phase_a_reader.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/phase_a_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..1a6786db01dca970f4cca545c4c71515fd0cddc9 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/phase_a_reader.py @@ -0,0 +1,328 @@ +"""Task-aware temporal/role residual for Phase-A visual memory tokens.""" + +from __future__ import annotations + +from typing import Any + +import flax.nnx as nnx +import jax +import jax.numpy as jnp +import numpy as np +import openpi.shared.array_typing as at +from mme_vla_suite.models.representation.utils import kernel_init + + +class PhaseAMetadataReader(nnx.Module): + """Fuse selected-frame metadata into already encoded visual tokens. + + The residual is explicitly gated by the intervention masks. A ``neutral`` + observation therefore returns the visual tokens bit-for-bit, independent + of the newly initialized reader parameters. + """ + + def __init__( + self, + *, + memory_token_dim: int, + event_vocab_size: int, + event_ordinal_vocab_size: int, + contract_vocab_size: int, + status_vocab_size: int, + categorical_embed_dim: int, + numeric_hidden_dim: int, + fusion_hidden_dim: int, + rngs: nnx.Rngs, + dtype: at.DTypeLike = jnp.float32, + ): + sizes = { + "memory_token_dim": memory_token_dim, + "event_vocab_size": event_vocab_size, + "event_ordinal_vocab_size": event_ordinal_vocab_size, + "contract_vocab_size": contract_vocab_size, + "status_vocab_size": status_vocab_size, + "categorical_embed_dim": categorical_embed_dim, + "numeric_hidden_dim": numeric_hidden_dim, + "fusion_hidden_dim": fusion_hidden_dim, + } + if any(value <= 1 for name, value in sizes.items() if name.endswith("vocab_size")): + raise ValueError("Phase-A categorical vocabularies must reserve neutral index zero") + if any(value <= 0 for name, value in sizes.items() if not name.endswith("vocab_size")): + raise ValueError("Phase-A reader dimensions must be positive") + + self.dtype = dtype + self.event_vocab_size = event_vocab_size + self.event_ordinal_vocab_size = event_ordinal_vocab_size + self.contract_vocab_size = contract_vocab_size + self.status_vocab_size = status_vocab_size + self.role_embed = nnx.Embed(4, categorical_embed_dim, rngs=rngs, dtype=dtype) + self.event_embed = nnx.Embed( + event_vocab_size, + categorical_embed_dim, + rngs=rngs, + dtype=dtype, + ) + self.ordinal_embed = nnx.Embed( + event_ordinal_vocab_size, + categorical_embed_dim, + rngs=rngs, + dtype=dtype, + ) + self.contract_embed = nnx.Embed( + contract_vocab_size, + categorical_embed_dim, + rngs=rngs, + dtype=dtype, + ) + self.status_embed = nnx.Embed( + status_vocab_size, + categorical_embed_dim, + rngs=rngs, + dtype=dtype, + ) + # [absolute_time, relative_age, delta_prev, confidence, evidence, + # three time masks, role mask, categorical mask] + self.numeric_in = nnx.Linear( + 10, + numeric_hidden_dim, + rngs=rngs, + dtype=dtype, + kernel_init=kernel_init, + ) + self.numeric_out = nnx.Linear( + numeric_hidden_dim, + numeric_hidden_dim, + rngs=rngs, + dtype=dtype, + kernel_init=kernel_init, + ) + fused_dim = 5 * categorical_embed_dim + numeric_hidden_dim + self.fuse_norm = nnx.LayerNorm(fused_dim, rngs=rngs, dtype=dtype) + self.fuse_in = nnx.Linear( + fused_dim, + fusion_hidden_dim, + rngs=rngs, + dtype=dtype, + kernel_init=kernel_init, + ) + self.out_proj = nnx.Linear( + fusion_hidden_dim, + memory_token_dim, + rngs=rngs, + dtype=dtype, + kernel_init=kernel_init, + ) + + def __call__( + self, + visual_tokens: at.Float[at.Array, "b l d"], + static_mask: at.Bool[at.Array, "b l"], + phase_a_frame_indices: at.Int[at.Array, "b l"], + phase_a_capture_steps: at.Int[at.Array, "b l"], + phase_a_time_values: at.Float[at.Array, "b l 3"], + phase_a_time_mask: at.Bool[at.Array, "b l 3"], + phase_a_role_ids: at.Int[at.Array, "b l"], + phase_a_role_mask: at.Bool[at.Array, "b l"], + phase_a_event_ids: at.Int[at.Array, "b l"], + phase_a_event_ordinals: at.Int[at.Array, "b l"], + phase_a_contract_ids: at.Int[at.Array, "b l"], + phase_a_status_ids: at.Int[at.Array, "b l"], + phase_a_categorical_mask: at.Bool[at.Array, "b l"], + phase_a_confidence: at.Float[at.Array, "b l"], + phase_a_evidence_mask: at.Bool[at.Array, "b l"], + phase_a_valid_mask: at.Bool[at.Array, "b l"], + ) -> tuple[at.Float[at.Array, "b l d"], dict[str, Any]]: + batch, length, _ = visual_tokens.shape + bl = (batch, length) + vectors = { + "static_mask": static_mask, + "frame_indices": phase_a_frame_indices, + "capture_steps": phase_a_capture_steps, + "role_ids": phase_a_role_ids, + "role_mask": phase_a_role_mask, + "event_ids": phase_a_event_ids, + "event_ordinals": phase_a_event_ordinals, + "contract_ids": phase_a_contract_ids, + "status_ids": phase_a_status_ids, + "categorical_mask": phase_a_categorical_mask, + "confidence": phase_a_confidence, + "evidence_mask": phase_a_evidence_mask, + "valid_mask": phase_a_valid_mask, + } + for name, value in vectors.items(): + if value.shape != bl: + raise ValueError(f"Phase-A {name} shape {value.shape} != {bl}") + if phase_a_time_values.shape != (*bl, 3): + raise ValueError("Phase-A time_values must have three channels") + if phase_a_time_mask.shape != (*bl, 3): + raise ValueError("Phase-A time_mask must have three channels") + for name in ( + "static_mask", + "role_mask", + "categorical_mask", + "evidence_mask", + "valid_mask", + ): + if vectors[name].dtype != jnp.bool_: + raise ValueError(f"Phase-A {name} must be boolean") + if phase_a_time_mask.dtype != jnp.bool_: + raise ValueError("Phase-A time_mask must be boolean") + for name in ( + "frame_indices", + "capture_steps", + "role_ids", + "event_ids", + "event_ordinals", + "contract_ids", + "status_ids", + ): + if not jnp.issubdtype(vectors[name].dtype, jnp.integer): + raise ValueError(f"Phase-A {name} must be integer") + if not jnp.issubdtype(phase_a_time_values.dtype, jnp.floating): + raise ValueError("Phase-A time_values must be floating point") + if not jnp.issubdtype(phase_a_confidence.dtype, jnp.floating): + raise ValueError("Phase-A confidence must be floating point") + if _is_concrete(static_mask, phase_a_valid_mask) and not np.array_equal( + np.asarray(static_mask), + np.asarray(phase_a_valid_mask), + ): + raise ValueError("Phase-A valid mask must equal the visual token mask") + if _is_concrete( + phase_a_frame_indices, + phase_a_capture_steps, + phase_a_valid_mask, + phase_a_time_values, + phase_a_time_mask, + phase_a_role_ids, + phase_a_role_mask, + phase_a_event_ids, + phase_a_event_ordinals, + phase_a_contract_ids, + phase_a_status_ids, + phase_a_categorical_mask, + phase_a_confidence, + phase_a_evidence_mask, + ): + frame_indices = np.asarray(phase_a_frame_indices) + capture_steps = np.asarray(phase_a_capture_steps) + valid_mask = np.asarray(phase_a_valid_mask) + invalid_mask = ~valid_mask + if np.any(frame_indices < 0) or np.any(capture_steps < 0): + raise ValueError("Phase-A frame indices and capture steps must be non-negative") + if np.any(frame_indices[invalid_mask]) or np.any(capture_steps[invalid_mask]): + raise ValueError("Phase-A padding provenance must be canonical zeros") + if np.any(np.asarray(phase_a_time_mask)[invalid_mask]): + raise ValueError("Phase-A padding cannot expose temporal metadata") + for name, mask in ( + ("role_mask", phase_a_role_mask), + ("categorical_mask", phase_a_categorical_mask), + ("evidence_mask", phase_a_evidence_mask), + ): + if np.any(np.asarray(mask) & invalid_mask): + raise ValueError(f"Phase-A {name} cannot mark padding") + + time_mask = np.asarray(phase_a_time_mask) + categorical_mask = np.asarray(phase_a_categorical_mask) + role_mask = np.asarray(phase_a_role_mask) + evidence_mask = np.asarray(phase_a_evidence_mask) + if not np.array_equal(role_mask, evidence_mask): + raise ValueError("Phase-A role mask must equal evidence mask") + if not np.array_equal(categorical_mask, evidence_mask): + raise ValueError("Phase-A categorical mask must equal evidence mask") + if not np.array_equal( + time_mask, + np.repeat(time_mask[..., :1], 3, axis=-1), + ): + raise ValueError("Phase-A time channels must share one token gate") + if np.any(np.asarray(phase_a_time_values)[~time_mask]): + raise ValueError("masked Phase-A time values must be neutral zeros") + if np.any(capture_steps[~np.any(time_mask, axis=-1)]): + raise ValueError("masked Phase-A capture steps must be neutral zeros") + if np.any(np.asarray(phase_a_role_ids)[~role_mask]): + raise ValueError("masked Phase-A role IDs must be neutral zeros") + for name, value in ( + ("event_ids", phase_a_event_ids), + ("event_ordinals", phase_a_event_ordinals), + ("contract_ids", phase_a_contract_ids), + ("status_ids", phase_a_status_ids), + ("confidence", phase_a_confidence), + ): + if np.any(np.asarray(value)[~categorical_mask]): + raise ValueError(f"masked Phase-A {name} must contain neutral zeros") + if np.any(np.asarray(phase_a_role_ids)[evidence_mask] == 0): + raise ValueError("Phase-A evidence tokens require a non-background role") + for name, value in ( + ("event_ids", phase_a_event_ids), + ("event_ordinals", phase_a_event_ordinals), + ("contract_ids", phase_a_contract_ids), + ("status_ids", phase_a_status_ids), + ): + if np.any(np.asarray(value)[evidence_mask] == 0): + raise ValueError(f"Phase-A evidence tokens require nonzero {name}") + + role = self._strict_ids(phase_a_role_ids, 4, "role_ids") + event = self._strict_ids(phase_a_event_ids, self.event_vocab_size, "event_ids") + ordinal = self._strict_ids( + phase_a_event_ordinals, + self.event_ordinal_vocab_size, + "event_ordinals", + ) + contract = self._strict_ids( + phase_a_contract_ids, + self.contract_vocab_size, + "contract_ids", + ) + status = self._strict_ids(phase_a_status_ids, self.status_vocab_size, "status_ids") + + role_gate = phase_a_role_mask[..., None].astype(self.dtype) + categorical_gate = phase_a_categorical_mask[..., None].astype(self.dtype) + categorical = [ + self.role_embed(role) * role_gate, + self.event_embed(event) * categorical_gate, + self.ordinal_embed(ordinal) * categorical_gate, + self.contract_embed(contract) * categorical_gate, + self.status_embed(status) * categorical_gate, + ] + time_mask_f = phase_a_time_mask.astype(self.dtype) + numeric = jnp.concatenate( + [ + phase_a_time_values.astype(self.dtype) * time_mask_f, + phase_a_confidence[..., None].astype(self.dtype) * categorical_gate, + phase_a_evidence_mask[..., None].astype(self.dtype), + time_mask_f, + role_gate, + categorical_gate, + ], + axis=-1, + ) + numeric = self.numeric_out(nnx.silu(self.numeric_in(numeric))) + fused = self.fuse_norm(jnp.concatenate([*categorical, numeric], axis=-1)) + delta = self.out_proj(nnx.silu(self.fuse_in(fused))) + metadata_active = ( + phase_a_role_mask | phase_a_categorical_mask | jnp.any(phase_a_time_mask, axis=-1) + ) & static_mask + output = visual_tokens + jnp.where( + metadata_active[..., None], + delta, + jnp.zeros_like(delta), + ) + stats = { + "phase_a_metadata_active_fraction": jnp.mean(metadata_active.astype(jnp.float32)), + "phase_a_evidence_token_fraction": jnp.mean((phase_a_evidence_mask & static_mask).astype(jnp.float32)), + } + return output, stats + + @staticmethod + def _strict_ids(values: jax.Array, size: int, name: str) -> jax.Array: + values = values.astype(jnp.int32) + if _is_concrete(values): + host = np.asarray(values) + if host.size and (int(host.min()) < 0 or int(host.max()) >= size): + raise ValueError(f"Phase-A {name} must be in [0, {size})") + return jnp.where((values >= 0) & (values < size), values, 0) + + +def _is_concrete(*values: jax.Array) -> bool: + return all(not isinstance(value, jax.core.Tracer) for value in values) + + +__all__ = ["PhaseAMetadataReader"] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/transition_status.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/transition_status.py new file mode 100644 index 0000000000000000000000000000000000000000..bf1c8c18bc14915f9f143e8856fb7346e2768d19 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/models/representation/transition_status.py @@ -0,0 +1,288 @@ +"""Low-cost coarse semantic-transition span head for HistoryPi0. + +The head consumes the 16 executable action-token features and emits two logits: +whether the chunk overlaps a reviewed transition interval, and whether a +positive chunk is the final chunk of that interval. It does not predict an +exact onset token. +""" + +from __future__ import annotations + +from typing import Any + +import flax.nnx as nnx +import jax +import jax.numpy as jnp +import openpi.shared.array_typing as at +from mme_vla_suite.models.representation.utils import kernel_init + +STATUS_EXECUTION_HORIZON = 16 +SEMANTIC_CONTEXT_HORIZON = 48 +ROBOT_VECTOR_DIM = 8 + + +def span_binary_loss( + span_logit: at.Float[at.Array, " b"], + span_target: at.Float[at.Array, " b"], + status_valid: at.Bool[at.Array, " b"], +) -> at.Float[at.Array, " b"]: + """Per-row ``BCEWithLogits`` for the coarse span target.""" + + logits = span_logit.astype(jnp.float32) + target = span_target.astype(jnp.float32) + loss = jax.nn.softplus(logits) - target * logits + return jnp.where(status_valid, loss, 0.0) + + +def last_span_valid_mask( + span_target: at.Float[at.Array, " b"], + last_span_valid: at.Bool[at.Array, " b"], +) -> at.Bool[at.Array, " b"]: + """Rows the conditional endpoint loss actually scores.""" + + return last_span_valid & (span_target.astype(jnp.float32) > 0.5) + + +def valid_row_rescale(valid: at.Bool[at.Array, " b"]) -> at.Float[at.Array, ""]: + """Turn a mean over all rows into a mean over participating rows.""" + + n_valid = jnp.sum(valid.astype(jnp.float32)) + return jnp.asarray(valid.shape[0], jnp.float32) / jnp.maximum(n_valid, 1.0) + + +def last_span_binary_loss( + last_span_logit: at.Float[at.Array, " b"], + last_span_target: at.Float[at.Array, " b"], + span_target: at.Float[at.Array, " b"], + last_span_valid: at.Bool[at.Array, " b"], +) -> at.Float[at.Array, " b"]: + """Conditional endpoint BCE, evaluated only for known positive spans.""" + + logits = last_span_logit.astype(jnp.float32) + target = last_span_target.astype(jnp.float32) + loss = jax.nn.softplus(logits) - target * logits + valid = last_span_valid_mask(span_target, last_span_valid) + return jnp.where(valid, loss, 0.0) + + +def weighted_status_loss_components( + *, + span_loss: at.Float[at.Array, " b"], + last_span_loss: at.Float[at.Array, " b"], + status_valid: at.Bool[at.Array, " b"], + span_target: at.Float[at.Array, " b"], + last_span_valid: at.Bool[at.Array, " b"], + span_loss_weight: float, + last_span_loss_weight: float, +) -> tuple[ + at.Float[at.Array, " b"], + at.Float[at.Array, " b"], + dict[str, at.Array], +]: + """Build the two rescaled Status terms and their effective metrics.""" + + endpoint_valid = last_span_valid_mask(span_target, last_span_valid) + span_rescale = valid_row_rescale(status_valid) + last_span_rescale = valid_row_rescale(endpoint_valid) + span_component = span_loss_weight * span_rescale * span_loss + last_span_component = ( + last_span_loss_weight * last_span_rescale * last_span_loss + ) + span_contribution = jnp.mean(span_component) + last_span_contribution = jnp.mean(last_span_component) + batch_size = jnp.asarray(status_valid.shape[0], dtype=jnp.float32) + status_valid_rows = jnp.sum(status_valid.astype(jnp.float32)) + last_span_valid_rows = jnp.sum(endpoint_valid.astype(jnp.float32)) + metrics = { + "transition_span_loss_weight": jnp.asarray( + span_loss_weight, dtype=jnp.float32 + ), + "transition_last_span_loss_weight": jnp.asarray( + last_span_loss_weight, dtype=jnp.float32 + ), + "transition_span_rescale": span_rescale, + "transition_last_span_rescale": last_span_rescale, + "transition_status_valid_rows": status_valid_rows, + "transition_last_span_valid_rows": last_span_valid_rows, + "transition_status_valid_fraction": status_valid_rows / batch_size, + "transition_last_span_valid_fraction": last_span_valid_rows / batch_size, + "transition_span_loss_contribution": span_contribution, + "transition_last_span_loss_contribution": last_span_contribution, + "transition_status_loss": span_contribution + last_span_contribution, + } + return span_component, last_span_component, metrics + + +class RealizedTransitionContextEncoder(nnx.Module): + """Pool up to 48 causal realized action/state deltas with one query.""" + + def __init__( + self, + *, + action_expert_width: int, + hidden_dim: int = 128, + rngs: nnx.Rngs, + dtype: at.DTypeLike = jnp.float32, + ) -> None: + if action_expert_width <= 0 or hidden_dim <= 0: + raise ValueError("transition context dimensions must be positive") + self.dtype = dtype + self.hidden_dim = hidden_dim + self.row_in = nnx.Linear( + 2 * ROBOT_VECTOR_DIM + 1, + hidden_dim, + rngs=rngs, + dtype=dtype, + kernel_init=kernel_init, + ) + self.row_out = nnx.Linear( + hidden_dim, + hidden_dim, + rngs=rngs, + dtype=dtype, + kernel_init=kernel_init, + ) + self.query = nnx.Param( + jax.random.normal(rngs.params(), (hidden_dim,), dtype=jnp.float32) + / jnp.sqrt(jnp.asarray(hidden_dim, jnp.float32)) + ) + # No bias is important: an all-masked history must be an exact zero + # residual, reproducing the context-free Status Head path. + self.out_proj = nnx.Linear( + hidden_dim, + action_expert_width, + use_bias=False, + rngs=rngs, + dtype=dtype, + kernel_init=kernel_init, + ) + + def __call__( + self, + action_delta: at.Float[at.Array, "b 48 8"], + state_delta: at.Float[at.Array, "b 48 8"], + relative_age: at.Float[at.Array, "b 48"], + valid_mask: at.Bool[at.Array, "b 48"], + ) -> at.Float[at.Array, "b d"]: + expected_rows = action_delta.shape[:2] + if action_delta.shape != (*expected_rows, ROBOT_VECTOR_DIM): + raise ValueError("transition action_delta must end in dimension 8") + if state_delta.shape != action_delta.shape: + raise ValueError("transition state_delta must match action_delta") + if expected_rows[1] != SEMANTIC_CONTEXT_HORIZON: + raise ValueError("transition context must contain exactly 48 rows") + if relative_age.shape != expected_rows or valid_mask.shape != expected_rows: + raise ValueError("transition age/mask shapes must match context rows") + + rows = jnp.concatenate( + [ + action_delta.astype(self.dtype), + state_delta.astype(self.dtype), + relative_age[..., None].astype(self.dtype), + ], + axis=-1, + ) + rows = self.row_out(nnx.silu(self.row_in(rows))) + scores = jnp.einsum( + "btd,d->bt", + rows.astype(jnp.float32), + self.query.value.astype(jnp.float32), + ) / jnp.sqrt(jnp.asarray(self.hidden_dim, jnp.float32)) + mask_f = valid_mask.astype(jnp.float32) + masked_scores = jnp.where(valid_mask, scores, -1e30) + max_score = jnp.max(masked_scores, axis=-1, keepdims=True) + weights = jnp.exp(masked_scores - max_score) * mask_f + weights = weights / jnp.maximum(jnp.sum(weights, axis=-1, keepdims=True), 1e-8) + pooled = jnp.einsum("bt,btd->bd", weights.astype(rows.dtype), rows) + pooled = jnp.where(jnp.any(valid_mask, axis=-1, keepdims=True), pooled, 0.0) + return self.out_proj(pooled) + + +class TransitionStatusHead(nnx.Module): + """Pool executable action features into shared span and final-span logits.""" + + def __init__( + self, + *, + action_expert_width: int, + context_hidden_dim: int = 128, + rngs: nnx.Rngs, + dtype: at.DTypeLike = jnp.float32, + ) -> None: + self.dtype = dtype + self.context = RealizedTransitionContextEncoder( + action_expert_width=action_expert_width, + hidden_dim=context_hidden_dim, + rngs=rngs, + dtype=dtype, + ) + self.span_norm = nnx.LayerNorm(action_expert_width, rngs=rngs, dtype=dtype) + self.status_out = nnx.Linear( + action_expert_width, + 2, + rngs=rngs, + dtype=dtype, + kernel_init=kernel_init, + ) + + def __call__( + self, + action_hidden: at.Float[at.Array, "b 16 d"], + *, + action_delta: at.Float[at.Array, "b 48 8"], + state_delta: at.Float[at.Array, "b 48 8"], + relative_age: at.Float[at.Array, "b 48"], + valid_mask: at.Bool[at.Array, "b 48"], + ) -> tuple[at.Float[at.Array, " b"], at.Float[at.Array, " b"]]: + if action_hidden.shape[1] != STATUS_EXECUTION_HORIZON: + raise ValueError("Status Head requires exactly 16 executable action slots") + context = self.context(action_delta, state_delta, relative_age, valid_mask) + status_action_hidden = jax.lax.stop_gradient(action_hidden) + features = status_action_hidden + context[:, None, :].astype(action_hidden.dtype) + status_features = self.span_norm(jnp.mean(features, axis=1)) + logits = self.status_out(status_features) + return logits[..., 0], logits[..., 1] + + +def transition_training_stats( + *, + span_logit: at.Float[at.Array, " b"], + span_target: at.Float[at.Array, " b"], + status_valid: at.Bool[at.Array, " b"], + span_loss: at.Float[at.Array, " b"], + last_span_logit: at.Float[at.Array, " b"], + last_span_target: at.Float[at.Array, " b"], + last_span_valid: at.Bool[at.Array, " b"], + last_span_loss: at.Float[at.Array, " b"], +) -> dict[str, Any]: + valid_f = status_valid.astype(jnp.float32) + denom = jnp.maximum(jnp.sum(valid_f), 1.0) + endpoint_valid = last_span_valid & (span_target > 0.5) + endpoint_valid_f = endpoint_valid.astype(jnp.float32) + endpoint_denom = jnp.maximum(jnp.sum(endpoint_valid_f), 1.0) + return { + "transition_span_loss": jnp.sum(span_loss * valid_f) / denom, + "transition_span_probability": jnp.sum(jax.nn.sigmoid(span_logit) * valid_f) / denom, + "transition_span_positive_rate": jnp.sum(span_target.astype(jnp.float32) * valid_f) / denom, + "transition_last_span_loss": jnp.sum(last_span_loss * endpoint_valid_f) / endpoint_denom, + "transition_last_span_probability": ( + jnp.sum(jax.nn.sigmoid(last_span_logit) * endpoint_valid_f) / endpoint_denom + ), + "transition_last_span_positive_rate": ( + jnp.sum(last_span_target.astype(jnp.float32) * endpoint_valid_f) / endpoint_denom + ), + } + + +__all__ = [ + "ROBOT_VECTOR_DIM", + "SEMANTIC_CONTEXT_HORIZON", + "STATUS_EXECUTION_HORIZON", + "RealizedTransitionContextEncoder", + "TransitionStatusHead", + "last_span_binary_loss", + "span_binary_loss", + "transition_training_stats", + "valid_row_rescale", + "weighted_status_loss_components", +] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/picmem_phase_a_rollout.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/picmem_phase_a_rollout.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0de69224665d67bd9ecce533c32b483f8b864c --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/picmem_phase_a_rollout.py @@ -0,0 +1,563 @@ +"""Fail-closed Phase-A runtime controller for RoboMME policy serving. + +The simulator and policy run in different processes during the standard +RoboMME evaluation. The simulator therefore sends one identity-bound reset +and a stream of event envelopes through the existing ``add_buffer`` request. +This module is the policy-side authority for that wire. It owns no task +semantics: it validates the transport, applies every event through +``RuntimeReadSession.ingest_event``, and materializes the resulting evolving +read through the exact host ``MemoryBuffer`` before ``model.sample_actions``. + +There is deliberately no legacy frame-sampling fallback once a Phase-A model +is loaded. A missing reset, a manager-mode mismatch, an event ahead of the +buffered visual history, or an incomplete 32-frame/512-token materialization +all fail the action request. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from copy import deepcopy +from dataclasses import dataclass, field +from typing import Any, TypedDict + +import numpy as np +from mme_vla_suite.training.picmem_phase_a_reader import ( + FACTOR_FIELDS, + FRAME_BUDGET, + OBSERVATION_FIELDS, + TOKEN_BUDGET, + PhaseAFactors, +) +from mme_vla_suite.training.picmem_phase_a_runtime import ( + RuntimePhaseAObservation, + materialize_runtime_observation, +) + +from picmem.memory.contracts import SelectionMode +from picmem.provenance.runtime_reader import ( + RuntimeReadError, + RuntimeReadSession, + canonical_json_sha256, +) + +RUNTIME_BATCH_SCHEMA_VERSION = "picmem_phase_a_rollout_batch_v2" +RUNTIME_BATCH_ACK_SCHEMA_VERSION = "picmem_phase_a_rollout_batch_ack_v1" +RUNTIME_START_SCHEMA_VERSION = "picmem_phase_a_rollout_start_v1" +RUNTIME_ENVELOPE_SCHEMA_VERSION = "picmem_phase_a_rollout_event_envelope_v1" +GENESIS_BATCH_SHA256 = "0" * 64 + +_BATCH_FIELDS = frozenset( + { + "schema_version", + "batch_sequence", + "previous_batch_sha256", + "batch_sha256", + "start", + "events", + } +) +_BATCH_HASH_FIELDS = ( + "schema_version", + "batch_sequence", + "previous_batch_sha256", + "start", + "events", +) +_START_FIELDS = frozenset( + { + "schema_version", + "reset", + "expected_identity_sha256", + "expected_source_identity_sha256", + "expected_source_contract_sha256", + "manager_mode", + "metadata_seed", + } +) +_ENVELOPE_FIELDS = frozenset({"schema_version", "event", "observed_source_state"}) + + +@dataclass(frozen=True, slots=True) +class PhaseARolloutMaterialization: + """One policy-visible runtime observation and its model input fields.""" + + runtime: RuntimePhaseAObservation + model_inputs: Mapping[str, np.ndarray] + + +class PhaseARolloutBatchAck(TypedDict): + """Strict policy-server acknowledgement for one committed batch.""" + + schema_version: str + batch_sequence: int + batch_sha256: str + duplicate: bool + runtime_receipt: dict[str, Any] + + +@dataclass(frozen=True, slots=True) +class PhaseARolloutPreparedBatch: + """Opaque one-shot result of validating a prospective host append.""" + + batch_sequence: int + batch_sha256: str + duplicate: bool + _controller_token: object = field(repr=False, compare=False) + _preparation_token: object = field(repr=False, compare=False) + + +@dataclass(frozen=True, slots=True) +class _PreparedState: + prepared: PhaseARolloutPreparedBatch + base_session: RuntimeReadSession | None + base_receipt_sha256: str | None + base_batch_sequence: int | None + base_batch_sha256: str | None + candidate_session: RuntimeReadSession | None + + +class PhaseARolloutController: + """Bind one formal Phase-A config to one live RoboMME episode at a time.""" + + def __init__(self, *, factors: PhaseAFactors, metadata_seed: int) -> None: + if type(factors) is not PhaseAFactors: + raise RuntimeReadError("rollout controller requires the exact PhaseAFactors class") + # Online mutation plans for non-relevant selectors are not frozen. The + # runtime bridge must never silently turn those arms into relevant. + factors.validate_implemented_path(selection_applied=SelectionMode.RELEVANT) + self._factors = factors + self._metadata_seed = _nat(metadata_seed, "metadata_seed") + self._session: RuntimeReadSession | None = None + self._last_batch_sequence: int | None = None + self._last_batch_sha256: str | None = None + self._controller_token = object() + self._prepared_state: _PreparedState | None = None + + @property + def factors(self) -> PhaseAFactors: + return self._factors + + @property + def metadata_seed(self) -> int: + return self._metadata_seed + + @property + def session(self) -> RuntimeReadSession | None: + return self._session + + @property + def last_batch_sequence(self) -> int | None: + return self._last_batch_sequence + + @property + def last_batch_sha256(self) -> str | None: + return self._last_batch_sha256 + + def reset(self) -> None: + """Drop all episode state when the outer policy receives ``reset``.""" + + self._session = None + self._last_batch_sequence = None + self._last_batch_sha256 = None + self._prepared_state = None + + def accept_add_buffer_payload( + self, + raw: Any, + *, + buffered_step: int, + ) -> PhaseARolloutBatchAck: + """Validate and immediately commit one batch without a host transaction. + + Production serving should use :meth:`prepare_add_buffer_payload`, + append the host ``MemoryBuffer`` only for a non-duplicate preparation, + and then call :meth:`commit_prepared_batch`. This convenience method + remains useful when no separate host mutation is part of the call. + """ + + prepared = self.prepare_add_buffer_payload( + raw, + prospective_buffered_step=buffered_step, + ) + return self.commit_prepared_batch(prepared) + + def prepare_add_buffer_payload( + self, + raw: Any, + *, + prospective_buffered_step: int, + ) -> PhaseARolloutPreparedBatch: + """Validate one batch against a prospective buffer append. + + ``prospective_buffered_step`` is the highest step that will exist only + after the host append succeeds. This method never publishes a + session or advances the batch-chain cursor. Instead it returns one + opaque, one-shot preparation that can be committed after the host + mutation succeeds. Exact retries are marked ``duplicate`` so the + host must skip appending the same visual history a second time. + + All start and event work happens on an unpublished candidate session, + so a bad later event cannot leave an earlier event partially accepted. + """ + + prospective_buffered_step = _nat( + prospective_buffered_step, + "prospective_buffered_step", + ) + batch = _exact_mapping(raw, _BATCH_FIELDS, "Phase-A rollout batch") + if batch["schema_version"] != RUNTIME_BATCH_SCHEMA_VERSION: + raise RuntimeReadError("Phase-A rollout batch schema_version mismatch") + + batch_sequence = _nat(batch["batch_sequence"], "batch_sequence") + previous_batch_sha256 = _sha256( + batch["previous_batch_sha256"], + "previous_batch_sha256", + ) + batch_sha256 = _sha256(batch["batch_sha256"], "batch_sha256") + batch_payload = {name: batch[name] for name in _BATCH_HASH_FIELDS} + if canonical_json_sha256(batch_payload) != batch_sha256: + raise RuntimeReadError("Phase-A rollout batch_sha256 mismatch") + + if self._last_batch_sequence is not None and batch_sequence == self._last_batch_sequence: + if batch_sha256 != self._last_batch_sha256: + raise RuntimeReadError("Phase-A rollout batch retry hash mismatch") + return self._issue_prepared( + batch_sequence=batch_sequence, + batch_sha256=batch_sha256, + duplicate=True, + candidate_session=None, + ) + + if self._last_batch_sequence is None: + if batch_sequence != 0: + raise RuntimeReadError("first Phase-A rollout batch_sequence must be zero") + if previous_batch_sha256 != GENESIS_BATCH_SHA256: + raise RuntimeReadError("first Phase-A rollout batch must name the genesis hash") + if batch["start"] is None: + raise RuntimeReadError("first Phase-A rollout batch requires a runtime start") + else: + if batch_sequence != self._last_batch_sequence + 1: + raise RuntimeReadError("Phase-A rollout batch_sequence must be contiguous") + if previous_batch_sha256 != self._last_batch_sha256: + raise RuntimeReadError("Phase-A rollout previous_batch_sha256 mismatch") + + start = batch["start"] + if start is not None: + if self._session is not None: + raise RuntimeReadError("Phase-A rollout session was already started") + candidate = self._start_session(start) + if candidate.current_step > prospective_buffered_step: + raise RuntimeReadError("Phase-A runtime start is ahead of buffered visual history") + elif self._session is None: + raise RuntimeReadError("Phase-A add_buffer arrived before an identity-bound runtime start") + else: + candidate = deepcopy(self._session) + + events = batch["events"] + if not isinstance(events, Sequence) or isinstance(events, (str, bytes)): + raise RuntimeReadError("Phase-A rollout events must be a sequence") + assert candidate is not None + for index, raw_envelope in enumerate(events): + envelope = _exact_mapping( + raw_envelope, + _ENVELOPE_FIELDS, + f"Phase-A rollout event envelope[{index}]", + ) + if envelope["schema_version"] != RUNTIME_ENVELOPE_SCHEMA_VERSION: + raise RuntimeReadError("Phase-A rollout event envelope schema_version mismatch") + event = envelope["event"] + if not isinstance(event, Mapping): + raise RuntimeReadError("Phase-A rollout envelope event must be a mapping") + runtime_step = _nat(event.get("runtime_step"), "event.runtime_step") + if runtime_step > prospective_buffered_step: + raise RuntimeReadError("Phase-A runtime event is ahead of buffered visual history") + candidate.ingest_event( + event, + observed_source_state=deepcopy(envelope["observed_source_state"]), + ) + if candidate.current_step > prospective_buffered_step: + raise RuntimeReadError("Phase-A runtime session advanced beyond buffered visual history") + + return self._issue_prepared( + batch_sequence=batch_sequence, + batch_sha256=batch_sha256, + duplicate=False, + candidate_session=candidate, + ) + + def commit_prepared_batch( + self, + prepared: PhaseARolloutPreparedBatch, + ) -> PhaseARolloutBatchAck: + """Publish one current preparation after the host append succeeds.""" + + if type(prepared) is not PhaseARolloutPreparedBatch: + raise RuntimeReadError("prepared rollout batch has the wrong type") + state = self._prepared_state + if ( + state is None + or prepared._controller_token is not self._controller_token + or prepared._preparation_token is not state.prepared._preparation_token + or prepared.batch_sequence != state.prepared.batch_sequence + or prepared.batch_sha256 != state.prepared.batch_sha256 + or prepared.duplicate is not state.prepared.duplicate + ): + raise RuntimeReadError("prepared rollout batch is stale, foreign, or already consumed") + + # A commit attempt consumes the preparation even when its base has + # drifted. Retrying an ambiguous host transaction must re-prepare + # from the current controller state rather than reuse an old token. + self._prepared_state = None + if ( + self._session is not state.base_session + or self._last_batch_sequence != state.base_batch_sequence + or self._last_batch_sha256 != state.base_batch_sha256 + or self._session_receipt_sha256(self._session) != state.base_receipt_sha256 + ): + raise RuntimeReadError("prepared rollout batch base state drifted before commit") + + if prepared.duplicate: + if state.candidate_session is not None: + raise RuntimeReadError("duplicate rollout preparation unexpectedly has a candidate") + else: + if state.candidate_session is None: + raise RuntimeReadError("new rollout preparation has no candidate session") + self._session = state.candidate_session + self._last_batch_sequence = prepared.batch_sequence + self._last_batch_sha256 = prepared.batch_sha256 + + return self._ack( + batch_sequence=prepared.batch_sequence, + batch_sha256=prepared.batch_sha256, + duplicate=prepared.duplicate, + ) + + def materialize_for_action( + self, + memory_buffer: Any, + *, + step: int, + normalize_state: Callable[[np.ndarray], Any], + ) -> PhaseARolloutMaterialization: + """Materialize evolving memory immediately before action sampling.""" + + step = _nat(step, "step") + if self._session is None: + raise RuntimeReadError("Phase-A action request has no identity-bound runtime session") + if not callable(normalize_state): + raise RuntimeReadError("Phase-A rollout requires the host state normalizer") + runtime = materialize_runtime_observation( + self._session, + memory_buffer, + step=step, + factors=self._factors, + metadata_seed=self._metadata_seed, + ) + if runtime.plan.frame_indices.shape != (FRAME_BUDGET,): + raise RuntimeReadError("Phase-A rollout frame budget drift") + if runtime.image.shape[0] != TOKEN_BUDGET or runtime.mask.shape != (TOKEN_BUDGET,): + raise RuntimeReadError("Phase-A rollout token budget drift") + + normalized_state = np.asarray(normalize_state(runtime.state)) + if normalized_state.shape != runtime.state.shape: + raise RuntimeReadError("Phase-A rollout normalized state geometry drift") + if normalized_state.dtype != np.float32: + raise RuntimeReadError("Phase-A rollout normalized state must be float32") + if not bool(np.isfinite(normalized_state).all()): + raise RuntimeReadError("Phase-A rollout normalized state must be finite") + normalized_state.setflags(write=False) + + model_inputs: dict[str, np.ndarray] = { + "static_image_emb": runtime.image, + "static_pos_emb": runtime.position, + "static_state_emb": normalized_state, + "static_mask": runtime.mask, + **runtime.metadata.to_observation(), + } + expected = { + "static_image_emb", + "static_pos_emb", + "static_state_emb", + "static_mask", + *OBSERVATION_FIELDS, + } + if set(model_inputs) != expected: + raise RuntimeReadError("Phase-A rollout model input fields drifted") + return PhaseARolloutMaterialization(runtime=runtime, model_inputs=model_inputs) + + def receipt(self) -> dict[str, Any]: + if self._session is None: + raise RuntimeReadError("Phase-A rollout has no session receipt") + receipt = self._session.receipt() + if receipt.get("manager_mode") != self._factors.manager_mode.value: + raise RuntimeReadError("Phase-A rollout receipt manager_mode drift") + return receipt + + def _start_session(self, raw: Any) -> RuntimeReadSession: + start = _exact_mapping(raw, _START_FIELDS, "Phase-A rollout start") + if start["schema_version"] != RUNTIME_START_SCHEMA_VERSION: + raise RuntimeReadError("Phase-A rollout start schema_version mismatch") + if start["manager_mode"] != self._factors.manager_mode.value: + raise RuntimeReadError("Phase-A rollout start manager_mode differs from the loaded policy config") + if _nat(start["metadata_seed"], "start.metadata_seed") != self._metadata_seed: + raise RuntimeReadError("Phase-A rollout start metadata_seed differs from policy config") + return RuntimeReadSession.from_reset( + start["reset"], + expected_identity_sha256=_sha256( + start["expected_identity_sha256"], + "expected_identity_sha256", + ), + expected_source_identity_sha256=_sha256( + start["expected_source_identity_sha256"], + "expected_source_identity_sha256", + ), + expected_source_contract_sha256=_sha256( + start["expected_source_contract_sha256"], + "expected_source_contract_sha256", + ), + manager_mode=self._factors.manager_mode, + ) + + def _ack( + self, + *, + batch_sequence: int, + batch_sha256: str, + duplicate: bool, + ) -> PhaseARolloutBatchAck: + return { + "schema_version": RUNTIME_BATCH_ACK_SCHEMA_VERSION, + "batch_sequence": batch_sequence, + "batch_sha256": batch_sha256, + "duplicate": duplicate, + "runtime_receipt": self.receipt(), + } + + def _issue_prepared( + self, + *, + batch_sequence: int, + batch_sha256: str, + duplicate: bool, + candidate_session: RuntimeReadSession | None, + ) -> PhaseARolloutPreparedBatch: + preparation_token = object() + prepared = PhaseARolloutPreparedBatch( + batch_sequence=batch_sequence, + batch_sha256=batch_sha256, + duplicate=duplicate, + _controller_token=self._controller_token, + _preparation_token=preparation_token, + ) + self._prepared_state = _PreparedState( + prepared=prepared, + base_session=self._session, + base_receipt_sha256=self._session_receipt_sha256(self._session), + base_batch_sequence=self._last_batch_sequence, + base_batch_sha256=self._last_batch_sha256, + candidate_session=candidate_session, + ) + return prepared + + @staticmethod + def _session_receipt_sha256(session: RuntimeReadSession | None) -> str | None: + if session is None: + return None + value = session.receipt().get("receipt_sha256") + return _sha256(value, "runtime receipt_sha256") + + +def controller_from_history_config(history_config: Any) -> PhaseARolloutController | None: + """Create the controller iff the loaded model is exactly Phase-A. + + OmegaConf nodes and plain mappings both provide ``get``. Any malformed + Phase-A declaration fails instead of returning ``None`` and re-enabling + legacy FrameSamp. + """ + + if history_config is None: + return None + perceptual = _optional_config_get(history_config, "perceptual_memory") + if perceptual is None: + return None + frame_selection = _optional_config_get(perceptual, "frame_selection") + if frame_selection is None: + return None + if _optional_config_get(frame_selection, "type") != "picmem_phase_a": + return None + if _config_get(history_config, "representation_type") != "perceptual": + raise RuntimeReadError("picmem_phase_a rollout requires perceptual representation") + if _config_get(perceptual, "type") != "frame_sampling": + raise RuntimeReadError("picmem_phase_a rollout requires frame_sampling host memory") + geometry = ( + int(_config_get(history_config, "budget")), + int(_config_get(history_config, "token_per_image")), + int(_config_get(history_config, "num_views")), + int(_config_get(frame_selection, "frame_budget")), + int(_config_get(frame_selection, "recent_anchor_count")), + ) + if geometry != (TOKEN_BUDGET, 16, 1, FRAME_BUDGET, 4): + raise RuntimeReadError("picmem_phase_a rollout requires 32 frames and exactly 512 visual tokens") + factors = PhaseAFactors.from_mapping( + {name: _config_get(frame_selection, name) for name in FACTOR_FIELDS}, + require_explicit=True, + ) + return PhaseARolloutController( + factors=factors, + metadata_seed=_config_get(frame_selection, "metadata_seed"), + ) + + +def _config_get(value: Any, name: str) -> Any: + result = _optional_config_get(value, name) + if result is None: + raise RuntimeReadError(f"Phase-A config is missing {name!r}") + return result + + +def _optional_config_get(value: Any, name: str) -> Any: + getter = getattr(value, "get", None) + if not callable(getter): + raise RuntimeReadError(f"Phase-A config node {name!r} is not mapping-like") + return getter(name) + + +def _exact_mapping(raw: Any, fields: frozenset[str], name: str) -> dict[str, Any]: + if not isinstance(raw, Mapping): + raise RuntimeReadError(f"{name} must be a mapping") + missing = fields - set(raw) + unknown = set(raw) - fields + if missing or unknown: + raise RuntimeReadError(f"{name} fields mismatch; missing={sorted(missing)}, unknown={sorted(unknown)}") + return dict(raw) + + +def _nat(value: Any, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) < 0: + raise RuntimeReadError(f"{name} must be a non-negative integer") + return int(value) + + +def _sha256(value: Any, name: str) -> str: + if ( + not isinstance(value, str) + or len(value) != 64 + or any(character not in "0123456789abcdef" for character in value) + ): + raise RuntimeReadError(f"{name} must be lowercase SHA-256") + return value + + +__all__ = [ + "GENESIS_BATCH_SHA256", + "RUNTIME_BATCH_ACK_SCHEMA_VERSION", + "RUNTIME_BATCH_SCHEMA_VERSION", + "RUNTIME_ENVELOPE_SCHEMA_VERSION", + "RUNTIME_START_SCHEMA_VERSION", + "PhaseARolloutBatchAck", + "PhaseARolloutController", + "PhaseARolloutMaterialization", + "PhaseARolloutPreparedBatch", + "controller_from_history_config", +] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/semantic_transition_runtime.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/semantic_transition_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..a23c5a3a1bc9254f4e2d634b1470ca7f81fbfe72 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/policies/semantic_transition_runtime.py @@ -0,0 +1,1236 @@ +"""Thin RoboMME rollout facade for semantic-transition status and memory updates. + +The adapter owns episode-local state in the evaluator process. It keeps the +policy server stateless, records only the prefix that actually executes, and +delegates semantic-window, evidence, writer, and task-context semantics to the +PIC-Mem runtime contracts. + +No simulator-private state enters this API. The only observation inputs are +the normal front/wrist images and the observable eight-value robot state that +the policy already consumes. +""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass, field +from typing import Any + +import numpy as np + +try: + from picmem.runtime.grounded_writer import ( + GroundedWriterRequest, + ValidatedWriterResult, + WriterDecision, + WriterRequestPurpose, + ) + from picmem.runtime.online_stage4 import ( + OnlineStage4MemoryReference, + OnlineStage4MemoryStore, + OnlineStage4ValidatedWriterResult, + OnlineStage4WriterRequest, + ) + from picmem.runtime.semantic_evidence import ( + RealizedObservation, + sample_uniform_observations, + ) + from picmem.runtime.semantic_window import ( + ChunkIngestResult, + ChunkTransitionStatus, + SemanticWindowController, + SemanticWindowPhase, + SemanticWindowState, + WindowResolution, + ) + from picmem.runtime.task_context import ( + OriginalTaskAnchor, + RenderedPolicyPrompt, + TaskContextCommit, + TaskContextStore, + ) +except ImportError as exc: # pragma: no cover - exercised only in an incorrectly installed host. + raise ImportError( + "RoboMME semantic-transition rollout requires the PIC-Mem runtime package" + ) from exc + + +STATUS_HORIZON = 16 +CONTEXT_HORIZON = 48 +ROBOT_VECTOR_DIM = 8 + + +class SemanticTransitionRolloutError(ValueError): + """The host called the rollout adapter out of order or with invalid data.""" + + +def _nonempty(value: object, field_name: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise SemanticTransitionRolloutError(f"{field_name} must be a non-empty string") + return value + + +def _natural(value: object, field_name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise SemanticTransitionRolloutError(f"{field_name} must be a non-negative integer") + return value + + +def _readonly_float32(value: Any, *, shape: tuple[int, ...], field_name: str) -> np.ndarray: + try: + result = np.asarray(value, dtype=np.float32) + except (TypeError, ValueError) as exc: + raise SemanticTransitionRolloutError(f"{field_name} must be a numeric array") from exc + if result.shape != shape: + raise SemanticTransitionRolloutError(f"{field_name} must have shape {shape}") + if not np.isfinite(result).all(): + raise SemanticTransitionRolloutError(f"{field_name} must contain only finite values") + result = np.array(result, dtype=np.float32, copy=True) + result.flags.writeable = False + return result + + +def _readonly_bool(value: Any, *, shape: tuple[int, ...], field_name: str) -> np.ndarray: + result = np.asarray(value) + if result.dtype != np.bool_ or result.shape != shape: + raise SemanticTransitionRolloutError(f"{field_name} must be a boolean array with shape {shape}") + result = np.array(result, dtype=np.bool_, copy=True) + result.flags.writeable = False + return result + + +@dataclass(frozen=True, slots=True) +class SemanticPolicyRequest: + """Prompt plus the cheap causal context supplied to one policy call.""" + + step: int + observation_id: str + rendered_prompt: RenderedPolicyPrompt + transition_context_action_delta: np.ndarray = field(repr=False, compare=False) + transition_context_state_delta: np.ndarray = field(repr=False, compare=False) + transition_context_relative_age: np.ndarray = field(repr=False, compare=False) + transition_context_valid_mask: np.ndarray = field(repr=False, compare=False) + history_required_indices: tuple[int, ...] = () + + def __post_init__(self) -> None: + _natural(self.step, "step") + _nonempty(self.observation_id, "observation_id") + if not isinstance(self.rendered_prompt, RenderedPolicyPrompt): + raise TypeError("rendered_prompt must be RenderedPolicyPrompt") + object.__setattr__( + self, + "transition_context_action_delta", + _readonly_float32( + self.transition_context_action_delta, + shape=(CONTEXT_HORIZON, ROBOT_VECTOR_DIM), + field_name="transition_context_action_delta", + ), + ) + object.__setattr__( + self, + "transition_context_state_delta", + _readonly_float32( + self.transition_context_state_delta, + shape=(CONTEXT_HORIZON, ROBOT_VECTOR_DIM), + field_name="transition_context_state_delta", + ), + ) + object.__setattr__( + self, + "transition_context_relative_age", + _readonly_float32( + self.transition_context_relative_age, + shape=(CONTEXT_HORIZON,), + field_name="transition_context_relative_age", + ), + ) + object.__setattr__( + self, + "transition_context_valid_mask", + _readonly_bool( + self.transition_context_valid_mask, + shape=(CONTEXT_HORIZON,), + field_name="transition_context_valid_mask", + ), + ) + history_required_indices = tuple(self.history_required_indices) + if any( + isinstance(index, bool) or not isinstance(index, int) or index < 0 + for index in history_required_indices + ): + raise SemanticTransitionRolloutError( + "history_required_indices must contain non-negative integers" + ) + if ( + len(set(history_required_indices)) != len(history_required_indices) + or history_required_indices != tuple(sorted(history_required_indices)) + ): + raise SemanticTransitionRolloutError( + "history_required_indices must be unique and sorted" + ) + object.__setattr__(self, "history_required_indices", history_required_indices) + + @property + def prompt(self) -> str: + return self.rendered_prompt.text + + def transition_model_inputs(self) -> dict[str, np.ndarray]: + """Return unbatched arrays using the Status Head's public input names.""" + + return { + "transition_context_action_delta": self.transition_context_action_delta, + "transition_context_state_delta": self.transition_context_state_delta, + "transition_context_relative_age": self.transition_context_relative_age, + "transition_context_valid_mask": self.transition_context_valid_mask, + } + + +@dataclass(frozen=True, slots=True) +class OnlineStage4PolicyRequest: + """One policy call with the same task/memory channels used during training.""" + + step: int + observation_id: str + prompt: str + static_semantic_memory: str + memory_revision: int + transition_context_action_delta: np.ndarray = field(repr=False, compare=False) + transition_context_state_delta: np.ndarray = field(repr=False, compare=False) + transition_context_relative_age: np.ndarray = field(repr=False, compare=False) + transition_context_valid_mask: np.ndarray = field(repr=False, compare=False) + history_required_indices: tuple[int, ...] = () + + def __post_init__(self) -> None: + _natural(self.step, "step") + _nonempty(self.observation_id, "observation_id") + _nonempty(self.prompt, "prompt") + _nonempty(self.static_semantic_memory, "static_semantic_memory") + _natural(self.memory_revision, "memory_revision") + object.__setattr__( + self, + "transition_context_action_delta", + _readonly_float32( + self.transition_context_action_delta, + shape=(CONTEXT_HORIZON, ROBOT_VECTOR_DIM), + field_name="transition_context_action_delta", + ), + ) + object.__setattr__( + self, + "transition_context_state_delta", + _readonly_float32( + self.transition_context_state_delta, + shape=(CONTEXT_HORIZON, ROBOT_VECTOR_DIM), + field_name="transition_context_state_delta", + ), + ) + object.__setattr__( + self, + "transition_context_relative_age", + _readonly_float32( + self.transition_context_relative_age, + shape=(CONTEXT_HORIZON,), + field_name="transition_context_relative_age", + ), + ) + object.__setattr__( + self, + "transition_context_valid_mask", + _readonly_bool( + self.transition_context_valid_mask, + shape=(CONTEXT_HORIZON,), + field_name="transition_context_valid_mask", + ), + ) + required = tuple(self.history_required_indices) + if any( + isinstance(index, bool) or not isinstance(index, int) or index < 0 + for index in required + ): + raise SemanticTransitionRolloutError( + "history_required_indices must contain non-negative integers" + ) + if required != tuple(sorted(set(required))): + raise SemanticTransitionRolloutError( + "history_required_indices must be unique and sorted" + ) + object.__setattr__(self, "history_required_indices", required) + + def transition_model_inputs(self) -> dict[str, np.ndarray]: + return { + "transition_context_action_delta": self.transition_context_action_delta, + "transition_context_state_delta": self.transition_context_state_delta, + "transition_context_relative_age": self.transition_context_relative_age, + "transition_context_valid_mask": self.transition_context_valid_mask, + } + + +@dataclass(frozen=True, slots=True) +class RealizedRobotDelta: + """One actually executed action and its resulting observable state delta.""" + + step: int + action_delta: np.ndarray = field(repr=False, compare=False) + state_delta: np.ndarray = field(repr=False, compare=False) + + def __post_init__(self) -> None: + _natural(self.step, "step") + object.__setattr__( + self, + "action_delta", + _readonly_float32( + self.action_delta, + shape=(ROBOT_VECTOR_DIM,), + field_name="action_delta", + ), + ) + object.__setattr__( + self, + "state_delta", + _readonly_float32( + self.state_delta, + shape=(ROBOT_VECTOR_DIM,), + field_name="state_delta", + ), + ) + + +class RealizedTransitionContext: + """Causal Status-Head inputs built only from actions executed in the simulator.""" + + def __init__(self, *, initial_step: int, initial_state: Any) -> None: + self._current_step = _natural(initial_step, "initial_step") + self._current_state = _readonly_float32( + initial_state, + shape=(ROBOT_VECTOR_DIM,), + field_name="initial_state", + ) + self._history: deque[RealizedRobotDelta] = deque(maxlen=CONTEXT_HORIZON) + + @property + def history(self) -> tuple[RealizedRobotDelta, ...]: + return tuple(self._history) + + def record( + self, + *, + step: int, + action: Any, + resulting_state: Any, + ) -> RealizedRobotDelta: + step = _natural(step, "step") + if step != self._current_step + 1: + raise SemanticTransitionRolloutError( + f"realized context steps must be contiguous; expected {self._current_step + 1}, got {step}" + ) + executed_action = _readonly_float32( + action, + shape=(ROBOT_VECTOR_DIM,), + field_name="action", + ) + post_state = _readonly_float32( + resulting_state, + shape=(ROBOT_VECTOR_DIM,), + field_name="resulting_state", + ) + action_delta = np.empty(ROBOT_VECTOR_DIM, dtype=np.float32) + action_delta[:7] = executed_action[:7] - self._current_state[:7] + action_delta[7] = executed_action[7] + realized = RealizedRobotDelta( + step=step, + action_delta=action_delta, + state_delta=post_state - self._current_state, + ) + self._history.append(realized) + self._current_step = step + self._current_state = post_state + return realized + + def model_inputs(self) -> dict[str, np.ndarray]: + action_delta = np.zeros((CONTEXT_HORIZON, ROBOT_VECTOR_DIM), dtype=np.float32) + state_delta = np.zeros((CONTEXT_HORIZON, ROBOT_VECTOR_DIM), dtype=np.float32) + relative_age = np.zeros(CONTEXT_HORIZON, dtype=np.float32) + valid_mask = np.zeros(CONTEXT_HORIZON, dtype=np.bool_) + history = tuple(self._history) + left_padding = CONTEXT_HORIZON - len(history) + for index, item in enumerate(history): + row = left_padding + index + action_delta[row] = item.action_delta + state_delta[row] = item.state_delta + relative_age[row] = (len(history) - index) / CONTEXT_HORIZON + valid_mask[row] = True + return { + "transition_context_action_delta": action_delta, + "transition_context_state_delta": state_delta, + "transition_context_relative_age": relative_age, + "transition_context_valid_mask": valid_mask, + } + + +@dataclass(frozen=True, slots=True) +class WriterApplication: + """One locally validated writer result applied at a chunk boundary.""" + + request_id: str + decision: WriterDecision + context_commit: TaskContextCommit | None + window_resolution_applied: bool + rendered_prompt: RenderedPolicyPrompt + + +@dataclass(frozen=True, slots=True) +class OnlineStage4WriterApplication: + """One operation resolved at a boundary, with the resulting policy memory.""" + + request_id: str + operation: str + memory_committed: bool + memory_before_revision: int + memory_after_revision: int + window_resolution_applied: bool + static_semantic_memory: str + history_required_indices: tuple[int, ...] + + +@dataclass(slots=True) +class _PendingActionChunk: + chunk_id: str + start_step: int + executable_actions: np.ndarray + executed_count: int = 0 + + +class SemanticTransitionRolloutAdapter: + """Episode-local bridge from RoboMME rollout calls to PIC-Mem runtime state.""" + + def __init__( + self, + *, + episode_nonce: str, + original_instruction: str, + initial_step: int, + initial_state: Any, + initial_front_image: Any, + initial_wrist_image: Any | None = None, + initial_observation_id: str | None = None, + initial_subgoal: str | None = None, + confirmation_tail: int = 4, + span_threshold: float = 0.5, + last_span_threshold: float = 0.5, + cooldown_chunks: int = 1, + ) -> None: + nonce = _nonempty(episode_nonce, "episode_nonce") + step = _natural(initial_step, "initial_step") + anchor = OriginalTaskAnchor(original_instruction) + self._task_context = TaskContextStore(anchor, active_subgoal=initial_subgoal) + self._window = SemanticWindowController( + nonce, + status_horizon=STATUS_HORIZON, + max_realized_steps=CONTEXT_HORIZON, + confirmation_tail=confirmation_tail, + span_threshold=span_threshold, + last_span_threshold=last_span_threshold, + cooldown_chunks=cooldown_chunks, + ) + initial_robot_state = _readonly_float32( + initial_state, + shape=(ROBOT_VECTOR_DIM,), + field_name="initial_state", + ) + self._realized_context = RealizedTransitionContext( + initial_step=step, + initial_state=initial_robot_state, + ) + self._current_observation = RealizedObservation( + observation_id=( + initial_observation_id + if initial_observation_id is not None + else f"{nonce}:observation:{step}" + ), + step=step, + front_image=initial_front_image, + wrist_image=initial_wrist_image, + robot_state=initial_robot_state, + ) + self._awaiting_policy_response: SemanticPolicyRequest | None = None + self._pending_chunk: _PendingActionChunk | None = None + self._preempted_chunk_result: ChunkIngestResult | None = None + self._writer_request: GroundedWriterRequest | None = None + self._writer_applications: dict[ + str, + tuple[ValidatedWriterResult, bool, WriterApplication], + ] = {} + self._initial_writer_prepared = False + self._history_required_indices: tuple[int, ...] = () + + @property + def original_task(self) -> OriginalTaskAnchor: + return self._task_context.anchor + + @property + def rendered_prompt(self) -> RenderedPolicyPrompt: + return self._task_context.render() + + @property + def current_step(self) -> int: + return self._current_observation.step + + @property + def phase(self) -> SemanticWindowPhase: + return self._window.phase + + @property + def history(self) -> tuple[RealizedRobotDelta, ...]: + return self._realized_context.history + + @property + def pending_chunk_id(self) -> str | None: + return self._pending_chunk.chunk_id if self._pending_chunk is not None else None + + @property + def preempted_chunk_result(self) -> ChunkIngestResult | None: + """Return the latest proposal canceled before action execution, if any.""" + + return self._preempted_chunk_result + + def prepare_policy_request(self) -> SemanticPolicyRequest: + """Open one policy call with the immutable anchor plus current context.""" + + if self._awaiting_policy_response is not None: + raise SemanticTransitionRolloutError("a policy response is already pending") + if self._pending_chunk is not None: + raise SemanticTransitionRolloutError("finish the current action chunk before the next policy call") + if self._window.ready_window is not None or self._writer_request is not None: + raise SemanticTransitionRolloutError("resolve the writer-ready window before the next policy call") + transition_context = self._realized_context.model_inputs() + request = SemanticPolicyRequest( + step=self.current_step, + observation_id=self._current_observation.observation_id, + rendered_prompt=self.rendered_prompt, + history_required_indices=self._history_required_indices, + **transition_context, + ) + self._awaiting_policy_response = request + return request + + def prepare_initial_writer_request( + self, + *, + front_images: tuple[Any, ...] | list[Any], + wrist_images: tuple[Any | None, ...] | list[Any | None], + ) -> GroundedWriterRequest: + """Build one pre-action request from demonstration history plus execution start.""" + + if self._initial_writer_prepared: + raise SemanticTransitionRolloutError("initial writer request was already prepared") + if ( + self._awaiting_policy_response is not None + or self._pending_chunk is not None + or self._writer_request is not None + or self._window.phase is not SemanticWindowPhase.CLOSED + or self._realized_context.history + ): + raise SemanticTransitionRolloutError( + "initial writer request must precede every policy call and executed action" + ) + fronts = tuple(front_images) + wrists = tuple(wrist_images) + if len(fronts) < 2 or len(fronts) != len(wrists): + raise SemanticTransitionRolloutError( + "pre-action evidence requires aligned demonstration and execution-start images" + ) + source_observations = tuple( + RealizedObservation( + observation_id=f"{self._window.episode_nonce}:history:{index}", + step=index, + front_image=front, + wrist_image=wrists[index], + ) + for index, front in enumerate(fronts) + ) + selected = sample_uniform_observations(source_observations, max_timepoints=16) + history_indices = tuple(observation.step for observation in selected) + evidence = tuple( + RealizedObservation( + observation_id=observation.observation_id, + step=timepoint_id, + front_image=observation.front_image, + wrist_image=observation.wrist_image, + ) + for timepoint_id, observation in enumerate(selected) + ) + window = SemanticWindowState( + window_id=f"{self._window.episode_nonce}:initial-memory:1", + episode_nonce=self._window.episode_nonce, + start_step=0, + current_step=len(evidence) - 1, + max_end_step=len(evidence) - 1, + observations=evidence, + chunk_ids=(f"{self._window.episode_nonce}:pre-action-demonstration",), + phase=SemanticWindowPhase.READY, + ) + request = GroundedWriterRequest( + original_task=self._task_context.anchor, + task_context=self._task_context.current, + window=window, + evidence=evidence, + purpose=WriterRequestPurpose.PRE_ACTION_DEMONSTRATION, + history_indices=history_indices, + ) + self._initial_writer_prepared = True + self._writer_request = request + return request + + def cancel_policy_request(self) -> None: + """Release a failed/aborted policy call without changing episode state.""" + + if self._awaiting_policy_response is None: + raise SemanticTransitionRolloutError("no policy response is pending") + self._awaiting_policy_response = None + + def accept_policy_response( + self, + *, + chunk_id: str, + actions: Any, + p_transition_span: float, + p_transition_last_given_span: float = 0.0, + ) -> np.ndarray: + """Bind a response and return its safe read-only executable prefix. + + An active window followed by a negative span proposal returns an empty + prefix: all 16 proposed actions are canceled before environment execution + while the realized positive window is sent to the writer. + """ + + request = self._awaiting_policy_response + if request is None: + raise SemanticTransitionRolloutError("accept_policy_response requires an open policy call") + if self._pending_chunk is not None: + raise SemanticTransitionRolloutError("an action chunk is already pending") + chunk_id = _nonempty(chunk_id, "chunk_id") + try: + proposed = np.asarray(actions, dtype=np.float32) + except (TypeError, ValueError) as exc: + raise SemanticTransitionRolloutError("actions must be a numeric matrix") from exc + if proposed.ndim != 2 or proposed.shape[0] < STATUS_HORIZON or proposed.shape[1] != ROBOT_VECTOR_DIM: + raise SemanticTransitionRolloutError( + f"actions must have shape [N, {ROBOT_VECTOR_DIM}] with N >= {STATUS_HORIZON}" + ) + if not np.isfinite(proposed).all(): + raise SemanticTransitionRolloutError("actions must contain only finite values") + executable = np.array(proposed[:STATUS_HORIZON], dtype=np.float32, copy=True) + executable.flags.writeable = False + try: + raw_span = np.asarray(p_transition_span) + except (TypeError, ValueError) as exc: + raise SemanticTransitionRolloutError("p_transition_span must be numeric") from exc + if ( + raw_span.shape != () + or not np.issubdtype(raw_span.dtype, np.number) + or np.issubdtype(raw_span.dtype, np.bool_) + ): + raise SemanticTransitionRolloutError("p_transition_span must be a numeric scalar") + try: + raw_last_span = np.asarray(p_transition_last_given_span) + except (TypeError, ValueError) as exc: + raise SemanticTransitionRolloutError( + "p_transition_last_given_span must be numeric" + ) from exc + if ( + raw_last_span.shape != () + or not np.issubdtype(raw_last_span.dtype, np.number) + or np.issubdtype(raw_last_span.dtype, np.bool_) + ): + raise SemanticTransitionRolloutError( + "p_transition_last_given_span must be a numeric scalar" + ) + status = ChunkTransitionStatus( + p_transition_span=float(raw_span), + p_transition_last_given_span=float(raw_last_span), + ) + preempted = self._window.start_chunk( + chunk_id=chunk_id, + start_step=request.step, + pre_observation=self._current_observation, + status=status, + ) + if preempted is not None: + if not preempted.preempted or not preempted.ready: + raise AssertionError("proposal-boundary result must be a ready preemption") + self._preempted_chunk_result = preempted + self._awaiting_policy_response = None + self._cache_writer_request() + canceled = np.empty((0, ROBOT_VECTOR_DIM), dtype=np.float32) + canceled.flags.writeable = False + return canceled + execution_limit = self._window.pending_execution_limit + if execution_limit is None: + raise AssertionError("accepted action proposal has no controller execution limit") + executable = np.array(executable[:execution_limit], dtype=np.float32, copy=True) + executable.flags.writeable = False + self._pending_chunk = _PendingActionChunk( + chunk_id=chunk_id, + start_step=request.step, + executable_actions=executable, + ) + self._awaiting_policy_response = None + return executable + + def record_executed_offset( + self, + *, + chunk_id: str, + offset: int, + resulting_state: Any, + front_image: Any, + wrist_image: Any | None = None, + observation_id: str | None = None, + ) -> RealizedRobotDelta: + """Record one sequential action only after its real observation exists.""" + + pending = self._require_pending_chunk(chunk_id) + if isinstance(offset, bool) or not isinstance(offset, int): + raise SemanticTransitionRolloutError("offset must be an integer") + expected_offset = pending.executed_count + 1 + if offset != expected_offset: + raise SemanticTransitionRolloutError( + f"executed offsets must be contiguous; expected {expected_offset}, got {offset}" + ) + if offset > len(pending.executable_actions): + raise SemanticTransitionRolloutError( + "offset exceeds the controller-bounded executable prefix" + ) + post_state = _readonly_float32( + resulting_state, + shape=(ROBOT_VECTOR_DIM,), + field_name="resulting_state", + ) + resulting_step = pending.start_step + offset + observation = RealizedObservation( + observation_id=( + observation_id + if observation_id is not None + else f"{self._window.episode_nonce}:observation:{resulting_step}" + ), + step=resulting_step, + front_image=front_image, + wrist_image=wrist_image, + robot_state=post_state, + ) + realized = self._realized_context.record( + step=resulting_step, + action=pending.executable_actions[offset - 1], + resulting_state=post_state, + ) + + self._window.record_executed_offset( + chunk_id=chunk_id, + offset=offset, + observation=observation, + ) + self._current_observation = observation + pending.executed_count += 1 + return realized + + def finish_chunk(self, *, chunk_id: str) -> ChunkIngestResult: + """Close the chunk and cancel every unexecuted action.""" + + self._require_pending_chunk(chunk_id) + result = self._window.finish_chunk(chunk_id=chunk_id) + self._pending_chunk = None + if result.ready: + self._cache_writer_request() + return result + + def writer_request_if_ready(self) -> GroundedWriterRequest | None: + """Return the cached uniform evidence request without doing image packaging.""" + + return self._writer_request + + def require_writer_request(self) -> GroundedWriterRequest: + request = self._writer_request + if request is None: + raise SemanticTransitionRolloutError("no semantic window is writer-ready") + return request + + def apply_writer_result( + self, + result: ValidatedWriterResult, + *, + commit_context: bool = True, + ) -> WriterApplication: + """Resolve one writer result at a policy boundary. + + ``commit_context=False`` is the shadow-mode path: the real Gemini + decision remains auditable and resolves the ready window, but an + ``update`` proposal cannot mutate the task-context revision. + """ + + if self._awaiting_policy_response is not None or self._pending_chunk is not None: + raise SemanticTransitionRolloutError("writer results may be applied only between policy calls") + if not isinstance(result, ValidatedWriterResult): + raise TypeError("result must be ValidatedWriterResult") + if type(commit_context) is not bool: + raise TypeError("commit_context must be bool") + previous = self._writer_applications.get(result.request_id) + if previous is not None: + previous_result, previous_commit_context, application = previous + if previous_result != result: + raise SemanticTransitionRolloutError("writer request id was reused with different content") + if previous_commit_context is not commit_context: + raise SemanticTransitionRolloutError( + "writer request retry cannot change commit_context mode" + ) + return application + request = self._writer_request + if request is None: + raise SemanticTransitionRolloutError("no writer-ready request is awaiting a result") + if result.request_id != request.request_id or result.window_id != request.window.window_id: + raise SemanticTransitionRolloutError("writer result does not match the current request/window") + if request.purpose is WriterRequestPurpose.PRE_ACTION_DEMONSTRATION: + context_commit = None + if result.decision is WriterDecision.UPDATE and commit_context: + if result.context_delta is None: + raise SemanticTransitionRolloutError( + "update result is missing its CAS context delta" + ) + context_commit = self._task_context.commit(result.context_delta) + self._history_required_indices = tuple( + request.history_indices[timepoint_id] + for timepoint_id in result.proposal.evidence_timepoint_ids + ) + elif result.decision is not WriterDecision.UPDATE and result.context_delta is not None: + raise SemanticTransitionRolloutError( + "non-update result must not contain a context delta" + ) + application = WriterApplication( + request_id=result.request_id, + decision=result.decision, + context_commit=context_commit, + window_resolution_applied=False, + rendered_prompt=self.rendered_prompt, + ) + self._writer_applications[result.request_id] = ( + result, + commit_context, + application, + ) + self._writer_request = None + return application + ready = self._window.ready_window + if ready is None or ready.window_id != result.window_id: + raise SemanticTransitionRolloutError("writer result window is no longer ready") + + context_commit = None + if result.decision is WriterDecision.UPDATE and commit_context: + if result.context_delta is None: + raise SemanticTransitionRolloutError("update result is missing its CAS context delta") + context_commit = self._task_context.commit(result.context_delta) + elif result.decision is not WriterDecision.UPDATE and result.context_delta is not None: + raise SemanticTransitionRolloutError("non-update result must not contain a context delta") + + resolution = WindowResolution(result.decision.value) + resolution_applied = self._window.resolve_ready_window( + window_id=result.window_id, + decision=resolution, + ) + application = WriterApplication( + request_id=result.request_id, + decision=result.decision, + context_commit=context_commit, + window_resolution_applied=resolution_applied, + rendered_prompt=self.rendered_prompt, + ) + self._writer_applications[result.request_id] = (result, commit_context, application) + self._writer_request = None + self._preempted_chunk_result = None + return application + + def _cache_writer_request(self) -> None: + ready = self._window.ready_window + if ready is None: + raise AssertionError("writer request requires a ready semantic window") + evidence = sample_uniform_observations(ready.observations, max_timepoints=16) + self._writer_request = GroundedWriterRequest( + original_task=self._task_context.anchor, + task_context=self._task_context.current, + window=ready, + evidence=evidence, + ) + + def _require_pending_chunk(self, chunk_id: str) -> _PendingActionChunk: + pending = self._pending_chunk + if pending is None: + raise SemanticTransitionRolloutError("no action chunk is pending") + if chunk_id != pending.chunk_id: + raise SemanticTransitionRolloutError( + f"pending chunk is {pending.chunk_id!r}, not {chunk_id!r}" + ) + return pending + + +class OnlineStage4SemanticTransitionRolloutAdapter(SemanticTransitionRolloutAdapter): + """Status-window adapter whose writer mutates Stage4 memory, not task text.""" + + def __init__( + self, + *, + episode_nonce: str, + memory_episode_id: str, + original_instruction: str, + initial_step: int, + history_frame_offset: int, + episode_frame_limit: int, + episode_fps: float, + initial_state: Any, + initial_front_image: Any, + initial_wrist_image: Any | None = None, + initial_observation_id: str | None = None, + confirmation_tail: int = 4, + span_threshold: float = 0.5, + last_span_threshold: float = 0.5, + cooldown_chunks: int = 1, + ) -> None: + super().__init__( + episode_nonce=episode_nonce, + original_instruction=original_instruction, + initial_step=initial_step, + initial_state=initial_state, + initial_front_image=initial_front_image, + initial_wrist_image=initial_wrist_image, + initial_observation_id=initial_observation_id, + initial_subgoal=None, + confirmation_tail=confirmation_tail, + span_threshold=span_threshold, + last_span_threshold=last_span_threshold, + cooldown_chunks=cooldown_chunks, + ) + self._online_memory = OnlineStage4MemoryStore(episode_id=memory_episode_id) + self._history_frame_offset = _natural(history_frame_offset, "history_frame_offset") + self._episode_frame_limit = _natural(episode_frame_limit, "episode_frame_limit") + if initial_step > self._episode_frame_limit: + raise SemanticTransitionRolloutError( + "initial_step cannot exceed episode_frame_limit" + ) + if ( + isinstance(episode_fps, bool) + or not isinstance(episode_fps, int | float) + or not np.isfinite(episode_fps) + or episode_fps <= 0 + ): + raise SemanticTransitionRolloutError( + "episode_fps must be a positive finite number" + ) + self._episode_fps = float(episode_fps) + self._initial_writer_prefixes: list[tuple[RealizedObservation, ...]] = [] + self._initial_writer_sequence = 0 + self._previous_online_writer_transition_end_frame: int | None = None + self._online_writer_applications: dict[ + str, + tuple[ + OnlineStage4ValidatedWriterResult, + bool, + OnlineStage4WriterApplication, + ], + ] = {} + self._retained_writer_observations: dict[int, RealizedObservation] = { + self._history_frame_offset + initial_step: self._current_observation + } + + @property + def memory_snapshot(self): + return self._online_memory.snapshot + + @property + def static_semantic_memory(self) -> str: + return self._online_memory.policy_memory_text + + def prepare_policy_request(self) -> OnlineStage4PolicyRequest: + if self._awaiting_policy_response is not None: + raise SemanticTransitionRolloutError("a policy response is already pending") + if self._pending_chunk is not None: + raise SemanticTransitionRolloutError( + "finish the current action chunk before the next policy call" + ) + if self._window.ready_window is not None or self._writer_request is not None: + raise SemanticTransitionRolloutError( + "resolve the writer-ready window before the next policy call" + ) + request = OnlineStage4PolicyRequest( + step=self.current_step, + observation_id=self._current_observation.observation_id, + prompt=self.original_task.instruction, + static_semantic_memory=self._online_memory.policy_memory_text, + memory_revision=self._online_memory.revision, + history_required_indices=self._online_memory.history_required_indices, + **self._realized_context.model_inputs(), + ) + self._awaiting_policy_response = request + return request + + def prepare_initial_writer_request( + self, + *, + front_images: tuple[Any, ...] | list[Any], + wrist_images: tuple[Any | None, ...] | list[Any | None], + ) -> OnlineStage4WriterRequest: + if self._initial_writer_prepared: + raise SemanticTransitionRolloutError("initial writer request was already prepared") + if ( + self._awaiting_policy_response is not None + or self._pending_chunk is not None + or self._writer_request is not None + or self._window.phase is not SemanticWindowPhase.CLOSED + or self._realized_context.history + ): + raise SemanticTransitionRolloutError( + "initial writer request must precede every policy call and executed action" + ) + fronts = tuple(front_images) + wrists = tuple(wrist_images) + if len(fronts) < 2 or len(fronts) != len(wrists): + raise SemanticTransitionRolloutError( + "pre-action evidence requires aligned demonstration and execution-start images" + ) + source = tuple( + RealizedObservation( + observation_id=f"{self._window.episode_nonce}:history:{index}", + step=index, + front_image=front, + wrist_image=wrists[index], + ) + for index, front in enumerate(fronts) + ) + selected = sample_uniform_observations(source, max_timepoints=8) + selected_count = len(selected) + prefix_lengths = tuple( + sorted( + { + max(2, (selected_count + 1) // 2), + max(2, (3 * selected_count + 3) // 4), + selected_count, + } + ) + ) + self._initial_writer_prefixes = [ + selected[:prefix_length] for prefix_length in prefix_lengths + ] + self._initial_writer_prepared = True + return self._cache_next_initial_writer_request() + + def apply_writer_result( + self, + result: OnlineStage4ValidatedWriterResult, + *, + commit_memory: bool = True, + ) -> OnlineStage4WriterApplication: + if self._awaiting_policy_response is not None or self._pending_chunk is not None: + raise SemanticTransitionRolloutError( + "writer results may be applied only between policy calls" + ) + if not isinstance(result, OnlineStage4ValidatedWriterResult): + raise TypeError("result must be OnlineStage4ValidatedWriterResult") + if type(commit_memory) is not bool: + raise TypeError("commit_memory must be bool") + previous = self._online_writer_applications.get(result.request_id) + if previous is not None: + previous_result, previous_commit_memory, application = previous + if previous_result != result: + raise SemanticTransitionRolloutError( + "writer request id was reused with different content" + ) + if previous_commit_memory is not commit_memory: + raise SemanticTransitionRolloutError( + "writer request retry cannot change commit_memory mode" + ) + return application + request = self._writer_request + if not isinstance(request, OnlineStage4WriterRequest): + raise SemanticTransitionRolloutError( + "no online Stage4 writer-ready request is awaiting a result" + ) + if result.request_id != request.request_id or result.window_id != request.window.window_id: + raise SemanticTransitionRolloutError( + "writer result does not match the current request/window" + ) + + before_revision = self._online_memory.revision + if commit_memory: + effective_from_frame = max(request.evidence_frame_indices) + if request.purpose is not WriterRequestPurpose.PRE_ACTION_DEMONSTRATION: + effective_from_frame += 1 + effective_from_frame = max( + effective_from_frame, + self._online_memory.snapshot.effective_from_frame + 1, + ) + self._online_memory.apply( + result.decision, + effective_from_frame=effective_from_frame, + ) + + window_resolution_applied = False + if request.purpose is WriterRequestPurpose.TRANSITION: + ready = self._window.ready_window + if ready is None or ready.window_id != result.window_id: + raise SemanticTransitionRolloutError( + "writer result window is no longer ready" + ) + if result.decision.operation != "abstain": + resolution = WindowResolution.UPDATE + elif result.decision.reason_code == "no_durable_memory_change": + resolution = WindowResolution.NO_CHANGE + else: + resolution = WindowResolution.ABSTAIN + window_resolution_applied = self._window.resolve_ready_window( + window_id=result.window_id, + decision=resolution, + ) + + application = OnlineStage4WriterApplication( + request_id=result.request_id, + operation=result.decision.operation, + memory_committed=( + commit_memory + and self._online_memory.revision != before_revision + ), + memory_before_revision=before_revision, + memory_after_revision=self._online_memory.revision, + window_resolution_applied=window_resolution_applied, + static_semantic_memory=self._online_memory.policy_memory_text, + history_required_indices=self._online_memory.history_required_indices, + ) + self._online_writer_applications[result.request_id] = ( + result, + commit_memory, + application, + ) + self._previous_online_writer_transition_end_frame = max( + request.evidence_frame_indices + ) + self._writer_request = None + self._preempted_chunk_result = None + if ( + request.purpose is WriterRequestPurpose.PRE_ACTION_DEMONSTRATION + and self._initial_writer_prefixes + ): + self._cache_next_initial_writer_request() + return application + + def _cache_next_initial_writer_request(self) -> OnlineStage4WriterRequest: + if self._writer_request is not None or not self._initial_writer_prefixes: + raise SemanticTransitionRolloutError( + "no pre-action demonstration prefix is ready" + ) + source = self._initial_writer_prefixes.pop(0) + frame_indices = tuple(observation.step for observation in source) + evidence = tuple( + RealizedObservation( + observation_id=observation.observation_id, + step=timepoint_id, + front_image=observation.front_image, + wrist_image=observation.wrist_image, + ) + for timepoint_id, observation in enumerate(source) + ) + self._initial_writer_sequence += 1 + window = SemanticWindowState( + window_id=( + f"{self._window.episode_nonce}:initial-memory:" + f"{self._initial_writer_sequence}" + ), + episode_nonce=self._window.episode_nonce, + start_step=0, + current_step=len(evidence) - 1, + max_end_step=len(evidence) - 1, + observations=evidence, + chunk_ids=(f"{self._window.episode_nonce}:pre-action-demonstration",), + phase=SemanticWindowPhase.READY, + ) + request = OnlineStage4WriterRequest( + original_task=self.original_task, + memory_before=self._online_memory.snapshot, + window=window, + evidence=evidence, + evidence_frame_indices=frame_indices, + remaining_episode_frames_after_transition=max( + 0, + self._episode_frame_limit - self.current_step, + ), + episode_fps=self._episode_fps, + previous_transition_end_frame=( + self._previous_online_writer_transition_end_frame + ), + purpose=WriterRequestPurpose.PRE_ACTION_DEMONSTRATION, + memory_references=self._active_memory_references(), + ) + self._retain_writer_evidence(request) + self._writer_request = request + return request + + def _cache_writer_request(self) -> None: + ready = self._window.ready_window + if ready is None: + raise AssertionError("writer request requires a ready semantic window") + evidence = sample_uniform_observations(ready.observations, max_timepoints=8) + frame_indices = tuple( + self._history_frame_offset + observation.step for observation in evidence + ) + request = OnlineStage4WriterRequest( + original_task=self.original_task, + memory_before=self._online_memory.snapshot, + window=ready, + evidence=evidence, + evidence_frame_indices=frame_indices, + remaining_episode_frames_after_transition=max( + 0, + self._episode_frame_limit - ready.current_step, + ), + episode_fps=self._episode_fps, + previous_transition_end_frame=( + self._previous_online_writer_transition_end_frame + ), + memory_references=self._active_memory_references(), + ) + self._retain_writer_evidence(request) + self._writer_request = request + + def _retain_writer_evidence(self, request: OnlineStage4WriterRequest) -> None: + self._retained_writer_observations.update( + zip(request.evidence_frame_indices, request.evidence, strict=True) + ) + + def _active_memory_references(self) -> tuple[OnlineStage4MemoryReference, ...]: + references: list[OnlineStage4MemoryReference] = [] + for item in self._online_memory.snapshot.items: + for image_ref in item.image_refs: + observation = self._retained_writer_observations.get(image_ref.frame_index) + if observation is None: + raise SemanticTransitionRolloutError( + "active memory anchor has no retained observable image" + ) + references.append( + OnlineStage4MemoryReference( + item_id=item.item_id, + image_ref=image_ref, + observation=observation, + ) + ) + return tuple(references) + + + +__all__ = [ + "CONTEXT_HORIZON", + "ROBOT_VECTOR_DIM", + "STATUS_HORIZON", + "OnlineStage4PolicyRequest", + "OnlineStage4SemanticTransitionRolloutAdapter", + "OnlineStage4WriterApplication", + "RealizedRobotDelta", + "RealizedTransitionContext", + "SemanticPolicyRequest", + "SemanticTransitionRolloutAdapter", + "SemanticTransitionRolloutError", + "WriterApplication", +] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/shared/mem_buffer.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/shared/mem_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f42fc04e871d13bfb6111cc1b359365989fef0 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/shared/mem_buffer.py @@ -0,0 +1,635 @@ +import jax +import jax.numpy as jnp +import einops +import math +import heapq +from copy import deepcopy +import numpy as np +from typing import Callable +import cv2 +from collections import defaultdict + + +from openpi.shared import image_tools +from mme_vla_suite.shared.data_utils import * + + +def create_dict(indices): + result = defaultdict(lambda: defaultdict(list)) # {step_idx: {view_idx: [patch_idx]}} + for step_idx, view_idx, patch_idx in indices: + result[step_idx][view_idx].append(patch_idx) + return result + + +class MemoryBuffer: + # We use 8x8 tokens each image for token dropping and 4x4 tokens for frame sampling. + def __init__( + self, + num_views: int = 1, # number of camera views to be used as memory, better use fixed-views + img_emb_dim: int = 2048, # the initila image token embedding dimension, siglip is 2048 + pos_emb_dim: int = 768, + state_emb_dim: int = 8, + max_steps: int = 4096, + compute_token_drop_score: bool = False, # set true when using token dropping + token_drop_keptsize: int = 2048, # max number of tokens to be kept in the heap for similarity score calculation + token_drop_stride: int = 8, # timestep stride for similarity score calculation, if too close, the difference will be too small + prepare_buffer: bool = False, # set true during online evaluation, set false during offline training + pool_type: str = "mean", # pooling type for the image tokens, mean or max + vision_enc_fn: Callable | None = None, # vision encoding function + ): + self.num_views = num_views + self.img_emb_dim = img_emb_dim + self.pos_emb_dim = pos_emb_dim + self.state_emb_dim = state_emb_dim + + self.pool_type = pool_type + self.token_drop_keptsize = token_drop_keptsize + self.token_drop_stride = token_drop_stride + self.token_drop_last_frame = -1 + self.scored_token_heap = [] + self.compute_token_drop_score = compute_token_drop_score + + self._history_feats = {} + + + if prepare_buffer: + # load models in GPUs to provide embeedings + # used for dataset buliding and evaluation + from mme_vla_suite.shared.posemb_3d import PosEmb3D + if vision_enc_fn is None: + from mme_vla_suite.shared.siglip_tokenizer import SigLipTokenizer + siglip_tokenizer = SigLipTokenizer() + self.vision_enc = jax.jit(siglip_tokenizer.__call__) + else: + self.vision_enc = vision_enc_fn + pos_embedder = PosEmb3D(dim=pos_emb_dim) + ranges = jnp.arange(max_steps) + self.pos_emb_dict = { + "8x8": np.array(pos_embedder(ranges, 8)), + "4x4": np.array(pos_embedder(ranges, 4)), + "2x2": np.array(pos_embedder(ranges, 2)), + } + else: + # used in dataset loading mode + self.vision_enc = None + self.pos_emb_dict = None + + def add_buffer( + self, + images, #: (t v h w 3), np.int8 + states, #: (t d), np.float32 + step_idx_list: list[int], + ): + assert self.vision_enc is not None, "encode is not initialized" + + t, v, _, _, _ = images.shape + assert v == self.num_views + + image_jnp = jnp.array( + images.astype(np.float32) / 255.0 * 2.0 - 1.0 + ) + image_jnp = einops.rearrange(image_jnp, "t v h w c -> (t v) h w c") + image_jnp = image_tools.resize_with_pad(image_jnp, 224, 224) + image_jnp = einops.rearrange(image_jnp, "(t v) h w c -> t v h w c", t=t, v=v) + output_emb = self.vision_enc(image_jnp) # (t, v, 64, 2048) + + pooled_emb_8x8 = pool_tokens_to_size(output_emb, 64) # (t, v, 64, 2048) + pooled_emb_4x4 = pool_tokens_to_size(output_emb, 16) # (t, v, 16, 2048) + pooled_emb_2x2 = pool_tokens_to_size(output_emb, 4) # (t, v, 4, 2048) + + for i, step_idx in enumerate(step_idx_list): + image_emb_8x8 = jax.device_get(pooled_emb_8x8)[i] # (v, 64, 2048) + image_emb_4x4 = jax.device_get(pooled_emb_4x4)[i] # (v, 16, 2048) + image_emb_2x2 = jax.device_get(pooled_emb_2x2)[i] # (v, 4, 2048) + + pos_emb_8x8 = self.pos_emb_dict["8x8"][ + step_idx*self.num_views : (step_idx+1)*self.num_views] # (v, 64, 768) + pos_emb_4x4 = self.pos_emb_dict["4x4"][ + step_idx*self.num_views : (step_idx+1)*self.num_views] # (v, 16, 768) + pos_emb_2x2 = self.pos_emb_dict["2x2"][ + step_idx*self.num_views : (step_idx+1)*self.num_views] # (v, 4, 768) + + token_emb_to_save = { + "image_pixels": images[i].copy(), # fp32, this is for visualization + "image_emb_8x8": image_emb_8x8, # bf16 + "image_emb_4x4": image_emb_4x4, # bf16 + "image_emb_2x2": image_emb_2x2, # bf16 + "pos_emb_8x8": pos_emb_8x8, # fp32 + "pos_emb_4x4": pos_emb_4x4, # fp32 + "pos_emb_2x2": pos_emb_2x2, # fp32 + "state_emb": states[i], # fp32 + } + assert step_idx not in self._history_feats, f"step_idx {step_idx} already in buffer" + self._history_feats[step_idx] = token_emb_to_save + + if self.compute_token_drop_score: + self._process_token_drop_score(step_idx) + + + def get_history_feats(self, step_idx: int, remove_image_pixels: bool = True): + if remove_image_pixels: + return {k: v for k, v in self._history_feats[step_idx].items() if k != "image_pixels"} + return self._history_feats[step_idx] + + + def _process_token_drop_score(self, step_idx): + if step_idx == 0: # all tokens in the first frame should be kept, only later frames are considered for token dropping + for patch_idx in range(64): # 64 patches in 8x8 grid, which is fixed here for now + for view_idx in range(self.num_views): + heapq.heappush( + self.scored_token_heap, (1000.0, step_idx, view_idx, patch_idx) + ) + + if step_idx == self.token_drop_last_frame + self.token_drop_stride: + prev_img = self._history_feats[max(0, self.token_drop_last_frame)]["image_pixels"] + curr_img = self._history_feats[step_idx]["image_pixels"] + + prev_img = prev_img.astype(np.float32) / 255.0 * 2.0 - 1.0 + curr_img = curr_img.astype(np.float32) / 255.0 * 2.0 - 1.0 + + prev_img_tokens = einops.rearrange(prev_img, "v (ph h) (pw w) c -> v (ph pw) (h w c)", ph=8, pw=8) + curr_img_tokens = einops.rearrange(curr_img, "v (ph h) (pw w) c -> v (ph pw) (h w c)", ph=8, pw=8) + + for view_idx in range(self.num_views): + # pixel works better than siglip embedding + difference = np.abs(prev_img_tokens[view_idx] - curr_img_tokens[view_idx]).mean(axis=-1) + for patch_idx in range(64): + if difference[patch_idx] < 1e-4: + # too similar, skip this patch + continue + heapq.heappush( + self.scored_token_heap, + ( + difference[patch_idx], + step_idx, # timestep index + view_idx, # view index + patch_idx, # patch index + ), + ) + if len(self.scored_token_heap) > self.token_drop_keptsize: + heapq.heappop(self.scored_token_heap) + + self.token_drop_last_frame += self.token_drop_stride + + + def clear(self): + self.scored_token_heap.clear() + self.token_drop_last_frame = -1 + self._history_feats.clear() + + + def get_token_dropping_indices(self): + selected_tokens_heap = deepcopy(self.scored_token_heap) + kept_indices = [] + while selected_tokens_heap: + _, buffer_idx, view_idx, patch_idx = heapq.heappop(selected_tokens_heap) + kept_indices.append((buffer_idx, view_idx, patch_idx)) + + return kept_indices + + @staticmethod + def filter_token_dropping_indices(kept_indices, step_idx, token_budget, is_sorted=True): + kept_indices_filtered = [item for item in kept_indices if item[0] <= step_idx] + kept_indices = kept_indices_filtered[-token_budget:] + if is_sorted: + kept_indices = sorted(kept_indices) + return kept_indices + + + def _prepare_token_dropping(self, history_feats, sorted_kept_indices, token_budget): + img_emb = np.zeros((token_budget, self.img_emb_dim), dtype=np.float32) + pos_emb = np.zeros((token_budget, self.pos_emb_dim), dtype=np.float32) + state_emb = np.zeros((token_budget, self.state_emb_dim), dtype=np.float32) + mask = np.zeros((token_budget), dtype=np.bool_) + + for idx, (buffer_idx, view_idx, patch_idx) in enumerate(sorted_kept_indices[:token_budget]): + img_emb[idx] = history_feats[buffer_idx][f"image_emb_8x8"][view_idx][patch_idx] + pos_emb[idx] = history_feats[buffer_idx][f"pos_emb_8x8"][view_idx][patch_idx] + state_emb[idx] = history_feats[buffer_idx]["state_emb"] + mask[idx] = True + + # print("effective token length: ", np.sum(mask)) + + return img_emb, pos_emb, state_emb, mask + + + def prepare_token_dropping(self, step_idx, token_budget, history_feats_gather_fn, kept_indices=None, *args, **kwargs): + if kept_indices is None: + indices_to_load = self.get_token_dropping_indices() + else: + indices_to_load = kept_indices + + sorted_kept_indices = self.filter_token_dropping_indices( + indices_to_load, step_idx, token_budget, is_sorted=True) + + indices_to_load = sorted(set([item[0] for item in sorted_kept_indices])) + # print("step_idx: ", step_idx) + # print(f"indices_to_load (length: {len(indices_to_load)}/{len(sorted_kept_indices)}): {indices_to_load}") + # self._visualize_token_dropping(sorted_kept_indices, step_idx) + # import pdb; pdb.set_trace() + + history_feats = history_feats_gather_fn(indices_to_load, *args, **kwargs) + + return self._prepare_token_dropping(history_feats, sorted_kept_indices, token_budget) + + + def _visualize_token_dropping(self, kept_indices, step_idx): + dic = create_dict(sorted(kept_indices)) + images = [self._history_feats[idx]["image_pixels"][0] for idx in range(len(self._history_feats))] + + images_anno = [] + for step_idx in dic: + img_anno = images[step_idx].copy() + + img_anno = cv2.putText( + img_anno, + f"{step_idx}", + (img_anno.shape[1] // 2, img_anno.shape[0] // 2), + cv2.FONT_HERSHEY_SIMPLEX, + 1, + (0, 0, 255), + 1, + ) + mask = np.zeros(img_anno.shape[:2], dtype=np.uint8) + + for patch_idx in range(64): + if patch_idx in dic[step_idx][0]: + continue + h_center = patch_idx // 8 * 32 + 16 + w_center = patch_idx % 8 * 32 + 16 + mask = cv2.rectangle( + mask, + (w_center - 16, h_center - 16), + (w_center + 16, h_center + 16), + 255, + -1, + ) + img_anno[mask == 255] = ( + img_anno[mask == 255] * 0.3 + np.array([255, 255, 255]) * 0.7 + ) + + images_anno.append(img_anno) + + import imageio, os + imageio.mimsave( + os.path.join( + "debug", + f"token_drop_anno_step_{step_idx}.mp4", + ), + images_anno, + fps=10, + ) + + + def get_frame_sampling_indices(self, step_idx, token_budget, token_per_image): + max_size = token_budget // (token_per_image * self.num_views) + return even_sampling_indices(step_idx, max_size) + + + def _prepare_frame_sampling(self, history_feats, indices_to_load, token_budget, token_per_image): + spatial_size = str(int(math.sqrt(token_per_image))) + spatial_key = f"{spatial_size}x{spatial_size}" + max_size = token_budget // (token_per_image * self.num_views) + + + sampled_img_emb = self._load_emb(history_feats, indices_to_load, f"image_emb_{spatial_key}") + sampled_pos_emb = self._load_emb(history_feats, indices_to_load, f"pos_emb_{spatial_key}") + sampled_state_emb = self._load_emb(history_feats, indices_to_load, "state_emb") + mask = np.ones((sampled_img_emb.shape[0]), dtype=np.bool_) + + # we use right padding to the perceptual memory + sampled_img_emb, sampled_pos_emb, sampled_state_emb, mask = right_padding_token_emb( + sampled_img_emb, sampled_pos_emb, sampled_state_emb, mask, max_size + ) + + img_emb = np.reshape(sampled_img_emb, (-1, self.img_emb_dim)) + pos_emb = np.reshape(sampled_pos_emb, (-1, self.pos_emb_dim)) + mask = np.repeat(mask, self.num_views * token_per_image) + state_emb = np.repeat(sampled_state_emb, self.num_views * token_per_image, axis=0) + + # print("effective token length: ", np.sum(mask)) + + return img_emb, pos_emb, state_emb, mask + + + def prepare_frame_sampling( + self, + step_idx, + token_budget, + token_per_image, + history_feats_gather_fn, + selected_indices=None, + *args, + **kwargs, + ): + if selected_indices is None: + indices_to_load = self.get_frame_sampling_indices(step_idx, token_budget, token_per_image) + else: + tokens_per_frame = token_per_image * self.num_views + if token_budget <= 0 or token_per_image <= 0 or token_budget % tokens_per_frame: + raise ValueError("selected-frame geometry must evenly divide the token budget") + frame_capacity = token_budget // tokens_per_frame + if not isinstance(selected_indices, (list, tuple)) or not selected_indices: + raise ValueError("selected_indices must be a non-empty list or tuple") + if any( + isinstance(value, bool) or not isinstance(value, (int, np.integer)) + for value in selected_indices + ): + raise ValueError("selected_indices must contain integers") + indices_to_load = [int(value) for value in selected_indices] + expected_count = min(frame_capacity, step_idx + 1) + if len(indices_to_load) != expected_count: + raise ValueError( + f"selected frame count must be exactly {expected_count}, got {len(indices_to_load)}" + ) + if indices_to_load != sorted(set(indices_to_load)): + raise ValueError("selected_indices must be sorted and unique") + if indices_to_load[0] < 0 or indices_to_load[-1] > step_idx: + raise ValueError("selected_indices must be causal and non-negative") + + history_feats = history_feats_gather_fn(indices_to_load, *args, **kwargs) + return self._prepare_frame_sampling(history_feats, indices_to_load, token_budget, token_per_image) + + + def prepare_phase_a_frame_sampling( + self, + step_idx, + token_budget, + frame_indices, + valid_mask, + token_counts, + history_feats_gather_fn, + *args, + **kwargs, + ): + """Materialize a mixed 64/16/4-token Phase-A frame plan. + + ``frame_indices`` and ``valid_mask`` are the immutable visual plan; + metadata interventions never enter this method. Consequently every + metadata arm gathers exactly the same feature blobs and preserves the + original PosEmb3D values and token mask byte-for-byte. + """ + + frame_indices = np.asarray(frame_indices) + valid_mask = np.asarray(valid_mask) + token_counts = np.asarray(token_counts) + if frame_indices.ndim != 1 or frame_indices.shape != valid_mask.shape: + raise ValueError("Phase-A frame indices and valid mask must be aligned vectors") + if token_counts.shape != frame_indices.shape: + raise ValueError("Phase-A token counts must align with frame slots") + if frame_indices.shape != (32,): + raise ValueError("Phase-A frame plan must contain exactly 32 slots") + if valid_mask.dtype != np.bool_: + raise ValueError("Phase-A valid mask must be boolean") + if not np.issubdtype(frame_indices.dtype, np.integer): + raise ValueError("Phase-A frame indices must be integers") + if not np.issubdtype(token_counts.dtype, np.integer): + raise ValueError("Phase-A token counts must be integers") + if self.num_views != 1: + raise ValueError("Phase-A reader requires exactly one memory view") + if token_budget != 512 or int(token_counts.sum()) != token_budget: + raise ValueError("Phase-A reader must materialize exactly 512 tokens") + if not set(int(value) for value in token_counts).issubset({4, 16, 64}): + raise ValueError("Phase-A frame token counts must be one of 4, 16 or 64") + + valid_indices = [int(value) for value in frame_indices[valid_mask]] + if not valid_indices or valid_indices != sorted(set(valid_indices)): + raise ValueError("Phase-A valid frame indices must be non-empty, sorted and unique") + if valid_indices[0] < 0 or valid_indices[-1] > step_idx: + raise ValueError("Phase-A frame indices must be causal and non-negative") + if np.any(frame_indices[~valid_mask] != 0): + raise ValueError("Phase-A padding frame indices must be canonical zeros") + + history_feats = history_feats_gather_fn(valid_indices, *args, **kwargs) + if set(history_feats) != set(valid_indices): + raise ValueError("Phase-A feature gather did not return the exact valid frame set") + first = history_feats[valid_indices[0]] + img_dtype = np.asarray(first["image_emb_4x4"]).dtype + pos_dtype = np.asarray(first["pos_emb_4x4"]).dtype + state_dtype = np.asarray(first["state_emb"]).dtype + image_blocks = [] + position_blocks = [] + state_blocks = [] + mask_blocks = [] + spatial_keys = {4: "2x2", 16: "4x4", 64: "8x8"} + for frame_idx, is_valid, token_count in zip( + frame_indices.tolist(), + valid_mask.tolist(), + token_counts.tolist(), + strict=True, + ): + token_count = int(token_count) + if is_valid: + feature = history_feats[int(frame_idx)] + spatial_key = spatial_keys[token_count] + image = np.asarray(feature[f"image_emb_{spatial_key}"]) + position = np.asarray(feature[f"pos_emb_{spatial_key}"]) + state = np.asarray(feature["state_emb"]) + expected_image = (self.num_views, token_count, self.img_emb_dim) + expected_position = (self.num_views, token_count, self.pos_emb_dim) + if image.shape != expected_image: + raise ValueError( + f"Phase-A image feature shape {image.shape} != {expected_image}" + ) + if position.shape != expected_position: + raise ValueError( + f"Phase-A position feature shape {position.shape} != {expected_position}" + ) + if state.shape != (self.state_emb_dim,): + raise ValueError( + f"Phase-A state feature shape {state.shape} != {(self.state_emb_dim,)}" + ) + image_blocks.append(image.reshape(token_count, self.img_emb_dim)) + position_blocks.append(position.reshape(token_count, self.pos_emb_dim)) + state_blocks.append(np.repeat(state[None, :], token_count, axis=0)) + mask_blocks.append(np.ones(token_count, dtype=np.bool_)) + else: + image_blocks.append( + np.zeros((token_count, self.img_emb_dim), dtype=img_dtype) + ) + position_blocks.append( + np.zeros((token_count, self.pos_emb_dim), dtype=pos_dtype) + ) + state_blocks.append( + np.zeros((token_count, self.state_emb_dim), dtype=state_dtype) + ) + mask_blocks.append(np.zeros(token_count, dtype=np.bool_)) + + img_emb = np.concatenate(image_blocks, axis=0) + pos_emb = np.concatenate(position_blocks, axis=0) + state_emb = np.concatenate(state_blocks, axis=0) + mask = np.concatenate(mask_blocks, axis=0) + expected_shapes = ( + (token_budget, self.img_emb_dim), + (token_budget, self.pos_emb_dim), + (token_budget, self.state_emb_dim), + (token_budget,), + ) + if tuple(value.shape for value in (img_emb, pos_emb, state_emb, mask)) != expected_shapes: + raise ValueError("Phase-A token materializer shape drift") + return img_emb, pos_emb, state_emb, mask + + + def _visualize_frame_sampling(self, indices_to_load, step_idx): + images = [self._history_feats[idx]["image_pixels"][0] for idx in indices_to_load] + + import imageio, os + imageio.mimsave( + os.path.join( + "debug", + f"frame_sampling_step_{step_idx}.mp4", + ), + images, + fps=2, + ) + + @staticmethod + def _load_emb(history_feats: dict, indices_to_load: list[int], key: str): + return np.stack( + [history_feats[idx][key] for idx in indices_to_load], + axis=0, + ) + + def default_history_feats_gather_fn(self, indices_to_load, *args, **kwargs): + return {idx: self._history_feats[idx] for idx in indices_to_load} + + +class MemoryBufferRecurrent(MemoryBuffer): + # By default, we use 8x8 tokens each image for recurrent memory. + def __init__( + self, + input_obs_horizon: int = 8, + max_recur_steps: int = 64, # max number of recurrent steps for all history + max_video_steps: int = 40, # max number of recurrent steps to load for the video-based observations for certain video-conditioned tasks + *args, **kwargs + ): + + super().__init__(*args, **kwargs) + + self.input_obs_horizon = input_obs_horizon + self.max_recur_steps = max_recur_steps + self.max_video_steps = max_video_steps + + + def add_buffer( + self, + images, #: (t v h w 3), np.int8 + state, #: (t d), np.float32 + step_idx_list: list[int], + ): + assert self.vision_enc is not None, "encode is not initialized" + + t, v, _, _, _ = images.shape + assert v == self.num_views + + image_jnp = jnp.array( + images.astype(np.float32) / 255.0 * 2.0 - 1.0 + ) + image_jnp = einops.rearrange(image_jnp, "t v h w c -> (t v) h w c") + image_jnp = image_tools.resize_with_pad(image_jnp, 224, 224) + image_jnp = einops.rearrange(image_jnp, "(t v) h w c -> t v h w c", t=t, v=v) + output_emb = self.vision_enc(image_jnp) # (t, v, 64, 2048) + + # use 8x8 tokens, since recurrent memory can take more tokens than perceptual memory + pooled_emb_8x8 = pool_tokens_to_size(output_emb, 64) # (t, v, 64, 2048) + + for i, step_idx in enumerate(step_idx_list): + image_emb_8x8 = jax.device_get(pooled_emb_8x8)[i] # (v, 64, 2048) + + pos_emb_8x8 = self.pos_emb_dict["8x8"][ + step_idx*self.num_views : (step_idx+1)*self.num_views] # (v, 64, 768) + + token_emb_to_save = { # recurrent memory only uses 8x8 + # "image_pixels": images[i].copy(), # fp32 + "image_emb_8x8": image_emb_8x8, + "pos_emb_8x8": pos_emb_8x8, + "state_emb": state[i], + } + assert step_idx not in self._history_feats, f"step_idx {step_idx} already in buffer" + self._history_feats[step_idx] = token_emb_to_save + + + def get_token_recurrent_indices(self, step_idx, exec_start_idx): + input_obs_horizon = self.input_obs_horizon + max_recur_steps = self.max_recur_steps + max_video_steps = self.max_video_steps + + assert step_idx >=0 and step_idx >= exec_start_idx + + if exec_start_idx == 0: + # no videos + if step_idx < input_obs_horizon: + indices_to_load = [step_idx] + else: + start_idx = step_idx % input_obs_horizon + indices_to_load = list(range(start_idx, step_idx+1, input_obs_horizon)) + indices_to_load = indices_to_load[-max_recur_steps:] + else: + if exec_start_idx <= input_obs_horizon * 2: + # if too short, use more granular sampling + video_indices = list(range(0, exec_start_idx, input_obs_horizon//2)) + elif exec_start_idx <= max_video_steps * input_obs_horizon: + # if not too short, use regular sampling + video_indices = list(range(0, exec_start_idx, input_obs_horizon)) + else: + # if too long, use fixed-size sampling + video_indices = np.linspace(0, exec_start_idx - 1, max_video_steps, dtype=int).tolist() + + if step_idx-exec_start_idx < input_obs_horizon: + rest_indices = [step_idx] + else: + start_idx = (step_idx-exec_start_idx) % input_obs_horizon + exec_start_idx + rest_indices = list(range(start_idx, step_idx+1, input_obs_horizon)) + + combined_indices = video_indices + rest_indices + indices_to_load = combined_indices[-max_recur_steps:] + + assert len(indices_to_load) > 0 and len(indices_to_load) <= max_recur_steps + + return indices_to_load + + + def _prepare_token_recurrent(self, history_feats, indices_to_load, padding=True): + recur_image_embs = [] + recur_pos_embs = [] + recur_state_embs = [] + recur_masks = [] + + for i in indices_to_load: + recur_image_embs.append(history_feats[i]["image_emb_8x8"]) # (v, p, d) + recur_pos_embs.append(history_feats[i]["pos_emb_8x8"]) # (v, p, d) + recur_state_embs.append(history_feats[i]["state_emb"]) # (d) + recur_masks.append(True) # (1) + + recur_image_emb = np.stack(recur_image_embs, axis=0) + recur_pos_emb = np.stack(recur_pos_embs, axis=0) + recur_state_emb = np.stack(recur_state_embs, axis=0) + recur_mask = np.stack(recur_masks, axis=0) + + if padding: + recur_image_emb, recur_pos_emb, recur_state_emb, recur_mask = left_padding_token_emb( + recur_image_emb, recur_pos_emb, recur_state_emb, recur_mask, self.max_recur_steps + ) + return recur_image_emb, recur_pos_emb, recur_state_emb, recur_mask + + + def prepare_token_recurrent(self, step_idx, exec_start_idx, history_feats_gather_fn, *args, **kwargs): + indices_to_load = self.get_token_recurrent_indices(step_idx, exec_start_idx) + # print("step_idx: ", step_idx, "exec_start_idx: ", exec_start_idx) + # print(f"indices_to_load ({len(indices_to_load)}): {indices_to_load}") + assert len(indices_to_load) > 0 and len(indices_to_load) <= self.max_recur_steps + history_feats = history_feats_gather_fn(indices_to_load, *args, **kwargs) + # self._visualize_token_recurrent(indices_to_load, step_idx) + return self._prepare_token_recurrent(history_feats, indices_to_load) + + def _visualize_token_recurrent(self, indices_to_load, step_idx): + images = [self._history_feats[idx]["image_pixels"][0] for idx in indices_to_load] + import imageio, os + imageio.mimsave( + os.path.join( + "debug", + f"token_recurrent_step_{step_idx}.mp4", + ), + images, + fps=2, + ) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/dataset.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..a889298e8b2a0fb94c09c22d83169967b09059c8 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/dataset.py @@ -0,0 +1,501 @@ +import json +import logging +import os +import pickle +import random +import re +from concurrent.futures import ThreadPoolExecutor, as_completed +from pathlib import Path + +import numpy as np +from mme_vla_suite.shared.mem_buffer import MemoryBuffer, MemoryBufferRecurrent +from mme_vla_suite.training.picmem_phase_a import FRAME_BUDGET, RECENT_ANCHOR_COUNT, selected_frame_read +from mme_vla_suite.training.picmem_phase_a_reader import ( + FACTOR_FIELDS, + OBSERVATION_FIELDS, + PhaseAFactors, + materialize_phase_a_read, +) +from omegaconf import DictConfig +from openpi.training import config as _config +from openpi.training.data_loader import Dataset + +from picmem.data.run084_source_consumer import Run084SourceDigestIndex +from picmem.provenance.frozen_reader import FrozenSelectionReader + +random.seed(0) +logger = logging.getLogger(__name__) + + +def load_vector_file(vector_path: str, step_idx: int) -> tuple[dict, int]: + with open(vector_path, "rb") as f: + return np.load(f, allow_pickle=True).item(), step_idx + + + +class SampleDataset(Dataset): + def __init__(self, dataset_path: str): + self.dataset_path = dataset_path + self.stats = json.load(open(os.path.join(self.dataset_path, "meta", "stats.json"))) + launch_kind = os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND", "") + source_digest_sha256 = os.environ.get("PICMEM_SOURCE_DIGEST_SHA256", "") + dataset_sha256 = os.environ.get("PICMEM_DATASET_SHA256", "") + if launch_kind == "formal" and not source_digest_sha256: + raise ValueError("formal Phase-A training requires PICMEM_SOURCE_DIGEST_SHA256") + self.source_digest_index = None + if source_digest_sha256: + if not dataset_sha256: + raise ValueError("source-digest-bound training requires PICMEM_DATASET_SHA256") + self.source_digest_index = Run084SourceDigestIndex.from_dataset( + Path(self.dataset_path), + expected_dataset_manifest_sha256=dataset_sha256, + expected_manifest_sha256=source_digest_sha256, + ) + declared_length = self.stats.get("execution_samples", self.stats.get("total_samples")) + if declared_length != len(self.source_digest_index.records): + raise ValueError("dataset stats differ from the source-digest row coverage") + + def __len__(self): + if "execution_samples" in self.stats: + return self.stats["execution_samples"] + else: + return self.stats["total_samples"] + + def __getitem__(self, idx): + if self.source_digest_index is not None: + return self.source_digest_index.load_pickle(idx) + with open(os.path.join(self.dataset_path, "data", f"{idx}.pkl"), "rb") as f: + return pickle.load(f) + + +class RoboMMEDataset(Dataset): + def __init__( + self, + dataset_path: str, + data_config: _config.DataConfig, + history_config: DictConfig | None, + action_horizon: int, + compute_norm_stats: bool = False, + ): + self.history_config = history_config + + + self.action_horizon = action_horizon + self.dataset = SampleDataset(dataset_path) + self.feature_dir = Path(self.dataset.dataset_path) / "features" + self.phase_a_enabled = False + self.phase_a_sidecar_dir = None + self.phase_a_frame_budget = FRAME_BUDGET + self.phase_a_recent_anchor_count = RECENT_ANCHOR_COUNT + self.phase_a_factors = PhaseAFactors() + self.phase_a_metadata_seed = 0 + self.phase_a_selection_reader = None + + if self.history_config is not None: + self.img_emb_dim = self.history_config.memory_feature.img.input_dim + self.pos_emb_dim = self.history_config.memory_feature.pos.input_dim + self.state_emb_dim = self.history_config.memory_feature.state.input_dim + self.num_views = self.history_config.num_views + self.streaming_obs_horizon = self.history_config.streaming_obs_horizon + + if "perceptual_memory" in self.history_config: + perceptual = self.history_config.perceptual_memory + frame_selection = perceptual.get("frame_selection") + else: + perceptual = None + frame_selection = None + if frame_selection is not None and frame_selection.get("type") == "picmem_phase_a": + if self.history_config.representation_type != "perceptual": + raise ValueError("picmem_phase_a requires perceptual representation") + if perceptual.get("type") != "frame_sampling": + raise ValueError("picmem_phase_a is only a frame_sampling selector") + unknown = set(frame_selection) - { + "type", + "sidecar_dir", + "frame_budget", + "recent_anchor_count", + "selection_mode", + "metadata_mode", + "reader_mode", + "manager_mode", + "metadata_seed", + "require_explicit_factors", + "subset_manifest_path", + "subset_manifest_sha256", + "replacement_manifest_path", + "replacement_manifest_sha256", + "best_visible_manifest_path", + "best_visible_manifest_sha256", + } + if unknown: + raise ValueError(f"unknown picmem_phase_a config fields: {sorted(unknown)}") + sidecar_dir = frame_selection.get("sidecar_dir") + if not isinstance(sidecar_dir, str) or not sidecar_dir.strip(): + raise ValueError( + "picmem_phase_a requires perceptual_memory.frame_selection.sidecar_dir" + ) + self.phase_a_enabled = True + self.phase_a_sidecar_dir = Path(sidecar_dir).expanduser().resolve(strict=True) + if not self.phase_a_sidecar_dir.is_dir(): + raise ValueError( + f"picmem_phase_a sidecar_dir is not a directory: {self.phase_a_sidecar_dir}" + ) + self.phase_a_frame_budget = int( + frame_selection.get("frame_budget", FRAME_BUDGET) + ) + self.phase_a_recent_anchor_count = int( + frame_selection.get("recent_anchor_count", RECENT_ANCHOR_COUNT) + ) + require_explicit = bool( + frame_selection.get("require_explicit_factors", False) + ) + factor_values = { + name: frame_selection.get(name) + for name in FACTOR_FIELDS + if name in frame_selection + } + self.phase_a_factors = PhaseAFactors.from_mapping( + factor_values, + require_explicit=require_explicit, + ) + self.phase_a_factors.validate_implemented_path() + frozen_fields = { + name: frame_selection.get(name) + for name in ( + "subset_manifest_path", + "subset_manifest_sha256", + "replacement_manifest_path", + "replacement_manifest_sha256", + "best_visible_manifest_path", + "best_visible_manifest_sha256", + ) + } + missing_frozen = [ + name + for name, value in frozen_fields.items() + if not isinstance(value, str) or not value + ] + if missing_frozen: + raise ValueError( + "picmem_phase_a requires frozen selection fields: " + f"{sorted(missing_frozen)}" + ) + self.phase_a_selection_reader = FrozenSelectionReader.load_formal( + subset_manifest_path=frozen_fields["subset_manifest_path"], + subset_manifest_sha256=frozen_fields["subset_manifest_sha256"], + replacement_manifest_path=frozen_fields["replacement_manifest_path"], + replacement_manifest_sha256=frozen_fields["replacement_manifest_sha256"], + best_visible_manifest_path=frozen_fields["best_visible_manifest_path"], + best_visible_manifest_sha256=frozen_fields["best_visible_manifest_sha256"], + manager_mode=self.phase_a_factors.manager_mode, + ) + self.phase_a_metadata_seed = frame_selection.get("metadata_seed", 0) + if ( + isinstance(self.phase_a_metadata_seed, bool) + or not isinstance(self.phase_a_metadata_seed, int) + or self.phase_a_metadata_seed < 0 + ): + raise ValueError("picmem_phase_a metadata_seed must be a non-negative integer") + tokens_per_frame = int(self.history_config.token_per_image) * int(self.num_views) + if ( + int(self.history_config.budget) != 512 + or int(self.history_config.token_per_image) != 16 + or int(self.num_views) != 1 + or int(self.history_config.budget) % tokens_per_frame + or int(self.history_config.budget) // tokens_per_frame != FRAME_BUDGET + or self.phase_a_frame_budget != FRAME_BUDGET + or self.phase_a_recent_anchor_count != RECENT_ANCHOR_COUNT + ): + raise ValueError( + "picmem_phase_a requires token_budget=512, token_per_image=16, " + "num_views=1, frame_budget=32, and recent_anchor_count=4" + ) + + if self.history_config.representation_type == "perceptual": + self.mem_buffer = MemoryBuffer( + num_views=self.num_views, + img_emb_dim=self.img_emb_dim, + pos_emb_dim=self.pos_emb_dim, + state_emb_dim=self.state_emb_dim, + token_drop_stride=self.streaming_obs_horizon // 2, + ) + elif self.history_config.representation_type == "recurrent": + self.mem_buffer = MemoryBufferRecurrent( + num_views=self.num_views, + img_emb_dim=self.img_emb_dim, + pos_emb_dim=self.pos_emb_dim, + state_emb_dim=self.state_emb_dim, + input_obs_horizon=self.streaming_obs_horizon, + max_recur_steps=self.history_config.recurrent_memory.max_recur_steps, + max_video_steps=self.history_config.recurrent_memory.max_pretraj_steps, + ) + else: + # symbolic memory does not need mem_buffer + self.mem_buffer = None + else: + logger.info("=== Do not use history ===") + + self.compute_norm_stats = compute_norm_stats + + if not compute_norm_stats: + self.state_norm_stats = data_config.norm_stats['state'] + self.use_quantiles = data_config.use_quantile_norm + + def _gather_history_feat(self, indices_to_load: list[int], epis_idx: int): + history_feats = {} + history_paths = [] + for idx in indices_to_load: + history_feats[idx] = {} + history_paths.append( + os.path.join(self.feature_dir, f"episode_{epis_idx}", f"token_emb_{idx}.npy") + ) + + if self.history_config.representation_type == "recurrent": + # load_vector_fn = load_vector_file_lru4096 if self.use_lru else load_vector_file + load_vector_fn = load_vector_file + max_workers = min(48, max(4, len(history_paths))) + else: + # load_vector_fn = load_vector_file_lru1024 if self.use_lru else load_vector_file + load_vector_fn = load_vector_file + max_workers = min(36, max(4, len(history_paths))) + with ThreadPoolExecutor(max_workers=max_workers) as executor: + future_to_path = { + executor.submit(load_vector_fn, path, idx): path + for path, idx in zip(history_paths, indices_to_load) + } + for future in as_completed(future_to_path): + np_dict, idx = future.result() + history_feats[idx] = np_dict + return history_feats + + + def prepare_token_drop(self, epis_idx, step_idx): + token_budget = self.history_config.budget + kept_indices = json.load(open(os.path.join(self.feature_dir, f"episode_{epis_idx}", "kept_indices.json"))) + + return self.mem_buffer.prepare_token_dropping( + step_idx, token_budget, self._gather_history_feat, + kept_indices=kept_indices, epis_idx=epis_idx) + + + def prepare_frame_sampling(self, epis_idx, step_idx, *, selected_indices=None): + token_per_image = self.history_config.token_per_image + token_budget = self.history_config.budget + + return self.mem_buffer.prepare_frame_sampling( + step_idx, token_budget, token_per_image, self._gather_history_feat, + selected_indices=selected_indices, epis_idx=epis_idx) + + + def prepare_phase_a_frame_sampling(self, epis_idx, step_idx, plan): + return self.mem_buffer.prepare_phase_a_frame_sampling( + step_idx, + int(self.history_config.budget), + plan.frame_indices, + plan.valid_mask, + plan.token_counts, + self._gather_history_feat, + epis_idx=epis_idx, + ) + + + + def prepare_token_recurrent(self, epis_idx, step_idx, exec_start_idx): + self.mem_buffer.exec_start_idx = exec_start_idx + + return self.mem_buffer.prepare_token_recurrent( + step_idx, exec_start_idx, self._gather_history_feat, + epis_idx=epis_idx) + + + def __len__(self): + return len(self.dataset) + + + def _normalize_state(self, state): + if self.compute_norm_stats: + return state + else: + if self.use_quantiles: + return (state - self.state_norm_stats.q01) / (self.state_norm_stats.q99 - self.state_norm_stats.q01 + 1e-6) * 2.0 - 1.0 + else: + return (state - self.state_norm_stats.mean) / (self.state_norm_stats.std + 1e-6) + + def _truncated_gaussian_noise(self, max_val: int, std: float = None) -> int: + """Generate truncated Gaussian noise centered at 0, clamped to [-max_val, max_val].""" + if std is None: + std = max_val / 2.5 # ~95% of samples within range before clamping + noise = random.gauss(0, std) + noise = max(-max_val, min(max_val, noise)) # clamp to [-max_val, max_val] + return int(round(noise)) + + def add_grounding_augmentation(self, subgoal: str, noise_range: int = 8) -> str: + if not subgoal: + return subgoal + + matches = re.findall(r'at <(\d+), (\d+)>', subgoal) + + if len(matches) == 0 or len(matches) > 1: + return subgoal + + x, y = matches[0] + x = int(x) + y = int(y) + noise_x = self._truncated_gaussian_noise(noise_range) + noise_y = self._truncated_gaussian_noise(noise_range) + + new_subgoal = subgoal.replace(f'at <{x}, {y}>', f'at <{x + noise_x}, {y + noise_y}>') + return new_subgoal + + + def __getitem__(self, idx): + data = self.dataset[idx] + + data["actions"] = data["actions"][:self.action_horizon] + + # During online evaluation, the ground-truth subgoal may change earlier than when it was recorded. + # To make the model robust to this temporal shift and avoid train/test distribution mismatch, + # we randomly sample from either subgoal or subgoal_online (early change). + if self.history_config is not None \ + and self.history_config.representation_type == "symbolic" \ + and self.history_config.symbolic_memory.type in ["simple_subgoal", "grounded_subgoal"] \ + and random.random() < 0.5: + data["simple_subgoal"] = data["simple_subgoal_online"] + data["grounded_subgoal"] = data["grounded_subgoal_online"] + data.pop("simple_subgoal_online") + data.pop("grounded_subgoal_online") + + if self.history_config is not None and self.history_config.representation_type == "symbolic": + data["grounded_subgoal"] = self.add_grounding_augmentation(data["grounded_subgoal"], noise_range=8) + data["simple_subgoal"] = self.add_grounding_augmentation(data["simple_subgoal"], noise_range=8) + + + if self.history_config is not None: + # use history + epis_idx = data["epis_idx"].item() + step_idx = data["step_idx"].item() + exec_start_idx = data["exec_start_idx"].item() + + if self.history_config.representation_type == "perceptual": + if self.history_config.perceptual_memory.type == "token_dropping": + ( + static_img_emb, + static_pos_emb, + static_state_emb, + static_mask, # >=64 + ) = self.prepare_token_drop(epis_idx, step_idx) + elif self.phase_a_enabled: + if self.phase_a_sidecar_dir is None: + raise ValueError("picmem_phase_a sidecar directory was not initialized") + if self.phase_a_selection_reader is None: + raise ValueError("picmem_phase_a frozen selection reader was not initialized") + frozen_row = self.phase_a_selection_reader.subset.validate_raw_sample( + int(idx), + data, + ) + read = selected_frame_read( + self.phase_a_sidecar_dir, + episode_id=int(epis_idx), + step=int(step_idx), + raw_exec_start=int(exec_start_idx), + instruction=data.get("prompt"), + frame_budget=self.phase_a_frame_budget, + recent_anchor_count=self.phase_a_recent_anchor_count, + expected_task_id=frozen_row.task_id, + expected_sidecar_sha256=frozen_row.sidecar_sha256, + manager_mode=self.phase_a_factors.manager_mode, + ) + replacement = self.phase_a_selection_reader.record_for( + frozen_row, + current_step=int(step_idx), + ) + read = self.phase_a_selection_reader.render( + read, + replacement, + self.phase_a_factors.selection_mode, + ) + plan = materialize_phase_a_read( + read, + self.phase_a_factors, + metadata_seed=self.phase_a_metadata_seed, + selection_applied=self.phase_a_factors.selection_mode, + ) + ( + static_img_emb, + static_pos_emb, + static_state_emb, + static_mask, + ) = self.prepare_phase_a_frame_sampling( + epis_idx, + step_idx, + plan, + ) + metadata = plan.metadata.to_observation() + if not np.array_equal(static_mask, metadata["phase_a_valid_mask"]): + raise ValueError("Phase-A visual and metadata token masks disagree") + data.update(metadata) + else: + ( + static_img_emb, + static_pos_emb, + static_state_emb, + static_mask, # slow >=64, mid >=16,fast >=4 + ) = self.prepare_frame_sampling(epis_idx, step_idx) + + data["static_image_emb"] = static_img_emb + data["static_pos_emb"] = static_pos_emb + data["static_state_emb"] = self._normalize_state(static_state_emb) + data["static_mask"] = static_mask + + elif self.history_config.representation_type == "recurrent": + recur_img_emb, recur_pos_emb, recur_state_emb, recur_mask = ( + self.prepare_token_recurrent( + epis_idx, step_idx, exec_start_idx) + ) + + data["recur_image_emb"] = recur_img_emb + data["recur_pos_emb"] = recur_pos_emb + data["recur_state_emb"] = self._normalize_state(recur_state_emb) + data["recur_mask"] = recur_mask # 1 ~ max_exec_steps + + elif self.history_config.representation_type == "symbolic": + pass + else: + raise ValueError( + f"Not supported representation type: {self.history_config.representation_type}" + ) + + + for key in [ + "static_image_emb", + "static_pos_emb", + "static_state_emb", + "static_mask", + + "recur_image_emb", + "recur_pos_emb", + "recur_state_emb", + "recur_mask", + + "simple_subgoal", + "grounded_subgoal", + "prompt", + # The pinned host RepackTransform names these optional fields even + # when the active history type is plain frame sampling. Keep them + # neutral; Phase-A never imports or materializes either old stack. + "picmem_token_features", + "picmem_token_mask", + "picmem_typed_role_ids", + "picmem_typed_categorical_ids", + "picmem_typed_numeric_values", + "picmem_typed_numeric_mask", + "picmem_typed_age_confidence", + "picmem_typed_contract_indices", + "picmem_typed_token_mask", + "_picmem_typed_task_index", + *OBSERVATION_FIELDS, + ]: + if key not in data: + data[key] = None + + return data diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a.py new file mode 100644 index 0000000000000000000000000000000000000000..677773c2fb6a4b0aa1db582e43507d8a337ea215 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a.py @@ -0,0 +1,201 @@ +"""Fail-closed RoboMME adapter for the standalone Phase-A memory. + +This is the only host module allowed to translate a raw RoboMME sample into a +Phase-A visual-frame plan. It deliberately imports no legacy host-side memory +package and no general PIC-Mem runtime, tensor, or model surface. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from picmem.memory.contracts import ManagerMode +from picmem.memory.memory import MemoryInvariantError, Read +from picmem.provenance.frozen_artifact import sha256_file +from picmem.provenance.run084 import replay_sidecar + +FRAME_BUDGET = 32 +RECENT_ANCHOR_COUNT = 4 +SUPPORTED_TASKS = frozenset({"MoveCube", "PickXtimes", "VideoPlaceButton", "VideoUnmask"}) + + +def load_episode_sidecar( + sidecar_dir: str | Path, + *, + episode_id: int, + instruction: str, +) -> tuple[Path, dict[str, Any]]: + """Resolve exactly one task-scoped sidecar for a raw host sample.""" + + episode_id = _nonnegative_int(episode_id, "episode_id") + instruction = _instruction(instruction) + root = Path(sidecar_dir).expanduser() + try: + root = root.resolve(strict=True) + except OSError as exc: + raise MemoryInvariantError(f"sidecar directory is unavailable: {root}") from exc + if not root.is_dir(): + raise MemoryInvariantError(f"sidecar path is not a directory: {root}") + + names = {f"episode_{episode_id}.json", f"episode_{episode_id:04d}.json"} + candidates = sorted( + { + path.resolve(strict=True) + for name in names + for path in root.glob(f"*/{name}") + } + ) + if not candidates: + raise MemoryInvariantError( + f"no sidecar exists for episode {episode_id}" + ) + + matches: list[tuple[Path, dict[str, Any]]] = [] + for path in candidates: + if root not in path.parents: + raise MemoryInvariantError(f"sidecar escapes configured root: {path}") + try: + annotation = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise MemoryInvariantError(f"cannot read sidecar JSON: {path}") from exc + if not isinstance(annotation, dict): + raise MemoryInvariantError(f"sidecar must contain a JSON object: {path}") + if _nonnegative_int(annotation.get("episode_id"), "sidecar episode_id") != episode_id: + raise MemoryInvariantError(f"sidecar episode identity mismatch: {path}") + task_id = annotation.get("task_id") + if task_id not in SUPPORTED_TASKS or path.parent.name != task_id: + raise MemoryInvariantError(f"sidecar task identity mismatch: {path}") + if _instruction(annotation.get("task_instruction")) == instruction: + matches.append((path, annotation)) + + if len(matches) != 1: + raise MemoryInvariantError( + f"expected exactly one episode/instruction sidecar for episode {episode_id}, " + f"found {len(matches)}" + ) + return matches[0] + + +def selected_frame_indices( + sidecar_dir: str | Path, + *, + episode_id: int, + step: int, + raw_exec_start: int, + instruction: str, + frame_budget: int = FRAME_BUDGET, + recent_anchor_count: int = RECENT_ANCHOR_COUNT, + manager_mode: ManagerMode | str = ManagerMode.FULL_EVOLVING, +) -> tuple[int, ...]: + """Return the sole frame plan consumed by the host perceptual loader.""" + + read = selected_frame_read( + sidecar_dir, + episode_id=episode_id, + step=step, + raw_exec_start=raw_exec_start, + instruction=instruction, + frame_budget=frame_budget, + recent_anchor_count=recent_anchor_count, + manager_mode=manager_mode, + ) + return tuple(read.valid_indices()) + + +def selected_frame_read( + sidecar_dir: str | Path, + *, + episode_id: int, + step: int, + raw_exec_start: int, + instruction: str, + frame_budget: int = FRAME_BUDGET, + recent_anchor_count: int = RECENT_ANCHOR_COUNT, + expected_task_id: str | None = None, + expected_sidecar_sha256: str | None = None, + manager_mode: ManagerMode | str = ManagerMode.FULL_EVOLVING, +) -> Read: + """Return the complete frame plan and provenance for one host sample.""" + + step = _nonnegative_int(step, "step") + raw_exec_start = _nonnegative_int(raw_exec_start, "raw_exec_start") + if frame_budget != FRAME_BUDGET: + raise MemoryInvariantError(f"Phase-A frame_budget must be {FRAME_BUDGET}") + if recent_anchor_count != RECENT_ANCHOR_COUNT: + raise MemoryInvariantError( + f"Phase-A recent_anchor_count must be {RECENT_ANCHOR_COUNT}" + ) + + path, annotation = load_episode_sidecar( + sidecar_dir, + episode_id=episode_id, + instruction=instruction, + ) + if expected_task_id is not None and annotation.get("task_id") != expected_task_id: + raise MemoryInvariantError( + f"sidecar task differs from frozen sample identity at {path}" + ) + if expected_sidecar_sha256 is not None: + actual_sidecar_sha256 = sha256_file(path) + if actual_sidecar_sha256 != expected_sidecar_sha256: + raise MemoryInvariantError( + f"sidecar hash differs from frozen sample identity at {path}" + ) + sidecar_exec_start = _nonnegative_int( + annotation.get("exec_start_step"), + "sidecar exec_start_step", + ) + step_offset = raw_exec_start - sidecar_exec_start + if step_offset < 0: + raise MemoryInvariantError( + f"raw execution starts before sidecar execution at {path}: " + f"{raw_exec_start} < {sidecar_exec_start}" + ) + + read = replay_sidecar( + annotation, + step, + step_offset=step_offset, + budget=frame_budget, + recent=recent_anchor_count, + manager_mode=manager_mode, + ) + indices = read.valid_indices() + if not isinstance(indices, list) or any( + isinstance(value, bool) or not isinstance(value, int) for value in indices + ): + raise MemoryInvariantError("Phase-A Read.valid_indices() returned non-integers") + if not indices: + raise MemoryInvariantError("Phase-A Read selected no visual frames") + if indices != sorted(set(indices)): + raise MemoryInvariantError("Phase-A Read selected duplicate or unsorted frames") + if len(indices) != min(frame_budget, step + 1) or indices[0] < 0 or indices[-1] > step: + raise MemoryInvariantError("Phase-A Read violated its causal frame budget") + if tuple(indices) != tuple( + frame.frame_index for frame in read.selected_frames if frame.valid_mask + ): + raise MemoryInvariantError("Phase-A Read metadata does not align with valid_indices()") + return read + + +def _instruction(value: Any) -> str: + if not isinstance(value, str) or not value or "\0" in value: + raise MemoryInvariantError("instruction must be a non-empty string") + return value + + +def _nonnegative_int(value: Any, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise MemoryInvariantError(f"{name} must be a non-negative integer") + return int(value) + + +__all__ = [ + "FRAME_BUDGET", + "RECENT_ANCHOR_COUNT", + "load_episode_sidecar", + "selected_frame_indices", + "selected_frame_read", +] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_full_state.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_full_state.py new file mode 100644 index 0000000000000000000000000000000000000000..94e45645994670b52cb227d0fb85a7aa57c6afa1 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_full_state.py @@ -0,0 +1,1936 @@ +"""Trajectory-complete Phase-A checkpoint, sampler, and continuity runtime.""" + +from __future__ import annotations + +import csv +import dataclasses +import functools +import hashlib +import json +import logging +import math +import os +import shutil +import tempfile +from collections.abc import Iterator, Mapping +from datetime import datetime +from pathlib import Path, PurePosixPath +from typing import Any, Protocol + +import jax +import numpy as np +import openpi.training.checkpoints as _checkpoints +import orbax.checkpoint as ocp +import torch +from etils import epath +from mme_vla_suite.models.config.utils import get_history_config +from mme_vla_suite.models.integration.history_observation import HistAugObservation +from mme_vla_suite.training.dataset import RoboMMEDataset +from openpi.shared import normalize as _normalize +from openpi.training.data_loader import TorchDataLoader, transform_dataset + +from picmem.memory.contracts import ArmManifest +from picmem.ops.calibration_manifest import ( + CalibrationManifestError, + SkuCalibrationManifest, + load_calibration_manifest, +) +from picmem.ops.checkpoint import ( + CheckpointInfo, + CheckpointMetadata, + SamplerState, + StateComponent, + StateManifest, + discover_checkpoints, + finalize_checkpoint, + is_phase_a_retained_checkpoint, + path_sha256, + validate_checkpoint, +) +from picmem.ops.continuity import CONTINUITY_SCHEMA, ContinuityMode, SamplerContinuity, WatchState, verify_continuity +from picmem.ops.registry import RUN084_BUILD_C_LINEAGE + +PHASE_A_CONTRACT_SCHEMA = "picmem_phase_a_host_full_state_v5" +PHASE_A_METRICS_SCHEMA = "picmem_phase_a_generation_metrics_v1" +PHASE_A_HISTORY_CONFIG = "perceptual-picmem-phase-a-modul.yaml" +SUPPORTED_GPU_CLASSES = frozenset({"h200", "h100_80g", "a100_80g", "a100_40g"}) +FORMAL_SAMPLER_SCHEMA = "picmem_run084_task_balanced_sampler_state_v1" +SMOKE_SAMPLER_SCHEMA = "picmem_phase_a_smoke_random_sampler_state_v1" +SMOKE_SUBSET_SHA256 = hashlib.sha256(b"picmem-phase-a-smoke-subset-v1").hexdigest() + + +def _identifier(value: Any, name: str) -> str: + portable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-" + if not isinstance(value, str) or not value or any(char not in portable for char in value): + raise ValueError(f"{name} must be a non-empty portable identifier") + return value + + +def _sha256(value: Any, name: str, *, nullable: bool = False) -> str | None: + if nullable and (value is None or value == ""): + return None + if not isinstance(value, str) or len(value) != 64 or any(char not in "0123456789abcdef" for char in value): + raise ValueError(f"{name} must be a lowercase SHA-256 digest") + return value + + +def _commit(value: Any, name: str) -> str: + if not isinstance(value, str) or len(value) != 40 or any(char not in "0123456789abcdef" for char in value): + raise ValueError(f"{name} must be a full lowercase git commit") + return value + + +def _runtime_fraction(value: Any, name: str) -> str: + if not isinstance(value, str) or value not in {"0.8", "0.9", "0.92"}: + raise ValueError(f"{name} must be a reviewed canonical runtime fraction") + return value + + +def _runtime_true(value: Any, name: str) -> bool: + if value != "true": + raise ValueError(f"{name} must be the reviewed canonical value 'true'") + return True + + +def _repr_sha256(value: Any) -> str: + return hashlib.sha256(repr(value).encode("utf-8")).hexdigest() + + +def _natural(value: str | int, name: str) -> int: + try: + parsed = int(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be a non-negative integer") from exc + if isinstance(value, bool) or parsed < 0 or str(parsed) != str(value): + raise ValueError(f"{name} must be a canonical non-negative integer") + return parsed + + +def _sampler_natural(value: Any, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) < 0: + raise ValueError(f"{name} must be a non-negative integer") + return int(value) + + +def _u64_words(value: int, name: str) -> jax.Array: + parsed = _natural(value, name) + if parsed > np.iinfo(np.uint64).max: + raise ValueError(f"{name} is larger than an unsigned 64-bit integer") + return jax.numpy.asarray( + [parsed & 0xFFFFFFFF, (parsed >> 32) & 0xFFFFFFFF], + dtype=jax.numpy.uint32, + ) + + +def _decode_u64_words(value: Any, name: str) -> int: + words = np.asarray(jax.device_get(value), dtype=np.uint32).reshape(-1) + if words.shape != (2,): + raise ValueError(f"{name} must contain exactly two uint32 words") + return int(words[0]) | (int(words[1]) << 32) + + +def _digest_bytes(value: str, name: str) -> jax.Array: + parsed = _sha256(value, name) + return jax.numpy.asarray(np.frombuffer(bytes.fromhex(str(parsed)), dtype=np.uint8)) + + +def _decode_digest(value: Any, name: str) -> str: + raw = np.asarray(jax.device_get(value), dtype=np.uint8).reshape(-1) + if raw.shape != (32,): + raise ValueError(f"{name} must contain exactly 32 digest bytes") + return str(_sha256(raw.tobytes().hex(), name)) + + +def _ascii_bytes(value: str, name: str) -> jax.Array: + parsed = _identifier(value, name) + return jax.numpy.asarray(np.frombuffer(parsed.encode("ascii"), dtype=np.uint8)) + + +def _decode_ascii(value: Any, name: str) -> str: + raw = np.asarray(jax.device_get(value), dtype=np.uint8).reshape(-1) + try: + decoded = raw.tobytes().decode("ascii") + except UnicodeDecodeError as exc: + raise ValueError(f"{name} is not ASCII") from exc + return _identifier(decoded, name) + + +def _path_bytes(value: Path, name: str) -> jax.Array: + parsed = _bound_regular_file(str(value), name) + return jax.numpy.asarray(np.frombuffer(str(parsed).encode("utf-8"), dtype=np.uint8)) + + +def _decode_path(value: Any, name: str) -> str: + raw = np.asarray(jax.device_get(value), dtype=np.uint8).reshape(-1) + try: + decoded = raw.tobytes().decode("utf-8") + except UnicodeDecodeError as exc: + raise ValueError(f"{name} is not UTF-8") from exc + return str(_bound_regular_file(decoded, name)) + + +def _sample_identity(value: Any, name: str) -> str: + return str(_sha256(value, name)) + + +def _bound_regular_file(value: Any, name: str) -> Path: + if not isinstance(value, str) or not value or any(character in value for character in "\r\n\0\\"): + raise ValueError(f"{name} must be a normalized absolute file path") + pure = PurePosixPath(value) + if not pure.is_absolute() or any(part in {"", ".", ".."} for part in pure.parts) or pure.as_posix() != value: + raise ValueError(f"{name} must be a normalized absolute file path") + path = Path(value) + if path.is_symlink() or not path.is_file() or path.resolve() != path: + raise ValueError(f"{name} must name a real canonical regular file") + return path + + +def _canonical_json(value: Mapping[str, Any]) -> bytes: + return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode() + + +def _pairs_no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate JSON key in arm manifest: {key}") + result[key] = value + return result + + +def _gpu_class_from_sku(value: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise ValueError("arm.gpu_sku must be a non-empty string") + sku = value.lower().replace("-", "_") + if "h200" in sku: + return "h200" + if "h100" in sku and "80" in sku: + return "h100_80g" + if "a100" in sku and "80" in sku: + return "a100_80g" + if "a100" in sku and "40" in sku: + return "a100_40g" + raise ValueError(f"unsupported arm gpu_sku: {value!r}") + + +def _write_atomic_json(path: Path, value: Mapping[str, Any], *, refuse_existing: bool = True) -> None: + payload = _canonical_json(value) + path.parent.mkdir(parents=True, exist_ok=True) + if path.exists() or path.is_symlink(): + if refuse_existing or path.is_symlink() or not path.is_file() or path.read_bytes() != payload: + raise ValueError(f"refusing to replace existing JSON contract: {path}") + return + descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def validate_phase_a_topology( + *, + gpu_class: str, + world_size: int, + local_device_count: int, + process_count: int, + fsdp_devices: int, + batch_size: int, + device_kinds: tuple[str, ...], +) -> None: + if gpu_class not in SUPPORTED_GPU_CLASSES: + raise ValueError(f"unsupported Phase-A GPU class: {gpu_class!r}") + if (world_size, local_device_count, process_count, fsdp_devices) != (8, 8, 1, 8): + raise ValueError( + "Phase-A full state requires exactly one process and eight local/global FSDP devices; " + f"got world={world_size} local={local_device_count} process={process_count} fsdp={fsdp_devices}" + ) + if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size <= 0 or batch_size % 4: + raise ValueError("Phase-A global batch must be a positive integer divisible by four tasks") + if len(device_kinds) != 8: + raise ValueError("Phase-A topology must describe exactly eight device kinds") + family = "H200" if gpu_class == "h200" else "H100" if gpu_class == "h100_80g" else "A100" + if any(family not in kind.upper() for kind in device_kinds): + raise ValueError(f"Phase-A runtime device family differs from requested {gpu_class}") + + +def initialize_phase_a_checkpoint_dir( + checkpoint_dir: epath.Path | str, + *, + overwrite: bool, + resume: bool, + launch_kind: str, +) -> tuple[ocp.CheckpointManager, bool]: + """Create a manager retaining the latest two plus launch-kind milestones.""" + + retention_policy = functools.partial(is_phase_a_retained_checkpoint, launch_kind=launch_kind) + # Reject an invalid launch kind before overwrite can mutate the checkpoint root. + retention_policy(0) + checkpoint_dir = epath.Path(checkpoint_dir).resolve() + resuming = False + if checkpoint_dir.exists(): + if overwrite: + checkpoint_dir.rmtree() + checkpoint_dir.mkdir(parents=True, exist_ok=True) + logging.info("Wiped Phase-A checkpoint directory %s", checkpoint_dir) + elif resume: + discovery = discover_checkpoints(Path(checkpoint_dir)) + if discovery.rejected: + details = ", ".join(f"{name}: {reason}" for name, reason in sorted(discovery.rejected.items())) + raise ValueError( + "Phase-A resume is blocked by unresolved checkpoint-like paths; " + "move them to an explicit recovery/abandoned root before retrying: " + f"{details}" + ) + resuming = discovery.selected is not None + if not resuming: + logging.info("Phase-A checkpoint root contains no finalized checkpoint") + else: + raise FileExistsError(f"Checkpoint directory {checkpoint_dir} already exists. Use resume to continue it.") + checkpoint_dir.mkdir(parents=True, exist_ok=True) + manager = ocp.CheckpointManager( + checkpoint_dir, + item_handlers={ + "assets": _checkpoints.CallbackHandler(), + "params": ocp.PyTreeCheckpointHandler(), + "resume_state": ocp.PyTreeCheckpointHandler(), + }, + options=ocp.CheckpointManagerOptions( + max_to_keep=2, + should_keep_fn=retention_policy, + create=False, + async_options=ocp.AsyncOptions(timeout_secs=7_200), + ), + ) + return manager, resuming + + +@dataclasses.dataclass(frozen=True) +class PhaseAContract: + launch_kind: str + experiment: str + job: str + run_id: str + generation: int + gpu_class: str + checkpoint_root: Path + interface_commit: str + code_commit: str + config_sha256: str + dataset_sha256: str + cohort_sha256: str + sidecar_sha256: str + feature_sha256: str + source_metadata_sha256: str + source_digest_sha256: str + artifact_identity_sha256: str + artifact_hashes_sha256: str + replacement_manifest_sha256: str + best_visible_manifest_sha256: str + sample_order_path: Path + sample_order_manifest_sha256: str + sample_order_sha256: str + training_manifest_kind: str + training_manifest_sha256: str + overlay_sha256: str + runtime_profile_id: str + runtime_candidate_id: str + runtime_policy_sha256: str + runtime_plan_sha256: str + runtime_matrix_sha256: str + runtime_calibration_sha256: str + optimizer_sha256: str + learning_rate_schedule_sha256: str + global_batch_size: int + micro_batch_per_device: int + gradient_accumulation_steps: int + dataloader_workers: int + prefetch_factor: int + xla_preallocate: bool + xla_memory_fraction: str + nccl_collective_channel_cap: int + nccl_p2p_channel_cap: int + xla_flags: str + runtime_checkpoint_interval: int + parent_metadata_sha256: str | None + continuity_mode: str + continuity_request_id: str + watch_state_dir: Path + continuity_path: Path + metrics_path: Path + + @classmethod + def from_environment(cls, config: Any) -> PhaseAContract: + launch_kind = os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND", "") + if launch_kind not in {"formal", "sku_smoke"}: + raise ValueError("PICMEM_PHASE_A_LAUNCH_KIND must be formal or sku_smoke") + gpu_class = os.environ.get("PICMEM_CHECKPOINT_GPU_CLASS", "") + global_batch_size = _natural(os.environ.get("BATCH_SIZE", ""), "BATCH_SIZE") + if global_batch_size <= 0: + raise ValueError("BATCH_SIZE must be positive") + devices = tuple(jax.devices()) + validate_phase_a_topology( + gpu_class=gpu_class, + world_size=jax.device_count(), + local_device_count=jax.local_device_count(), + process_count=jax.process_count(), + fsdp_devices=int(config.fsdp_devices), + batch_size=global_batch_size, + device_kinds=tuple(str(device.device_kind) for device in devices), + ) + checkpoint_root = Path(os.environ.get("PICMEM_CHECKPOINT_ROOT", "")).expanduser().resolve() + if checkpoint_root != Path(config.checkpoint_dir).resolve(): + raise ValueError("PICMEM_CHECKPOINT_ROOT differs from TrainConfig.checkpoint_dir") + experiment = _identifier(os.environ.get("PICMEM_CHECKPOINT_EXPERIMENT"), "experiment") + if experiment != config.exp_name: + raise ValueError("checkpoint experiment differs from TrainConfig.exp_name") + generation = _natural(os.environ.get("PICMEM_CHECKPOINT_GENERATION", ""), "generation") + mode = os.environ.get("PICMEM_CONTINUITY_MODE", "") + parent = _sha256( + os.environ.get("PICMEM_PARENT_METADATA_SHA256"), + "PICMEM_PARENT_METADATA_SHA256", + nullable=True, + ) + if generation == 0: + if mode != "initial" or parent is not None: + raise ValueError("generation zero must be an initial launch without a checkpoint parent") + elif mode == ContinuityMode.CHECKPOINT_RESUME.value: + if parent is None: + raise ValueError("checkpoint_resume requires its exact parent metadata SHA-256") + elif mode == ContinuityMode.RESTART_ZERO.value: + if parent is not None: + raise ValueError("restart_zero must not name a checkpoint parent") + else: + raise ValueError("nonzero launcher generation has an unsupported continuity mode") + watch_state_dir = Path(os.environ.get("PICMEM_WATCH_STATE_DIR", "")).expanduser().resolve() + continuity_request_id = _identifier( + os.environ.get("PICMEM_CONTINUITY_REQUEST_ID"), + "PICMEM_CONTINUITY_REQUEST_ID", + ) + if mode != "initial": + _sha256(continuity_request_id, "PICMEM_CONTINUITY_REQUEST_ID") + continuity_path = Path(os.environ.get("PICMEM_CONTINUITY_PATH", "")).expanduser().resolve() + if continuity_path != watch_state_dir / f"continuity-{continuity_request_id}.json": + raise ValueError("PICMEM_CONTINUITY_PATH is not request-bound to the watchdog state directory") + metrics_path = Path(os.environ.get("PICMEM_METRICS_PATH", "")).expanduser().resolve() + expected_suffix = ("attempts", f"generation-{generation}", "metrics.tsv") + if tuple(metrics_path.parts[-3:]) != expected_suffix: + raise ValueError("PICMEM_METRICS_PATH is not generation-specific") + if config.metrics_path is None or metrics_path != Path(config.metrics_path).expanduser().resolve(): + raise ValueError("PICMEM_METRICS_PATH differs from TrainConfig.metrics_path") + contract = cls( + launch_kind=launch_kind, + experiment=experiment, + job=_identifier(os.environ.get("PICMEM_CHECKPOINT_JOB"), "job"), + run_id=_identifier(os.environ.get("PICMEM_CHECKPOINT_RUN_ID"), "run_id"), + generation=generation, + gpu_class=gpu_class, + checkpoint_root=checkpoint_root, + interface_commit=_commit(os.environ.get("PICMEM_INTERFACE_COMMIT"), "PICMEM_INTERFACE_COMMIT"), + code_commit=_commit(os.environ.get("PICMEM_CODE_COMMIT"), "PICMEM_CODE_COMMIT"), + config_sha256=str(_sha256(os.environ.get("PICMEM_CONFIG_SHA256"), "PICMEM_CONFIG_SHA256")), + dataset_sha256=str(_sha256(os.environ.get("PICMEM_DATASET_SHA256"), "PICMEM_DATASET_SHA256")), + cohort_sha256=str(_sha256(os.environ.get("PICMEM_COHORT_SHA256"), "PICMEM_COHORT_SHA256")), + sidecar_sha256=str(_sha256(os.environ.get("PICMEM_SIDECAR_SHA256"), "PICMEM_SIDECAR_SHA256")), + feature_sha256=str(_sha256(os.environ.get("PICMEM_FEATURE_SHA256"), "PICMEM_FEATURE_SHA256")), + source_metadata_sha256=str( + _sha256(os.environ.get("PICMEM_SOURCE_METADATA_SHA256"), "PICMEM_SOURCE_METADATA_SHA256") + ), + source_digest_sha256=str( + _sha256(os.environ.get("PICMEM_SOURCE_DIGEST_SHA256"), "PICMEM_SOURCE_DIGEST_SHA256") + ), + artifact_identity_sha256=str( + _sha256(os.environ.get("PICMEM_ARTIFACT_IDENTITY_SHA256"), "PICMEM_ARTIFACT_IDENTITY_SHA256") + ), + artifact_hashes_sha256=str( + _sha256(os.environ.get("PICMEM_ARTIFACT_HASHES_SHA256"), "PICMEM_ARTIFACT_HASHES_SHA256") + ), + replacement_manifest_sha256=str( + _sha256( + os.environ.get("PICMEM_REPLACEMENT_MANIFEST_SHA256"), + "PICMEM_REPLACEMENT_MANIFEST_SHA256", + ) + ), + best_visible_manifest_sha256=str( + _sha256( + os.environ.get("PICMEM_BEST_VISIBLE_MANIFEST_SHA256"), + "PICMEM_BEST_VISIBLE_MANIFEST_SHA256", + ) + ), + sample_order_path=_bound_regular_file( + os.environ.get("PICMEM_SAMPLE_ORDER_MANIFEST"), + "PICMEM_SAMPLE_ORDER_MANIFEST", + ), + sample_order_manifest_sha256=str( + _sha256( + os.environ.get("PICMEM_SAMPLE_ORDER_MANIFEST_SHA256"), + "PICMEM_SAMPLE_ORDER_MANIFEST_SHA256", + ) + ), + sample_order_sha256=str( + _sha256(os.environ.get("PICMEM_SAMPLE_ORDER_SHA256"), "PICMEM_SAMPLE_ORDER_SHA256") + ), + training_manifest_kind=_identifier( + os.environ.get("PICMEM_TRAINING_MANIFEST_KIND"), + "PICMEM_TRAINING_MANIFEST_KIND", + ), + training_manifest_sha256=str( + _sha256(_training_manifest_sha256_from_environment(), "training manifest SHA-256") + ), + overlay_sha256=str(_sha256(os.environ.get("PICMEM_OVERLAY_SHA256"), "PICMEM_OVERLAY_SHA256")), + runtime_profile_id=_identifier( + os.environ.get("PICMEM_RUNTIME_PROFILE_ID"), + "PICMEM_RUNTIME_PROFILE_ID", + ), + runtime_candidate_id=_identifier( + os.environ.get("PICMEM_RUNTIME_CANDIDATE_ID"), + "PICMEM_RUNTIME_CANDIDATE_ID", + ), + runtime_policy_sha256=str( + _sha256(os.environ.get("PICMEM_RUNTIME_POLICY_SHA256"), "PICMEM_RUNTIME_POLICY_SHA256") + ), + runtime_plan_sha256=str( + _sha256(os.environ.get("PICMEM_RUNTIME_PLAN_SHA256"), "PICMEM_RUNTIME_PLAN_SHA256") + ), + runtime_matrix_sha256=str( + _sha256(os.environ.get("PICMEM_RUNTIME_MATRIX_SHA256"), "PICMEM_RUNTIME_MATRIX_SHA256") + ), + runtime_calibration_sha256=str( + _sha256( + os.environ.get("PICMEM_RUNTIME_CALIBRATION_SHA256"), + "PICMEM_RUNTIME_CALIBRATION_SHA256", + ) + ), + optimizer_sha256=str(_sha256(os.environ.get("PICMEM_OPTIMIZER_SHA256"), "PICMEM_OPTIMIZER_SHA256")), + learning_rate_schedule_sha256=str( + _sha256(os.environ.get("PICMEM_LR_SCHEDULE_SHA256"), "PICMEM_LR_SCHEDULE_SHA256") + ), + global_batch_size=global_batch_size, + micro_batch_per_device=_natural( + os.environ.get("MICRO_BATCH_PER_DEVICE", ""), + "MICRO_BATCH_PER_DEVICE", + ), + gradient_accumulation_steps=_natural( + os.environ.get("GRADIENT_ACCUMULATION_STEPS", ""), + "GRADIENT_ACCUMULATION_STEPS", + ), + dataloader_workers=_natural(os.environ.get("NUM_WORKERS", ""), "NUM_WORKERS"), + prefetch_factor=_natural(os.environ.get("PREFETCH_FACTOR", ""), "PREFETCH_FACTOR"), + xla_preallocate=_runtime_true( + os.environ.get("XLA_PYTHON_CLIENT_PREALLOCATE"), + "XLA_PYTHON_CLIENT_PREALLOCATE", + ), + xla_memory_fraction=_runtime_fraction( + os.environ.get("XLA_PYTHON_CLIENT_MEM_FRACTION"), + "XLA_PYTHON_CLIENT_MEM_FRACTION", + ), + nccl_collective_channel_cap=_natural( + os.environ.get("NCCL_MAX_NCHANNELS", ""), + "NCCL_MAX_NCHANNELS", + ), + nccl_p2p_channel_cap=_natural( + os.environ.get("PICMEM_XLA_P2P_MAX_NCHANNELS", ""), + "PICMEM_XLA_P2P_MAX_NCHANNELS", + ), + xla_flags=os.environ.get("XLA_FLAGS", ""), + runtime_checkpoint_interval=_natural(os.environ.get("SAVE_INTERVAL", ""), "SAVE_INTERVAL"), + parent_metadata_sha256=parent, + continuity_mode=mode, + continuity_request_id=continuity_request_id, + watch_state_dir=watch_state_dir, + continuity_path=continuity_path, + metrics_path=metrics_path, + ) + if contract.micro_batch_per_device <= 0 or contract.gradient_accumulation_steps != 1: + raise ValueError("Phase-A runtime requires positive micro batch and accumulation exactly 1") + if contract.global_batch_size != int(config.batch_size): + raise ValueError("runtime global batch differs from TrainConfig.batch_size") + if 8 * contract.micro_batch_per_device * contract.gradient_accumulation_steps != contract.global_batch_size: + raise ValueError("runtime batch geometry differs from TrainConfig.batch_size") + if contract.dataloader_workers != int(config.num_workers): + raise ValueError("runtime dataloader workers differ from TrainConfig.num_workers") + if contract.runtime_checkpoint_interval != int(config.save_interval): + raise ValueError("runtime checkpoint interval differs from TrainConfig.save_interval") + if ( + contract.dataloader_workers <= 0 + or contract.prefetch_factor <= 0 + or contract.nccl_collective_channel_cap <= 0 + or contract.nccl_p2p_channel_cap <= 0 + ): + raise ValueError("Phase-A runtime requires positive workers and prefetch") + expected_p2p_flag = f"--xla_gpu_nccl_p2p_max_nchannels={contract.nccl_p2p_channel_cap}" + if not contract.xla_flags or any(character in contract.xla_flags for character in "\t\r\n"): + raise ValueError("runtime XLA_FLAGS must be non-empty single-line text") + if contract.xla_flags.split().count(expected_p2p_flag) != 1: + raise ValueError("runtime XLA_FLAGS does not contain the exact reviewed P2P channel cap") + zero = "0" * 64 + if launch_kind == "formal": + if zero in { + contract.runtime_matrix_sha256, + contract.runtime_calibration_sha256, + contract.optimizer_sha256, + contract.learning_rate_schedule_sha256, + }: + raise ValueError("formal runtime lineage cannot use calibration/smoke sentinels") + if contract.optimizer_sha256 != _repr_sha256(config.optimizer): + raise ValueError("formal optimizer config differs from PICMEM_OPTIMIZER_SHA256") + if contract.learning_rate_schedule_sha256 != _repr_sha256(config.lr_schedule): + raise ValueError("formal LR schedule differs from PICMEM_LR_SCHEDULE_SHA256") + elif any( + value != zero + for value in ( + contract.runtime_matrix_sha256, + contract.runtime_calibration_sha256, + contract.optimizer_sha256, + contract.learning_rate_schedule_sha256, + ) + ): + raise ValueError("SKU smoke runtime lineage must use explicit zero-hash sentinels") + _validate_bound_training_manifest(contract, config) + return contract + + def stable_json(self, config: Any) -> dict[str, Any]: + return { + "schema_version": PHASE_A_CONTRACT_SCHEMA, + "launch_kind": self.launch_kind, + "run": {"experiment": self.experiment, "job": self.job, "run_id": self.run_id}, + "topology": { + "gpu_class": self.gpu_class, + "world_size": 8, + "fsdp_devices": 8, + "global_batch_size": self.global_batch_size, + "micro_batch_per_device": self.micro_batch_per_device, + "gradient_accumulation_steps": self.gradient_accumulation_steps, + }, + "runtime": { + "profile_id": self.runtime_profile_id, + "candidate_id": self.runtime_candidate_id, + "policy_sha256": self.runtime_policy_sha256, + "plan_sha256": self.runtime_plan_sha256, + "matrix_sha256": self.runtime_matrix_sha256, + "calibration_sha256": self.runtime_calibration_sha256, + "optimizer_sha256": self.optimizer_sha256, + "learning_rate_schedule_sha256": self.learning_rate_schedule_sha256, + "dataloader_workers": self.dataloader_workers, + "prefetch_factor": self.prefetch_factor, + "xla_preallocate": self.xla_preallocate, + "xla_memory_fraction": self.xla_memory_fraction, + "nccl_collective_channel_cap": self.nccl_collective_channel_cap, + "nccl_p2p_channel_cap": self.nccl_p2p_channel_cap, + "xla_flags": self.xla_flags, + "checkpoint_interval": self.runtime_checkpoint_interval, + }, + "lineage": { + "interface_commit": self.interface_commit, + "code_commit": self.code_commit, + "config_sha256": self.config_sha256, + "dataset_sha256": self.dataset_sha256, + "cohort_sha256": self.cohort_sha256, + "sidecar_sha256": self.sidecar_sha256, + "feature_sha256": self.feature_sha256, + "source_metadata_sha256": self.source_metadata_sha256, + "source_digest_sha256": self.source_digest_sha256, + "artifact_identity_sha256": self.artifact_identity_sha256, + "artifact_hashes_sha256": self.artifact_hashes_sha256, + "replacement_manifest_sha256": self.replacement_manifest_sha256, + "best_visible_manifest_sha256": self.best_visible_manifest_sha256, + "sample_order_path": str(self.sample_order_path), + "sample_order_manifest_sha256": self.sample_order_manifest_sha256, + "sample_order_sha256": self.sample_order_sha256, + "training_manifest_kind": self.training_manifest_kind, + "training_manifest_sha256": self.training_manifest_sha256, + "overlay_sha256": self.overlay_sha256, + }, + "optimizer": repr(config.optimizer), + "lr_schedule": repr(config.lr_schedule), + "ema_decay": config.ema_decay, + "seed": int(config.seed), + "sampler_seed": int(config.sampler_seed if config.sampler_seed is not None else config.seed), + } + + def checkpoint_metadata(self, step: int) -> CheckpointMetadata: + from picmem.ops.cadence import GpuClass + + return CheckpointMetadata( + experiment=self.experiment, + job=self.job, + run_id=self.run_id, + step=step, + generation=self.generation, + gpu_class=GpuClass(self.gpu_class), + world_size=8, + fsdp_devices=8, + launch_kind=self.launch_kind, + training_manifest_kind=self.training_manifest_kind, + training_manifest_sha256=self.training_manifest_sha256, + runtime_profile_id=self.runtime_profile_id, + runtime_candidate_id=self.runtime_candidate_id, + runtime_policy_sha256=self.runtime_policy_sha256, + runtime_plan_sha256=self.runtime_plan_sha256, + runtime_matrix_sha256=self.runtime_matrix_sha256, + runtime_calibration_sha256=self.runtime_calibration_sha256, + optimizer_sha256=self.optimizer_sha256, + learning_rate_schedule_sha256=self.learning_rate_schedule_sha256, + global_batch_size=self.global_batch_size, + micro_batch_per_device=self.micro_batch_per_device, + gradient_accumulation_steps=self.gradient_accumulation_steps, + dataloader_workers=self.dataloader_workers, + prefetch_factor=self.prefetch_factor, + xla_preallocate=self.xla_preallocate, + xla_memory_fraction=self.xla_memory_fraction, + nccl_collective_channel_cap=self.nccl_collective_channel_cap, + nccl_p2p_channel_cap=self.nccl_p2p_channel_cap, + xla_flags=self.xla_flags, + checkpoint_interval=self.runtime_checkpoint_interval, + interface_commit=self.interface_commit, + code_commit=self.code_commit, + config_sha256=self.config_sha256, + dataset_sha256=self.dataset_sha256, + cohort_sha256=self.cohort_sha256, + sidecar_sha256=self.sidecar_sha256, + feature_sha256=self.feature_sha256, + source_metadata_sha256=self.source_metadata_sha256, + source_digest_sha256=self.source_digest_sha256, + artifact_identity_sha256=self.artifact_identity_sha256, + artifact_hashes_sha256=self.artifact_hashes_sha256, + replacement_manifest_sha256=self.replacement_manifest_sha256, + best_visible_manifest_sha256=self.best_visible_manifest_sha256, + sample_order_path=str(self.sample_order_path), + sample_order_manifest_sha256=self.sample_order_manifest_sha256, + sample_order_sha256=self.sample_order_sha256, + overlay_sha256=self.overlay_sha256, + parent_metadata_sha256=self.parent_metadata_sha256, + ) + + +def _training_manifest_environment() -> tuple[str, str, str]: + kind = os.environ.get("PICMEM_TRAINING_MANIFEST_KIND", "") + expected = { + "arm_v3": ("PICMEM_ARM_MANIFEST", "PICMEM_ARM_MANIFEST_SHA256", "formal"), + "sku_calibration_v1": ( + "PICMEM_CALIBRATION_MANIFEST", + "PICMEM_CALIBRATION_MANIFEST_SHA256", + "sku_smoke", + ), + } + if kind not in expected: + raise ValueError("PICMEM_TRAINING_MANIFEST_KIND must be arm_v3 or sku_calibration_v1") + path_name, sha_name, launch_kind = expected[kind] + if os.environ.get("PICMEM_PHASE_A_LAUNCH_KIND") != launch_kind: + raise ValueError("training manifest kind disagrees with PICMEM_PHASE_A_LAUNCH_KIND") + forbidden = ( + ("PICMEM_CALIBRATION_MANIFEST", "PICMEM_CALIBRATION_MANIFEST_SHA256") + if kind == "arm_v3" + else ("PICMEM_ARM_MANIFEST", "PICMEM_ARM_MANIFEST_SHA256") + ) + if any(os.environ.get(name) for name in forbidden): + raise ValueError("process environment ambiguously carries both training manifest kinds") + return kind, path_name, sha_name + + +def _training_manifest_sha256_from_environment() -> str: + _, _, sha_name = _training_manifest_environment() + return os.environ.get(sha_name, "") + + +def _load_bound_training_manifest() -> ArmManifest | SkuCalibrationManifest: + kind, path_name, sha_name = _training_manifest_environment() + raw_path = os.environ.get(path_name, "") + unresolved = Path(raw_path).expanduser() + if not raw_path or unresolved.is_symlink() or not unresolved.is_file(): + raise ValueError(f"{path_name} must name a real regular file") + manifest_path = unresolved.resolve() + expected_sha256 = str(_sha256(os.environ.get(sha_name), sha_name)) + if kind == "sku_calibration_v1": + try: + return load_calibration_manifest( + manifest_path, + expected_sha256=expected_sha256, + ).manifest + except CalibrationManifestError as exc: + raise ValueError(f"{path_name} is not a trusted SKU calibration manifest") from exc + raw = manifest_path.read_bytes() + if hashlib.sha256(raw).hexdigest() != expected_sha256: + raise ValueError(f"{path_name} content differs from {sha_name}") + try: + value = json.loads(raw, object_pairs_hook=_pairs_no_duplicates) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f"{path_name} is not valid duplicate-free JSON") from exc + return ArmManifest.from_mapping(value) + + +def _resume_lineage() -> str: + resume_lineage = os.environ.get("PICMEM_RESUME_LINEAGE", "") + if not resume_lineage: + raise ValueError("PICMEM_RESUME_LINEAGE must be non-empty") + normalized = PurePosixPath(resume_lineage) + if ( + normalized.is_absolute() + or not normalized.parts + or any(part in {"", ".", ".."} for part in normalized.parts) + or normalized.as_posix() != resume_lineage + ): + raise ValueError("PICMEM_RESUME_LINEAGE must be a normalized safe relative path") + return resume_lineage + + +def _factor_environment() -> dict[str, str | None]: + return { + "selection_mode": os.environ.get("PICMEM_PHASE_A_SELECTION_MODE"), + "metadata_mode": os.environ.get("PICMEM_PHASE_A_METADATA_MODE"), + "reader_mode": os.environ.get("PICMEM_PHASE_A_READER_MODE"), + "manager_mode": os.environ.get("PICMEM_PHASE_A_MANAGER_MODE"), + } + + +def _validate_bound_arm(contract: PhaseAContract, config: Any, arm: ArmManifest | None = None) -> None: + """Re-validate the exact formal arm inside the training process trust boundary.""" + + loaded = _load_bound_training_manifest() if arm is None else arm + if not isinstance(loaded, ArmManifest): + raise ValueError("formal arm validation received a non-arm training manifest") + arm = loaded + if contract.training_manifest_kind != "arm_v3": + raise ValueError("formal checkpoint contract does not bind arm_v3") + if contract.training_manifest_sha256 != os.environ.get("PICMEM_ARM_MANIFEST_SHA256"): + raise ValueError("checkpoint contract and process arm-manifest hashes differ") + process_source_digest_sha256 = str( + _sha256( + os.environ.get("PICMEM_SOURCE_DIGEST_SHA256"), + "PICMEM_SOURCE_DIGEST_SHA256", + ) + ) + expected_source_digest_sha256 = str( + _sha256( + RUN084_BUILD_C_LINEAGE["source_digest_manifest_sha256"], + "RUN084_BUILD_C_LINEAGE.source_digest_manifest_sha256", + ) + ) + if contract.source_digest_sha256 != process_source_digest_sha256: + raise ValueError("checkpoint contract and process source-digest hashes differ") + if process_source_digest_sha256 != expected_source_digest_sha256: + raise ValueError("formal training requires the exact verified Run084-v2 build_c source digest") + resume_lineage = _resume_lineage() + + factors = _factor_environment() + expected = { + "arm_id": contract.job, + "parent_commit": contract.code_commit, + "parent_tree": _commit(os.environ.get("PICMEM_CODE_TREE"), "PICMEM_CODE_TREE"), + "host_overlay_sha256": contract.overlay_sha256, + "dataset_sha256": contract.dataset_sha256, + "sidecar_sha256": contract.sidecar_sha256, + "feature_sha256": contract.feature_sha256, + "source_metadata_sha256": contract.source_metadata_sha256, + "artifact_identity_sha256": contract.artifact_identity_sha256, + "artifact_hashes_sha256": contract.artifact_hashes_sha256, + "replacement_manifest_sha256": contract.replacement_manifest_sha256, + "best_visible_manifest_sha256": contract.best_visible_manifest_sha256, + "sample_order_manifest_sha256": contract.sample_order_manifest_sha256, + "sample_order_sha256": contract.sample_order_sha256, + "evaluation_cohort_sha256": contract.cohort_sha256, + "resume_lineage": resume_lineage, + "global_batch": contract.global_batch_size, + "seed": _sampler_natural(config.seed, "config.seed"), + "checkpoint_interval": _sampler_natural(config.save_interval, "config.save_interval"), + } + drift = [name for name, expected_value in expected.items() if getattr(arm, name) != expected_value] + drift.extend(name for name, expected_value in factors.items() if getattr(arm, name).value != expected_value) + if _gpu_class_from_sku(arm.gpu_sku) != contract.gpu_class: + drift.append("gpu_sku") + sampler_seed = config.sampler_seed if config.sampler_seed is not None else config.seed + if _sampler_natural(sampler_seed, "config.sampler_seed") != arm.seed: + drift.append("sampler_seed") + if drift: + raise ValueError(f"training-process ArmManifest immutable lineage drift: {sorted(set(drift))}") + + +def _validate_bound_calibration( + contract: PhaseAContract, + config: Any, + calibration: SkuCalibrationManifest | None = None, +) -> None: + loaded = _load_bound_training_manifest() if calibration is None else calibration + if not isinstance(loaded, SkuCalibrationManifest): + raise ValueError("SKU calibration validation received a formal ArmManifest") + calibration = loaded + if contract.training_manifest_kind != "sku_calibration_v1": + raise ValueError("SKU calibration checkpoint contract does not bind sku_calibration_v1") + if contract.training_manifest_sha256 != os.environ.get("PICMEM_CALIBRATION_MANIFEST_SHA256"): + raise ValueError("checkpoint contract and process calibration-manifest hashes differ") + + lineage = calibration.lineage + sample_order = calibration.sample_order + runtime = calibration.runtime + factors = _factor_environment() + expected_lineage = { + "parent_commit": contract.code_commit, + "parent_tree": _commit(os.environ.get("PICMEM_CODE_TREE"), "PICMEM_CODE_TREE"), + "host_overlay_sha256": contract.overlay_sha256, + "artifact_schema_version": os.environ.get("PICMEM_ARTIFACT_SCHEMA_VERSION"), + "dataset_version": os.environ.get("PICMEM_DATASET_VERSION"), + "artifact_hashes_sha256": contract.artifact_hashes_sha256, + "dataset_sha256": contract.dataset_sha256, + "sidecar_sha256": contract.sidecar_sha256, + "feature_sha256": contract.feature_sha256, + "source_metadata_sha256": contract.source_metadata_sha256, + "source_digest_manifest_sha256": contract.source_digest_sha256, + "source_digest_tree_sha256": os.environ.get("PICMEM_SOURCE_DIGEST_TREE_SHA256"), + "source_digest_rows": _natural( + os.environ.get("PICMEM_SOURCE_DIGEST_ROWS", ""), + "PICMEM_SOURCE_DIGEST_ROWS", + ), + "source_digest_bytes": _natural( + os.environ.get("PICMEM_SOURCE_DIGEST_BYTES", ""), + "PICMEM_SOURCE_DIGEST_BYTES", + ), + "artifact_identity_sha256": contract.artifact_identity_sha256, + "replacement_manifest_sha256": contract.replacement_manifest_sha256, + "best_visible_manifest_sha256": contract.best_visible_manifest_sha256, + "evaluation_cohort_sha256": contract.cohort_sha256, + } + expected_order = { + "dataset_sha256": contract.dataset_sha256, + "seed": _sampler_natural( + config.sampler_seed if config.sampler_seed is not None else config.seed, + "config.sampler_seed", + ), + "global_batch": contract.global_batch_size, + "manifest_path": str(contract.sample_order_path), + "manifest_sha256": contract.sample_order_manifest_sha256, + "sample_order_sha256": contract.sample_order_sha256, + } + expected_runtime = { + "gpu_count": 8, + "profile_id": contract.runtime_profile_id, + "candidate_id": contract.runtime_candidate_id, + "policy_sha256": contract.runtime_policy_sha256, + "plan_sha256": contract.runtime_plan_sha256, + "world_size": 8, + "global_batch": contract.global_batch_size, + "micro_batch_per_device": contract.micro_batch_per_device, + "gradient_accumulation_steps": contract.gradient_accumulation_steps, + "dataloader_workers": contract.dataloader_workers, + "prefetch_factor": contract.prefetch_factor, + "xla_preallocate": contract.xla_preallocate, + "xla_memory_fraction": contract.xla_memory_fraction, + "nccl_collective_channel_cap": contract.nccl_collective_channel_cap, + "nccl_p2p_channel_cap": contract.nccl_p2p_channel_cap, + "checkpoint_interval": contract.runtime_checkpoint_interval, + "train_steps": _sampler_natural(config.num_train_steps, "config.num_train_steps"), + } + expected_p2p = f"--xla_gpu_nccl_p2p_max_nchannels={contract.nccl_p2p_channel_cap}" + base_flags = tuple(flag for flag in contract.xla_flags.split() if flag != expected_p2p) + drift = [] + if calibration.calibration_id != contract.job: + drift.append("calibration_id") + if calibration.resume_lineage != _resume_lineage(): + drift.append("resume_lineage") + drift.extend( + f"lineage.{name}" + for name, expected_value in expected_lineage.items() + if getattr(lineage, name) != expected_value + ) + drift.extend( + f"sample_order.{name}" + for name, expected_value in expected_order.items() + if getattr(sample_order, name) != expected_value + ) + drift.extend( + f"runtime.{name}" + for name, expected_value in expected_runtime.items() + if str(getattr(runtime, name)) != str(expected_value) + ) + if runtime.xla_base_flags != base_flags: + drift.append("runtime.xla_base_flags") + if runtime.gpu_class.value != contract.gpu_class: + drift.append("runtime.gpu_class") + if _gpu_class_from_sku(runtime.gpu_sku) != contract.gpu_class: + drift.append("runtime.gpu_sku") + drift.extend( + f"factors.{name}" + for name, expected_value in factors.items() + if getattr(calibration.factors, name).value != expected_value + ) + if drift: + raise ValueError(f"training-process SKU calibration immutable lineage drift: {sorted(set(drift))}") + + +def _validate_bound_training_manifest(contract: PhaseAContract, config: Any) -> None: + manifest = _load_bound_training_manifest() + if contract.launch_kind == "formal": + if not isinstance(manifest, ArmManifest): + raise ValueError("formal launch requires an ArmManifest") + _validate_bound_arm(contract, config, manifest) + elif contract.launch_kind == "sku_smoke": + if not isinstance(manifest, SkuCalibrationManifest): + raise ValueError("SKU smoke requires a SkuCalibrationManifest") + _validate_bound_calibration(contract, config, manifest) + else: + raise ValueError("unsupported Phase-A training manifest launch kind") + + +def _validate_phase_a_factor_contract(frame_selection: Mapping[str, Any]) -> None: + """Require the resolved YAML, process environment, and arm to name one treatment.""" + + if frame_selection.get("require_explicit_factors") is not True: + raise ValueError("formal Phase-A YAML must require explicit factors") + manifest = _load_bound_training_manifest() + factor_source = manifest if isinstance(manifest, ArmManifest) else manifest.factors + names = { + "selection_mode": "PICMEM_PHASE_A_SELECTION_MODE", + "metadata_mode": "PICMEM_PHASE_A_METADATA_MODE", + "reader_mode": "PICMEM_PHASE_A_READER_MODE", + "manager_mode": "PICMEM_PHASE_A_MANAGER_MODE", + } + drift = [] + for name, environment_name in names.items(): + yaml_value = frame_selection.get(name) + environment_value = os.environ.get(environment_name) + manifest_value = getattr(factor_source, name).value + if not isinstance(yaml_value, str) or not yaml_value: + drift.append(f"yaml.{name}") + if not isinstance(environment_value, str) or not environment_value: + drift.append(f"environment.{name}") + if yaml_value != environment_value or yaml_value != manifest_value: + drift.append(name) + if drift: + raise ValueError(f"Phase-A manifest/environment/YAML factor drift: {sorted(set(drift))}") + + +class PhaseASampler(Protocol): + """Minimal checkpointable sampler interface consumed by the host runtime.""" + + seed: int + batch_size: int + num_batches: int + epoch: int + batch_cursor: int + + def state_dict(self) -> dict[str, Any]: ... + + def load_state_dict(self, state: Mapping[str, Any]) -> None: ... + + def mark_batch_consumed(self) -> None: ... + + def next_batch_sample_ids(self) -> tuple[str, ...]: ... + + def __iter__(self) -> Iterator[int]: ... + + def __len__(self) -> int: ... + + +class PhaseASmokeRandomSampler(torch.utils.data.Sampler[int]): + """Synthetic smoke-only sampler; formal loading never constructs this class.""" + + def __init__( + self, + dataset_size: int, + *, + batch_size: int, + seed: int, + epoch: int = 0, + batch_cursor: int = 0, + ) -> None: + if dataset_size < batch_size or batch_size <= 0: + raise ValueError("checkpointable sampler requires at least one positive full batch") + if seed < 0 or epoch < 0 or batch_cursor < 0: + raise ValueError("checkpointable sampler seed/position must be non-negative") + if seed > np.iinfo(np.uint64).max: + raise ValueError("checkpointable sampler seed must fit in uint64") + self.dataset_size = int(dataset_size) + self.batch_size = int(batch_size) + self.seed = int(seed) + self.num_batches = self.dataset_size // self.batch_size + self.epoch = int(epoch) + self.batch_cursor = 0 + self.set_position(epoch=epoch, batch_cursor=batch_cursor) + + def _order(self, epoch: int) -> np.ndarray: + sequence = np.random.SeedSequence([self.seed, int(epoch)]) + rng = np.random.default_rng(sequence) + return rng.permutation(self.dataset_size)[: self.num_batches * self.batch_size] + + def next_batch_sample_ids(self) -> tuple[str, ...]: + start = self.batch_cursor * self.batch_size + end = start + self.batch_size + return tuple( + hashlib.sha256(f"picmem-smoke-row:{int(value)}".encode("ascii")).hexdigest() + for value in self._order(self.epoch)[start:end] + ) + + def state_dict(self) -> dict[str, Any]: + return { + "schema_version": SMOKE_SAMPLER_SCHEMA, + "subset_manifest_sha256": SMOKE_SUBSET_SHA256, + "seed": self.seed, + "batch_size": self.batch_size, + "num_batches": self.num_batches, + "epoch": self.epoch, + "batch_cursor": self.batch_cursor, + "next_sample_ids": list(self.next_batch_sample_ids()), + } + + def load_state_dict(self, state: Mapping[str, Any]) -> None: + expected = { + "schema_version", + "subset_manifest_sha256", + "seed", + "batch_size", + "num_batches", + "epoch", + "batch_cursor", + "next_sample_ids", + } + if set(state) != expected: + raise ValueError("Phase-A smoke sampler state fields mismatch") + immutable = ( + state["schema_version"], + state["subset_manifest_sha256"], + state["seed"], + state["batch_size"], + state["num_batches"], + ) + expected_immutable = ( + SMOKE_SAMPLER_SCHEMA, + SMOKE_SUBSET_SHA256, + self.seed, + self.batch_size, + self.num_batches, + ) + if immutable != expected_immutable: + raise ValueError("Phase-A smoke sampler lineage mismatch") + self.set_position(epoch=int(state["epoch"]), batch_cursor=int(state["batch_cursor"])) + supplied = tuple( + _sample_identity(value, "smoke sampler next_sample_ids item") for value in state["next_sample_ids"] + ) + if supplied != self.next_batch_sample_ids(): + raise ValueError("Phase-A smoke sampler next sample IDs mismatch") + + def set_position(self, *, epoch: int, batch_cursor: int) -> None: + if epoch < 0 or not 0 <= batch_cursor < self.num_batches: + raise ValueError("Phase-A sampler position is outside the complete-batch epoch") + self.epoch = int(epoch) + self.batch_cursor = int(batch_cursor) + + def mark_batch_consumed(self) -> None: + cursor = self.batch_cursor + 1 + if cursor == self.num_batches: + self.epoch += 1 + cursor = 0 + self.batch_cursor = cursor + + def __iter__(self): + start = self.batch_cursor * self.batch_size + yield from (int(value) for value in self._order(self.epoch)[start:]) + + def __len__(self) -> int: + return (self.num_batches - self.batch_cursor) * self.batch_size + + +class PhaseADataLoader: + def __init__( + self, + data_config: Any, + data_loader: TorchDataLoader, + sampler: PhaseASampler, + sample_order: Mapping[str, Any], + ): + self._data_config = data_config + self._data_loader = data_loader + self.sampler = sampler + self._sample_order = dict(sample_order) + self.last_batch_task_counts: dict[str, int] = {} + + def data_config(self) -> Any: + return self._data_config + + def __iter__(self): + for batch in self._data_loader: + self._validate_sample_order_state(self.sampler.state_dict()) + result = HistAugObservation.from_dict(batch), batch["actions"] + self.sampler.mark_batch_consumed() + yield result + + def sampler_state_dict(self) -> dict[str, Any]: + state = self.sampler.state_dict() + self._validate_sample_order_state(state) + return state + + def load_sampler_state_dict(self, state: Mapping[str, Any]) -> None: + self.sampler.load_state_dict(state) + self._validate_sample_order_state(self.sampler.state_dict()) + + def _validate_sample_order_state( + self, + state: Mapping[str, Any], + *, + authoritative_step: int | None = None, + ) -> None: + parsed = _sampler_state(state) + step = parsed["epoch"] * parsed["num_batches"] + parsed["batch_cursor"] + if authoritative_step is not None and step != authoritative_step: + raise ValueError("Run084 sampler cursor differs from the authoritative global step") + train_steps = _sampler_natural(self._sample_order.get("train_steps"), "sample_order.train_steps") + if step > train_steps: + raise ValueError("Run084 sampler advanced beyond the frozen 80k sample order") + sample_ids = parsed["next_sample_ids"] + if step < train_steps: + batch_digests = self._sample_order.get("batch_sha256") + if not isinstance(batch_digests, list) or len(batch_digests) != train_steps: + raise ValueError("Run084 sample-order batch digest geometry drift") + raw = b"".join(bytes.fromhex(identity) for identity in sample_ids) + if hashlib.sha256(raw).hexdigest() != batch_digests[step]: + raise ValueError("live Run084 sampler batch differs from the frozen sample order") + else: + probes = self._sample_order.get("probe_batches") + expected = probes.get(str(step)) if isinstance(probes, Mapping) else None + if expected != sample_ids: + raise ValueError("final Run084 sampler cursor differs from the frozen next-batch probe") + + +def create_phase_a_data_loader( + dataset_path: str, + data_config: Any, + history_config: str, + action_horizon: int, + batch_size: int, + *, + sharding: jax.sharding.Sharding, + num_workers: int, + prefetch_factor: int, + seed: int, + subset_manifest_sha256: str, + sidecar_sha256: str, + sample_order_path: str | Path, + sample_order_manifest_sha256: str, + sample_order_sha256: str, +) -> PhaseADataLoader: + history = get_history_config(history_config) + frame_selection = history.perceptual_memory.get("frame_selection", {}) + if ( + history.representation_type != "perceptual" + or history.perceptual_memory.type != "frame_sampling" + or frame_selection.get("type") != "picmem_phase_a" + ): + raise ValueError("Phase-A full-state loader requires the reviewed picmem_phase_a frame selector") + _validate_phase_a_factor_contract(frame_selection) + if jax.process_count() != 1: + raise ValueError("Phase-A checkpointable data loading supports exactly one JAX process") + if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size <= 0 or batch_size % 4: + raise ValueError("formal Phase-A loader requires a positive four-task-balanced global batch") + from picmem.provenance.frozen_artifact import Run084SubsetIndex + from picmem.sampling.run084_sample_order import RUN084_FORMAL_TRAIN_STEPS, load_run084_sample_order + from picmem.sampling.run084_sampler import Run084TaskBalancedSampler + + subset = Run084SubsetIndex.load( + Path(dataset_path) / "meta" / "picmem_subset_manifest.json", + expected_sha256=str(_sha256(subset_manifest_sha256, "subset_manifest_sha256")), + ) + if subset.sidecar_tree_sha256 != _sha256(sidecar_sha256, "sidecar_sha256"): + raise ValueError("Run084 subset sidecar tree differs from formal lineage") + raw_dataset = RoboMMEDataset( + dataset_path=dataset_path, + data_config=data_config, + history_config=history, + action_horizon=action_horizon, + ) + dataset = transform_dataset(raw_dataset, data_config) + if len(dataset) != len(subset.records): + raise ValueError("host dataset length differs from the frozen Run084 subset") + sampler = Run084TaskBalancedSampler( + subset, + batch_size=batch_size, + seed=seed, + auto_advance=False, + ) + sample_order = load_run084_sample_order( + sample_order_path, + expected_manifest_sha256=str(_sha256(sample_order_manifest_sha256, "sample_order_manifest_sha256")), + expected_sample_order_sha256=str(_sha256(sample_order_sha256, "sample_order_sha256")), + subset=subset, + seed=seed, + batch_size=batch_size, + train_steps=RUN084_FORMAL_TRAIN_STEPS, + runtime_sampler=sampler, + ) + loader = TorchDataLoader( + dataset, + local_batch_size=batch_size, + sharding=sharding, + shuffle=False, + sampler=sampler, + num_workers=num_workers, + seed=seed, + framework="jax", + ) + if num_workers <= 0 or prefetch_factor <= 0: + raise ValueError("Phase-A formal loader requires positive workers and prefetch_factor") + loader.torch_loader.prefetch_factor = prefetch_factor + if loader.torch_loader.prefetch_factor != prefetch_factor: + raise ValueError("PyTorch DataLoader did not accept the reviewed prefetch_factor") + return PhaseADataLoader(data_config, loader, sampler, sample_order) + + +def _sampler_state(value: Mapping[str, Any]) -> dict[str, Any]: + expected = { + "schema_version", + "subset_manifest_sha256", + "seed", + "batch_size", + "num_batches", + "epoch", + "batch_cursor", + "next_sample_ids", + } + if set(value) != expected: + raise ValueError("Phase-A full-state sampler fields mismatch") + schema_version = _identifier(value["schema_version"], "sampler.schema_version") + if schema_version not in {FORMAL_SAMPLER_SCHEMA, SMOKE_SAMPLER_SCHEMA}: + raise ValueError("Phase-A sampler schema is unsupported") + batch_size = _sampler_natural(value["batch_size"], "sampler.batch_size") + next_ids = tuple(_sample_identity(item, "sampler.next_sample_ids item") for item in value["next_sample_ids"]) + if batch_size <= 0 or len(next_ids) != batch_size: + raise ValueError("Phase-A sampler must name exactly one positive ordered next batch") + parsed = { + "schema_version": schema_version, + "subset_manifest_sha256": str(_sha256(value["subset_manifest_sha256"], "sampler.subset_manifest_sha256")), + "seed": _sampler_natural(value["seed"], "sampler.seed"), + "batch_size": batch_size, + "num_batches": _sampler_natural(value["num_batches"], "sampler.num_batches"), + "epoch": _sampler_natural(value["epoch"], "sampler.epoch"), + "batch_cursor": _sampler_natural(value["batch_cursor"], "sampler.batch_cursor"), + "next_sample_ids": list(next_ids), + } + if parsed["batch_size"] % 4 or parsed["num_batches"] <= 0: + raise ValueError("Phase-A sampler must describe a non-empty four-task-balanced run") + if parsed["batch_cursor"] >= parsed["num_batches"]: + raise ValueError("Phase-A sampler batch_cursor must be smaller than num_batches") + if any(parsed[name] > np.iinfo(np.uint64).max for name in ("seed", "num_batches", "epoch", "batch_cursor")): + raise ValueError("Phase-A sampler state values must fit in uint64") + return parsed + + +def _scheduler_value(schedule: Any, step: int) -> float: + value = float(np.asarray(jax.device_get(schedule(step)))) + if not math.isfinite(value) or value <= 0: + raise ValueError(f"Phase-A learning rate must be finite and positive, got {value}") + return value + + +def _resume_payload( + state: Any, + *, + train_rng: Any, + sampler_state: Mapping[str, Any], + schedule: Any, + contract: PhaseAContract, +) -> dict[str, Any]: + if state.ema_params is None: + raise ValueError("Phase-A full state requires EMA parameters") + step = int(np.asarray(jax.device_get(state.step))) + sampler = _sampler_state(sampler_state) + if sampler["batch_size"] != contract.global_batch_size: + raise ValueError("checkpoint sampler batch differs from the runtime-bound Phase-A contract") + if contract.launch_kind in {"formal", "sku_smoke"}: + sampler_step = sampler["epoch"] * sampler["num_batches"] + sampler["batch_cursor"] + if sampler_step != step: + raise ValueError("Run084 sampler cursor differs from authoritative TrainState.step") + return { + "authoritative_step": state.step, + "current_params": state.params, + "ema_params": state.ema_params, + "optimizer": state.opt_state, + "scheduler": { + "step": state.step, + "learning_rate": jax.numpy.asarray(_scheduler_value(schedule, step), dtype=jax.numpy.float32), + }, + "rng": {"train_key_data": jax.random.key_data(train_rng)}, + "sampler": { + "schema_version_ascii": _ascii_bytes(sampler["schema_version"], "sampler.schema_version"), + "subset_manifest_sha256": _digest_bytes( + sampler["subset_manifest_sha256"], "sampler.subset_manifest_sha256" + ), + "seed_u64": _u64_words(sampler["seed"], "sampler.seed"), + "batch_size_u64": _u64_words(sampler["batch_size"], "sampler.batch_size"), + "num_batches_u64": _u64_words(sampler["num_batches"], "sampler.num_batches"), + "epoch_u64": _u64_words(sampler["epoch"], "sampler.epoch"), + "batch_cursor_u64": _u64_words(sampler["batch_cursor"], "sampler.batch_cursor"), + "next_sample_identity_sha256": jax.numpy.asarray( + np.stack( + [np.frombuffer(bytes.fromhex(identity), dtype=np.uint8) for identity in sampler["next_sample_ids"]] + ) + ), + }, + "immutable_lineage": { + "config_sha256": _digest_bytes(contract.config_sha256, "config_sha256"), + "dataset_sha256": _digest_bytes(contract.dataset_sha256, "dataset_sha256"), + "cohort_sha256": _digest_bytes(contract.cohort_sha256, "cohort_sha256"), + "sidecar_sha256": _digest_bytes(contract.sidecar_sha256, "sidecar_sha256"), + "feature_sha256": _digest_bytes(contract.feature_sha256, "feature_sha256"), + "source_metadata_sha256": _digest_bytes( + contract.source_metadata_sha256, + "source_metadata_sha256", + ), + "source_digest_sha256": _digest_bytes( + contract.source_digest_sha256, + "source_digest_sha256", + ), + "artifact_identity_sha256": _digest_bytes( + contract.artifact_identity_sha256, + "artifact_identity_sha256", + ), + "artifact_hashes_sha256": _digest_bytes( + contract.artifact_hashes_sha256, + "artifact_hashes_sha256", + ), + "replacement_manifest_sha256": _digest_bytes( + contract.replacement_manifest_sha256, + "replacement_manifest_sha256", + ), + "best_visible_manifest_sha256": _digest_bytes( + contract.best_visible_manifest_sha256, + "best_visible_manifest_sha256", + ), + "sample_order_path_utf8": _path_bytes(contract.sample_order_path, "sample_order_path"), + "sample_order_manifest_sha256": _digest_bytes( + contract.sample_order_manifest_sha256, + "sample_order_manifest_sha256", + ), + "sample_order_sha256": _digest_bytes( + contract.sample_order_sha256, + "sample_order_sha256", + ), + "training_manifest_sha256": _digest_bytes( + contract.training_manifest_sha256, + "training_manifest_sha256", + ), + "overlay_sha256": _digest_bytes(contract.overlay_sha256, "overlay_sha256"), + "runtime_policy_sha256": _digest_bytes( + contract.runtime_policy_sha256, + "runtime_policy_sha256", + ), + "runtime_plan_sha256": _digest_bytes(contract.runtime_plan_sha256, "runtime_plan_sha256"), + "runtime_matrix_sha256": _digest_bytes( + contract.runtime_matrix_sha256, + "runtime_matrix_sha256", + ), + "runtime_calibration_sha256": _digest_bytes( + contract.runtime_calibration_sha256, + "runtime_calibration_sha256", + ), + "optimizer_sha256": _digest_bytes(contract.optimizer_sha256, "optimizer_sha256"), + "learning_rate_schedule_sha256": _digest_bytes( + contract.learning_rate_schedule_sha256, + "learning_rate_schedule_sha256", + ), + }, + } + + +def _decode_sampler(payload: Mapping[str, Any]) -> dict[str, Any]: + batch_size = _decode_u64_words(payload["batch_size_u64"], "sampler.batch_size_u64") + identity_bytes = np.asarray( + jax.device_get(payload["next_sample_identity_sha256"]), + dtype=np.uint8, + ) + if identity_bytes.shape != (batch_size, 32): + raise ValueError("restored sampler next-sample identity matrix has the wrong shape") + return _sampler_state( + { + "schema_version": _decode_ascii(payload["schema_version_ascii"], "sampler.schema_version_ascii"), + "subset_manifest_sha256": _decode_digest( + payload["subset_manifest_sha256"], "sampler.subset_manifest_sha256" + ), + "seed": _decode_u64_words(payload["seed_u64"], "sampler.seed_u64"), + "batch_size": batch_size, + "num_batches": _decode_u64_words(payload["num_batches_u64"], "sampler.num_batches_u64"), + "epoch": _decode_u64_words(payload["epoch_u64"], "sampler.epoch_u64"), + "batch_cursor": _decode_u64_words(payload["batch_cursor_u64"], "sampler.batch_cursor_u64"), + "next_sample_ids": [row.tobytes().hex() for row in identity_bytes], + } + ) + + +def _validate_resume_lineage(payload: Mapping[str, Any], contract: PhaseAContract) -> None: + expected = { + "config_sha256": contract.config_sha256, + "dataset_sha256": contract.dataset_sha256, + "cohort_sha256": contract.cohort_sha256, + "sidecar_sha256": contract.sidecar_sha256, + "feature_sha256": contract.feature_sha256, + "source_metadata_sha256": contract.source_metadata_sha256, + "source_digest_sha256": contract.source_digest_sha256, + "artifact_identity_sha256": contract.artifact_identity_sha256, + "artifact_hashes_sha256": contract.artifact_hashes_sha256, + "replacement_manifest_sha256": contract.replacement_manifest_sha256, + "best_visible_manifest_sha256": contract.best_visible_manifest_sha256, + "sample_order_path_utf8": str(contract.sample_order_path), + "sample_order_manifest_sha256": contract.sample_order_manifest_sha256, + "sample_order_sha256": contract.sample_order_sha256, + "training_manifest_sha256": contract.training_manifest_sha256, + "overlay_sha256": contract.overlay_sha256, + "runtime_policy_sha256": contract.runtime_policy_sha256, + "runtime_plan_sha256": contract.runtime_plan_sha256, + "runtime_matrix_sha256": contract.runtime_matrix_sha256, + "runtime_calibration_sha256": contract.runtime_calibration_sha256, + "optimizer_sha256": contract.optimizer_sha256, + "learning_rate_schedule_sha256": contract.learning_rate_schedule_sha256, + } + if set(payload) != set(expected): + raise ValueError("Phase-A restored immutable lineage fields mismatch") + drift = [] + for name, value in expected.items(): + actual = ( + _decode_path(payload[name], "sample_order_path") + if name == "sample_order_path_utf8" + else _decode_digest(payload[name], name) + ) + if actual != value: + drift.append(name) + if drift: + raise ValueError(f"Phase-A restored immutable lineage drift: {drift}") + + +def materialize_phase_a_contract(contract: PhaseAContract, config: Any) -> Path: + path = contract.checkpoint_root / "picmem_phase_a_full_state_contract.json" + payload = contract.stable_json(config) + if path.exists(): + if path.is_symlink() or not path.is_file() or path.read_bytes() != _canonical_json(payload): + raise ValueError("Phase-A immutable checkpoint-root contract drift") + else: + _write_atomic_json(path, payload) + return path + + +def _save_assets(directory: epath.Path, data_loader: PhaseADataLoader, contract_path: Path) -> None: + data_config = data_loader.data_config() + if data_config.norm_stats is not None and data_config.asset_id is not None: + _normalize.save(directory / data_config.asset_id, data_config.norm_stats) + shutil.copyfile(contract_path, Path(directory) / contract_path.name) + + +def _write_state_manifest(checkpoint_dir: Path, step: int, sampler: Mapping[str, Any]) -> None: + assets_digest = path_sha256(checkpoint_dir / "assets") + resume_digest = path_sha256(checkpoint_dir / "resume_state") + params_digest = path_sha256(checkpoint_dir / "params") + components = { + "assets": StateComponent("assets", "assets", assets_digest), + "trainable_params": StateComponent("resume_state", "resume_state/current_params", resume_digest), + "ema_params": StateComponent("resume_state", "resume_state/ema_params", resume_digest), + "inference_params": StateComponent("params", "params/inference_params", params_digest), + "optimizer": StateComponent("resume_state", "resume_state/optimizer", resume_digest), + "scheduler": StateComponent("resume_state", "resume_state/scheduler", resume_digest), + "rng": StateComponent("resume_state", "resume_state/rng", resume_digest), + } + parsed_sampler = _sampler_state(sampler) + manifest = StateManifest( + authoritative_global_step=step, + components=components, + sampler=SamplerState( + path="resume_state", + orbax_item="resume_state/sampler", + sha256=resume_digest, + schema_version=parsed_sampler["schema_version"], + subset_manifest_sha256=parsed_sampler["subset_manifest_sha256"], + seed=parsed_sampler["seed"], + batch_size=parsed_sampler["batch_size"], + num_batches=parsed_sampler["num_batches"], + epoch=parsed_sampler["epoch"], + batch_cursor=parsed_sampler["batch_cursor"], + next_sample_ids=tuple(parsed_sampler["next_sample_ids"]), + ), + ) + _write_atomic_json(checkpoint_dir / "picmem_state_manifest.json", manifest.to_json()) + + +def save_phase_a_checkpoint( + checkpoint_manager: Any, + state: Any, + data_loader: PhaseADataLoader, + step: int, + *, + contract: PhaseAContract, + contract_path: Path, + train_rng: Any, + schedule: Any, +) -> CheckpointInfo: + authoritative_step = int(np.asarray(jax.device_get(state.step))) + if int(step) != authoritative_step: + raise ValueError("checkpoint step differs from authoritative TrainState.step") + sampler = data_loader.sampler_state_dict() + payload = _resume_payload( + state, + train_rng=train_rng, + sampler_state=sampler, + schedule=schedule, + contract=contract, + ) + accepted = checkpoint_manager.save( + authoritative_step, + { + "assets": lambda directory: _save_assets(directory, data_loader, contract_path), + "params": {"params": state.ema_params}, + "resume_state": payload, + }, + ) + if not accepted: + raise RuntimeError(f"checkpoint manager rejected Phase-A full-state step {authoritative_step}") + checkpoint_manager.wait_until_finished() + checkpoint_dir = Path(checkpoint_manager.directory) / str(authoritative_step) + _write_state_manifest(checkpoint_dir, authoritative_step, sampler) + info = finalize_checkpoint(checkpoint_dir, contract.checkpoint_metadata(authoritative_step)) + print(f"PICMEM_CHECKPOINT_FINALIZE_COMPLETE step={authoritative_step}", flush=True) + return info + + +def _tree_equal(left: Any, right: Any) -> bool: + if jax.tree_util.tree_structure(left) != jax.tree_util.tree_structure(right): + return False + return all( + np.array_equal(np.asarray(jax.device_get(a)), np.asarray(jax.device_get(b))) + for a, b in zip(jax.tree_util.tree_leaves(left), jax.tree_util.tree_leaves(right), strict=True) + ) + + +def _validate_checkpoint_contract(info: CheckpointInfo, contract: PhaseAContract) -> None: + metadata = info.metadata + expected = { + "experiment": contract.experiment, + "job": contract.job, + "run_id": contract.run_id, + "gpu_class": contract.gpu_class, + "world_size": 8, + "fsdp_devices": 8, + "launch_kind": contract.launch_kind, + "training_manifest_kind": contract.training_manifest_kind, + "training_manifest_sha256": contract.training_manifest_sha256, + "runtime_profile_id": contract.runtime_profile_id, + "runtime_candidate_id": contract.runtime_candidate_id, + "runtime_policy_sha256": contract.runtime_policy_sha256, + "runtime_plan_sha256": contract.runtime_plan_sha256, + "runtime_matrix_sha256": contract.runtime_matrix_sha256, + "runtime_calibration_sha256": contract.runtime_calibration_sha256, + "optimizer_sha256": contract.optimizer_sha256, + "learning_rate_schedule_sha256": contract.learning_rate_schedule_sha256, + "global_batch_size": contract.global_batch_size, + "micro_batch_per_device": contract.micro_batch_per_device, + "gradient_accumulation_steps": contract.gradient_accumulation_steps, + "dataloader_workers": contract.dataloader_workers, + "prefetch_factor": contract.prefetch_factor, + "xla_preallocate": contract.xla_preallocate, + "xla_memory_fraction": contract.xla_memory_fraction, + "nccl_collective_channel_cap": contract.nccl_collective_channel_cap, + "nccl_p2p_channel_cap": contract.nccl_p2p_channel_cap, + "xla_flags": contract.xla_flags, + "checkpoint_interval": contract.runtime_checkpoint_interval, + "interface_commit": contract.interface_commit, + "code_commit": contract.code_commit, + "config_sha256": contract.config_sha256, + "dataset_sha256": contract.dataset_sha256, + "cohort_sha256": contract.cohort_sha256, + "sidecar_sha256": contract.sidecar_sha256, + "feature_sha256": contract.feature_sha256, + "source_metadata_sha256": contract.source_metadata_sha256, + "source_digest_sha256": contract.source_digest_sha256, + "artifact_identity_sha256": contract.artifact_identity_sha256, + "artifact_hashes_sha256": contract.artifact_hashes_sha256, + "replacement_manifest_sha256": contract.replacement_manifest_sha256, + "best_visible_manifest_sha256": contract.best_visible_manifest_sha256, + "sample_order_path": str(contract.sample_order_path), + "sample_order_manifest_sha256": contract.sample_order_manifest_sha256, + "sample_order_sha256": contract.sample_order_sha256, + "overlay_sha256": contract.overlay_sha256, + } + actual = {name: getattr(metadata, name) for name in expected} + actual["gpu_class"] = metadata.gpu_class.value + drift = [name for name, value in expected.items() if actual[name] != value] + if drift: + raise ValueError(f"Phase-A resume checkpoint lineage drift: {drift}") + if metadata.generation >= contract.generation: + raise ValueError("Phase-A resume checkpoint is not from an earlier generation") + if contract.parent_metadata_sha256 != info.metadata_sha256: + raise ValueError("Phase-A resume parent edge differs from the selected checkpoint metadata hash") + + +def restore_phase_a_checkpoint( + checkpoint_manager: Any, + state: Any, + data_loader: PhaseADataLoader, + *, + contract: PhaseAContract, + train_rng: Any, + schedule: Any, + step: int, +) -> tuple[Any, Any, dict[str, Any], CheckpointInfo]: + checkpoint_dir = Path(checkpoint_manager.directory) / str(int(step)) + info = validate_checkpoint( + checkpoint_dir, + expected_experiment=contract.experiment, + expected_job=contract.job, + expected_gpu_class=contract.gpu_class, + ) + _validate_checkpoint_contract(info, contract) + target = _resume_payload( + state, + train_rng=train_rng, + sampler_state=data_loader.sampler_state_dict(), + schedule=schedule, + contract=contract, + ) + try: + restored = checkpoint_manager.restore( + int(step), + items={"resume_state": target, "params": {"params": state.ema_params}}, + ) + except Exception as exc: + raise ValueError("Phase-A Orbax resume state is missing or corrupt") from exc + payload = restored["resume_state"] + restored_step = int(np.asarray(jax.device_get(payload["authoritative_step"]))) + scheduler_step = int(np.asarray(jax.device_get(payload["scheduler"]["step"]))) + if restored_step != int(step) or scheduler_step != restored_step: + raise ValueError("Phase-A authoritative/scheduler/checkpoint steps disagree") + saved_lr = float(np.asarray(jax.device_get(payload["scheduler"]["learning_rate"]))) + expected_lr = _scheduler_value(schedule, restored_step) + if not np.isclose(saved_lr, expected_lr, rtol=1e-6, atol=0.0): + raise ValueError("Phase-A restored scheduler value differs from the immutable schedule") + if not _tree_equal(payload["ema_params"], restored["params"]["params"]): + raise ValueError("Phase-A inference params differ from restored EMA params") + _validate_resume_lineage(payload["immutable_lineage"], contract) + sampler = _decode_sampler(payload["sampler"]) + if contract.launch_kind in {"formal", "sku_smoke"}: + sampler_step = sampler["epoch"] * sampler["num_batches"] + sampler["batch_cursor"] + if sampler_step != restored_step: + raise ValueError("restored Run084 sampler cursor differs from authoritative checkpoint step") + data_loader.load_sampler_state_dict(sampler) + restored_rng = jax.random.wrap_key_data(payload["rng"]["train_key_data"]) + restored_state = dataclasses.replace( + state, + step=payload["authoritative_step"], + params=payload["current_params"], + opt_state=payload["optimizer"], + ema_params=payload["ema_params"], + ) + return restored_state, restored_rng, sampler, info + + +class PhaseAMetricWriter: + FIELDS = ("schema_version", "wall_time", "step", "learning_rate", "loss", "metrics_json") + + def __init__(self, path: Path): + self.path = path + path.parent.mkdir(parents=True, exist_ok=True) + self._stream = path.open("x", newline="") + self._writer = csv.DictWriter(self._stream, fieldnames=self.FIELDS, delimiter="\t", lineterminator="\n") + self._writer.writeheader() + self._flush() + + def _flush(self) -> None: + self._stream.flush() + os.fsync(self._stream.fileno()) + + def write(self, *, step: int, learning_rate: float, metrics: Mapping[str, Any]) -> None: + parsed: dict[str, float] = {} + for name, value in metrics.items(): + array = np.asarray(jax.device_get(value)) + if array.size == 1: + scalar = float(array.reshape(())) + if not math.isfinite(scalar): + raise ValueError(f"Phase-A metric {name} is not finite") + parsed[name] = scalar + if "loss" not in parsed: + raise ValueError("Phase-A metrics are missing scalar loss") + if not math.isfinite(learning_rate) or learning_rate <= 0: + raise ValueError("Phase-A metric learning rate must be finite and positive") + self._writer.writerow( + { + "schema_version": PHASE_A_METRICS_SCHEMA, + "wall_time": datetime.now().astimezone().isoformat(timespec="seconds"), + "step": int(step), + "learning_rate": repr(float(learning_rate)), + "loss": repr(parsed["loss"]), + "metrics_json": json.dumps(parsed, sort_keys=True, separators=(",", ":")), + } + ) + self._flush() + + def close(self) -> None: + if not self._stream.closed: + self._stream.close() + + def __enter__(self) -> PhaseAMetricWriter: + return self + + def __exit__(self, *_: Any) -> None: + self.close() + + +class ContinuityEmitter: + def __init__(self, contract: PhaseAContract, metrics_path: Path): + self.contract = contract + self.metrics_path = metrics_path.resolve() + if self.metrics_path != contract.metrics_path: + raise ValueError("continuity emitter metrics path differs from the Phase-A contract") + self.pending: Any | None = None + self.sampler: SamplerContinuity | None = None + self.resume_step: int | None = None + self.rng_sha256: str | None = None + self._boundary_step: int | None = None + self._boundary_sampler: SamplerContinuity | None = None + self._boundary_rng_sha256: str | None = None + + @staticmethod + def _sampler(value: Mapping[str, Any]) -> SamplerContinuity: + parsed = _sampler_state(value) + return SamplerContinuity( + schema_version=parsed["schema_version"], + subset_manifest_sha256=parsed["subset_manifest_sha256"], + seed=parsed["seed"], + batch_size=parsed["batch_size"], + num_batches=parsed["num_batches"], + epoch=parsed["epoch"], + batch_cursor=parsed["batch_cursor"], + next_sample_ids=tuple(parsed["next_sample_ids"]), + ) + + @staticmethod + def _rng_sha256(train_rng: Any) -> str: + key_data = np.asarray(jax.device_get(jax.random.key_data(train_rng)), dtype=np.uint32) + return hashlib.sha256(key_data.tobytes(order="C")).hexdigest() + + def _report_path(self, pending: Any) -> Path: + return self.contract.watch_state_dir / f"continuity-{pending.request_id}.json" + + def _clear_completed_request(self) -> None: + """Re-arm the live process for a later pause in the same generation.""" + + self.pending = None + self.sampler = None + self.resume_step = None + self.rng_sha256 = None + + def _capture_pending_from_boundary(self) -> None: + if self.pending is not None: + return + state_path = self.contract.watch_state_dir / "state.json" + if not state_path.is_file() or state_path.is_symlink(): + return + state = WatchState.from_json(json.loads(state_path.read_text(encoding="utf-8"))) + if (state.experiment, state.job, state.generation) != ( + self.contract.experiment, + self.contract.job, + self.contract.generation, + ): + raise ValueError("watch state identity/generation differs from the running Phase-A process") + pending = state.pending_continuity + if pending is None: + return + report_path = self._report_path(pending) + if report_path.exists(): + return + if self._boundary_step is None or self._boundary_sampler is None or self._boundary_rng_sha256 is None: + raise ValueError("continuity request arrived before a live trainer boundary was recorded") + if pending.mode is ContinuityMode.RESTART_ZERO: + if self._boundary_step != 0 or pending.resume_step != 0: + raise ValueError("restart_zero did not begin from authoritative step zero") + elif pending.mode is ContinuityMode.CHECKPOINT_RESUME: + if self._boundary_step != pending.resume_step: + raise ValueError("running state step differs from watchdog checkpoint handoff") + elif pending.resume_step is not None or pending.expected_sampler is not None: + raise ValueError("paused resume request guessed a lagging checkpoint handoff") + if pending.expected_sampler is not None and self._boundary_sampler != pending.expected_sampler: + raise ValueError("restored sampler differs from watchdog checkpoint handoff") + self.pending = pending + self.resume_step = self._boundary_step + self.sampler = self._boundary_sampler + self.rng_sha256 = self._boundary_rng_sha256 + + def capture_pending( + self, + *, + current_step: int, + sampler_state: Mapping[str, Any], + train_rng: Any, + ) -> None: + """Record a live loop boundary and acknowledge any pending request. + + The method is intentionally called before every batch. ``after_metric`` + checks again so a process paused during a device step still uses the + exact pre-step sampler/RNG boundary and the first post-resume metric. + """ + + self._boundary_step = _sampler_natural(current_step, "continuity current_step") + self._boundary_sampler = self._sampler(sampler_state) + if self._boundary_sampler.batch_size != self.contract.global_batch_size: + raise ValueError("continuity sampler batch differs from the runtime-bound Phase-A contract") + self._boundary_rng_sha256 = self._rng_sha256(train_rng) + self._capture_pending_from_boundary() + + def after_metric(self, *, first_metric_step: int, learning_rate: float) -> None: + self._capture_pending_from_boundary() + if self.pending is None or self.sampler is None or self.resume_step is None or self.rng_sha256 is None: + return + pending = self.pending + report_path = self._report_path(pending) + if report_path.exists(): + verify_continuity( + report_path, + pending, + self.contract.experiment, + self.contract.job, + ) + self._clear_completed_request() + return + if first_metric_step != self.resume_step + 1: + raise ValueError("first continuity metric is not the exact live next step") + marker = "PICMEM_CLEAN_START_OK" if pending.mode is ContinuityMode.RESTART_ZERO else "PICMEM_RESUME_OK" + payload = { + "schema_version": CONTINUITY_SCHEMA, + "experiment": self.contract.experiment, + "job": self.contract.job, + "generation": self.contract.generation, + "mode": pending.mode.value, + "request_id": pending.request_id, + "resume_marker": marker, + "resume_step": self.resume_step, + "first_metric_step": int(first_metric_step), + "learning_rate": float(learning_rate), + "rng_sha256": self.rng_sha256, + "sampler": self.sampler.to_json(), + "metrics_path": str(self.metrics_path), + "prior_metrics_reused": False, + } + _write_atomic_json(report_path, payload) + verify_continuity( + report_path, + pending, + self.contract.experiment, + self.contract.job, + ) + self._clear_completed_request() + + +__all__ = [ + "PHASE_A_HISTORY_CONFIG", + "ContinuityEmitter", + "PhaseAContract", + "PhaseADataLoader", + "PhaseAMetricWriter", + "PhaseASampler", + "PhaseASmokeRandomSampler", + "create_phase_a_data_loader", + "initialize_phase_a_checkpoint_dir", + "materialize_phase_a_contract", + "restore_phase_a_checkpoint", + "save_phase_a_checkpoint", + "validate_phase_a_topology", +] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_reader.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..f36debca74124f760e06c0198e4f806693a2168c --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_reader.py @@ -0,0 +1,717 @@ +"""Token-layout and metadata materialization for the Phase-A visual reader. + +The standalone :mod:`picmem.memory` package owns the frozen ``Read`` and +``SelectedFrame`` contracts. This host adapter is deliberately the only place +that turns those frame-level records into RoboMME's fixed 512-token +observation. Visual selection is kept separate from metadata interventions so +all metadata arms retain byte-identical image features, PosEmb3D tensors and +valid-token masks. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np + +from picmem.memory.contracts import ( + ManagerMode, + MetadataMode, + ReaderMode, + SelectedFrame, + SelectionMode, +) +from picmem.memory.memory import MemoryInvariantError, Read + +FRAME_BUDGET = 32 +TOKEN_BUDGET = 512 +FIXED_TOKENS_PER_FRAME = 16 +MAX_VARIABLE_EVIDENCE = 6 +FLOAT32_NEGATIVE_ZERO_BITS = np.uint32(0x80000000) + +TIME_CHANNELS = 3 +EVENT_VOCAB_SIZE = 4096 +CONTRACT_VOCAB_SIZE = 128 +STATUS_VOCAB_SIZE = 32 +EVENT_ORDINAL_VOCAB_SIZE = 128 + +FACTOR_FIELDS = frozenset({"selection_mode", "metadata_mode", "reader_mode", "manager_mode"}) + +OBSERVATION_FIELDS = ( + "phase_a_frame_indices", + "phase_a_capture_steps", + "phase_a_time_values", + "phase_a_time_mask", + "phase_a_role_ids", + "phase_a_role_mask", + "phase_a_event_ids", + "phase_a_event_ordinals", + "phase_a_contract_ids", + "phase_a_status_ids", + "phase_a_categorical_mask", + "phase_a_confidence", + "phase_a_evidence_mask", + "phase_a_valid_mask", +) + + +@dataclass(frozen=True) +class PhaseAFactors: + """The four declared experiment factors consumed by this host path.""" + + selection_mode: SelectionMode = SelectionMode.RELEVANT + metadata_mode: MetadataMode = MetadataMode.NEUTRAL + reader_mode: ReaderMode = ReaderMode.FIXED16 + manager_mode: ManagerMode = ManagerMode.FULL_EVOLVING + + @classmethod + def from_mapping( + cls, + raw: Mapping[str, Any] | None, + *, + require_explicit: bool = False, + ) -> PhaseAFactors: + if raw is None: + raw = {} + if not isinstance(raw, Mapping): + raise ValueError("Phase-A factors must be a mapping") + unknown = set(raw) - FACTOR_FIELDS + if unknown: + raise ValueError(f"unknown Phase-A factor fields: {sorted(unknown)}") + missing = FACTOR_FIELDS - set(raw) + if require_explicit and missing: + raise ValueError(f"explicit Phase-A factors are missing: {sorted(missing)}") + values = { + "selection_mode": raw.get("selection_mode", SelectionMode.RELEVANT), + "metadata_mode": raw.get("metadata_mode", MetadataMode.NEUTRAL), + "reader_mode": raw.get("reader_mode", ReaderMode.FIXED16), + "manager_mode": raw.get("manager_mode", ManagerMode.FULL_EVOLVING), + } + try: + return cls( + selection_mode=SelectionMode(values["selection_mode"]), + metadata_mode=MetadataMode(values["metadata_mode"]), + reader_mode=ReaderMode(values["reader_mode"]), + manager_mode=ManagerMode(values["manager_mode"]), + ) + except ValueError as exc: + raise ValueError(f"unsupported Phase-A factor value: {exc}") from exc + + def validate_implemented_path( + self, + *, + selection_applied: SelectionMode | str | None = None, + ) -> None: + """Fail rather than silently run a factor this branch does not own.""" + + if selection_applied is not None: + try: + applied = SelectionMode(selection_applied) + except ValueError as exc: + raise ValueError(f"unsupported applied selection mode: {selection_applied!r}") from exc + if applied is not self.selection_mode: + raise NotImplementedError( + "Phase-A materializer selection_mode does not match the verified frozen selection plan" + ) + if self.reader_mode is ReaderMode.RAW_VLM: + raise NotImplementedError("reader_mode='raw_vlm' requires the separately gated raw-image reader") + + +@dataclass(frozen=True) +class PhaseATokenMetadata: + """Model-facing metadata aligned one-to-one with 512 visual tokens.""" + + frame_indices: np.ndarray + capture_steps: np.ndarray + time_values: np.ndarray + time_mask: np.ndarray + role_ids: np.ndarray + role_mask: np.ndarray + event_ids: np.ndarray + event_ordinals: np.ndarray + contract_ids: np.ndarray + status_ids: np.ndarray + categorical_mask: np.ndarray + confidence: np.ndarray + evidence_mask: np.ndarray + valid_mask: np.ndarray + + def __post_init__(self) -> None: + vector_specs = { + "frame_indices": np.int32, + "capture_steps": np.int32, + "role_ids": np.int32, + "role_mask": np.bool_, + "event_ids": np.int32, + "event_ordinals": np.int32, + "contract_ids": np.int32, + "status_ids": np.int32, + "categorical_mask": np.bool_, + "confidence": np.float32, + "evidence_mask": np.bool_, + "valid_mask": np.bool_, + } + for name, dtype in vector_specs.items(): + value = getattr(self, name) + if not isinstance(value, np.ndarray) or value.shape != (TOKEN_BUDGET,): + raise MemoryInvariantError(f"Phase-A token metadata {name} must have shape {(TOKEN_BUDGET,)}") + if value.dtype != dtype: + raise MemoryInvariantError(f"Phase-A token metadata {name} must have dtype {np.dtype(dtype)}") + for name in ("time_values", "time_mask"): + value = getattr(self, name) + expected_dtype = np.float32 if name == "time_values" else np.bool_ + if not isinstance(value, np.ndarray) or value.shape != ( + TOKEN_BUDGET, + TIME_CHANNELS, + ): + raise MemoryInvariantError( + f"Phase-A token metadata {name} must have shape {(TOKEN_BUDGET, TIME_CHANNELS)}" + ) + if value.dtype != expected_dtype: + raise MemoryInvariantError(f"Phase-A token metadata {name} must have dtype {np.dtype(expected_dtype)}") + if np.any(self.time_values.view(np.uint32) == FLOAT32_NEGATIVE_ZERO_BITS): + raise MemoryInvariantError("Phase-A time values must encode zero as canonical +0.0") + + invalid = ~self.valid_mask + if np.any(self.frame_indices < 0) or np.any(self.capture_steps < 0): + raise MemoryInvariantError("Phase-A token provenance must be non-negative") + if np.any(self.frame_indices[invalid]) or np.any(self.capture_steps[invalid]): + raise MemoryInvariantError("Phase-A token padding provenance must be canonical zeros") + if np.any(self.time_mask[invalid]): + raise MemoryInvariantError("Phase-A token padding cannot expose temporal metadata") + for name in ("role_mask", "categorical_mask", "evidence_mask"): + if np.any(getattr(self, name) & invalid): + raise MemoryInvariantError(f"Phase-A token {name} cannot mark padding") + + if not np.array_equal(self.role_mask, self.evidence_mask): + raise MemoryInvariantError("Phase-A role mask must equal evidence mask") + if not np.array_equal(self.categorical_mask, self.evidence_mask): + raise MemoryInvariantError("Phase-A categorical mask must equal evidence mask") + if not np.array_equal( + self.time_mask, + np.repeat(self.time_mask[:, :1], TIME_CHANNELS, axis=1), + ): + raise MemoryInvariantError("Phase-A time channels must share one token gate") + + if np.any(self.time_values[~self.time_mask]): + raise MemoryInvariantError("masked Phase-A time values must be neutral zeros") + if np.any(self.capture_steps[~np.any(self.time_mask, axis=-1)]): + raise MemoryInvariantError("masked Phase-A capture steps must be neutral zeros") + if np.any(self.role_ids[~self.role_mask]): + raise MemoryInvariantError("masked Phase-A role IDs must be neutral zeros") + for name in ( + "event_ids", + "event_ordinals", + "contract_ids", + "status_ids", + "confidence", + ): + if np.any(getattr(self, name)[~self.categorical_mask]): + raise MemoryInvariantError(f"masked Phase-A {name} must contain neutral zeros") + + if not np.all(np.isfinite(self.time_values)): + raise MemoryInvariantError("Phase-A time values must be finite") + if np.any((self.time_values < 0) | (self.time_values > 1)): + raise MemoryInvariantError("Phase-A normalized time values must be in [0, 1]") + if not np.all(np.isfinite(self.confidence)) or np.any((self.confidence < 0) | (self.confidence > 1)): + raise MemoryInvariantError("Phase-A confidence must be finite and in [0, 1]") + if np.any(self.role_ids[self.evidence_mask] == 0): + raise MemoryInvariantError("Phase-A evidence tokens require a non-background role") + for name in ("event_ids", "event_ordinals", "contract_ids", "status_ids"): + if np.any(getattr(self, name)[self.evidence_mask] == 0): + raise MemoryInvariantError(f"Phase-A evidence tokens require nonzero {name}") + + def to_observation(self) -> dict[str, np.ndarray]: + values = { + "phase_a_frame_indices": self.frame_indices, + "phase_a_capture_steps": self.capture_steps, + "phase_a_time_values": self.time_values, + "phase_a_time_mask": self.time_mask, + "phase_a_role_ids": self.role_ids, + "phase_a_role_mask": self.role_mask, + "phase_a_event_ids": self.event_ids, + "phase_a_event_ordinals": self.event_ordinals, + "phase_a_contract_ids": self.contract_ids, + "phase_a_status_ids": self.status_ids, + "phase_a_categorical_mask": self.categorical_mask, + "phase_a_confidence": self.confidence, + "phase_a_evidence_mask": self.evidence_mask, + "phase_a_valid_mask": self.valid_mask, + } + if tuple(values) != OBSERVATION_FIELDS: + raise AssertionError("Phase-A observation field registry drift") + return values + + @classmethod + def from_observation( + cls, + raw: Mapping[str, Any], + *, + metadata_mode: MetadataMode | str, + ) -> PhaseATokenMetadata: + """Recover the exact token contract after host observation transforms. + + Missing or extra Phase-A fields are schema drift. Recovered arrays are + detached from the host container and made immutable before validation. + """ + + if not isinstance(raw, Mapping): + raise MemoryInvariantError("Phase-A observation must be a mapping") + if set(raw) != set(OBSERVATION_FIELDS): + missing = sorted(set(OBSERVATION_FIELDS) - set(raw)) + extra = sorted(set(raw) - set(OBSERVATION_FIELDS)) + raise MemoryInvariantError(f"Phase-A observation field drift (missing={missing}, extra={extra})") + names = { + "frame_indices": "phase_a_frame_indices", + "capture_steps": "phase_a_capture_steps", + "time_values": "phase_a_time_values", + "time_mask": "phase_a_time_mask", + "role_ids": "phase_a_role_ids", + "role_mask": "phase_a_role_mask", + "event_ids": "phase_a_event_ids", + "event_ordinals": "phase_a_event_ordinals", + "contract_ids": "phase_a_contract_ids", + "status_ids": "phase_a_status_ids", + "categorical_mask": "phase_a_categorical_mask", + "confidence": "phase_a_confidence", + "evidence_mask": "phase_a_evidence_mask", + "valid_mask": "phase_a_valid_mask", + } + values: dict[str, np.ndarray] = {} + for name, field in names.items(): + value = np.array(raw[field], copy=True) + value.setflags(write=False) + values[name] = value + metadata = cls(**values) + metadata.validate_mode(metadata_mode) + return metadata + + def validate_mode(self, metadata_mode: MetadataMode | str) -> None: + """Enforce the exact mask geometry of one declared metadata arm.""" + + try: + mode = MetadataMode(metadata_mode) + except (TypeError, ValueError) as exc: + raise MemoryInvariantError(f"unsupported Phase-A metadata mode: {metadata_mode!r}") from exc + full_time = np.repeat(self.valid_mask[:, None], TIME_CHANNELS, axis=1) + no_time = np.zeros_like(full_time) + task_aware_modes = { + MetadataMode.CORRECT, + MetadataMode.TIME_SHUFFLED, + MetadataMode.ORDER_REVERSED, + MetadataMode.ROLE_ONLY, + } + if mode in task_aware_modes: + if not np.array_equal(self.role_mask, self.evidence_mask) or not np.array_equal( + self.categorical_mask, + self.evidence_mask, + ): + raise MemoryInvariantError(f"metadata_mode={mode.value} requires task-aware gates on evidence only") + elif np.any(self.role_mask) or np.any(self.categorical_mask) or np.any(self.evidence_mask): + raise MemoryInvariantError(f"metadata_mode={mode.value} requires neutral task-aware gates") + + expected_time = no_time if mode in {MetadataMode.ROLE_ONLY, MetadataMode.NEUTRAL} else full_time + if not np.array_equal(self.time_mask, expected_time): + raise MemoryInvariantError(f"metadata_mode={mode.value} has an invalid temporal gate") + + +@dataclass(frozen=True) +class PhaseAFramePlan: + """A validated frame plan, per-frame token geometry and token metadata.""" + + frame_indices: np.ndarray + valid_mask: np.ndarray + evidence_mask: np.ndarray + token_counts: np.ndarray + metadata: PhaseATokenMetadata + + @property + def valid_indices(self) -> tuple[int, ...]: + return tuple(int(value) for value in self.frame_indices[self.valid_mask]) + + +def materialize_phase_a_read( + read: Read, + factors: PhaseAFactors, + *, + metadata_seed: int = 0, + selection_applied: SelectionMode | str = SelectionMode.RELEVANT, +) -> PhaseAFramePlan: + """Validate one ``Read`` and produce a strict 512-token host plan.""" + + if not isinstance(read, Read): + raise MemoryInvariantError("Phase-A materializer requires a Read") + if not isinstance(factors, PhaseAFactors): + raise ValueError("factors must be PhaseAFactors") + factors.validate_implemented_path(selection_applied=selection_applied) + metadata_seed = _nonnegative_int(metadata_seed, "metadata_seed") + frames = _validated_selected_frames(read) + token_counts = _token_layout(frames, factors.reader_mode) + frame_metadata = _intervene_metadata( + frames, + factors.metadata_mode, + seed=metadata_seed, + read_step=read.step, + ) + token_metadata = _repeat_metadata(frame_metadata, token_counts) + token_metadata.validate_mode(factors.metadata_mode) + + frame_indices = np.asarray([frame.frame_index for frame in frames], dtype=np.int32) + valid_mask = np.asarray([frame.valid_mask for frame in frames], dtype=np.bool_) + evidence_mask = np.asarray([frame.evidence_mask for frame in frames], dtype=np.bool_) + for value in (frame_indices, valid_mask, evidence_mask, token_counts): + value.setflags(write=False) + return PhaseAFramePlan( + frame_indices=frame_indices, + valid_mask=valid_mask, + evidence_mask=evidence_mask, + token_counts=token_counts, + metadata=token_metadata, + ) + + +def _validated_selected_frames(read: Read) -> tuple[SelectedFrame, ...]: + try: + read_step = _nonnegative_int(read.step, "Read.step") + except ValueError as exc: + raise MemoryInvariantError(str(exc)) from exc + frames = read.selected_frames + if not isinstance(frames, tuple) or len(frames) != FRAME_BUDGET: + raise MemoryInvariantError(f"Phase-A Read.selected_frames must contain exactly {FRAME_BUDGET} slots") + if any(not isinstance(frame, SelectedFrame) for frame in frames): + raise MemoryInvariantError("Phase-A selected frame has the wrong contract type") + if read.frame_indices.shape != (FRAME_BUDGET,): + raise MemoryInvariantError("Phase-A frame_indices shape drift") + if read.evidence_mask.shape != (FRAME_BUDGET,) or read.valid_mask.shape != (FRAME_BUDGET,): + raise MemoryInvariantError("Phase-A frame masks shape drift") + + valid_indices: list[int] = [] + previous_capture: int | None = None + denominator = max(read_step, 1) + for slot, frame in enumerate(frames): + if frame.valid_mask != bool(read.valid_mask[slot]): + raise MemoryInvariantError("SelectedFrame.valid_mask disagrees with Read.valid_mask") + if frame.evidence_mask != bool(read.evidence_mask[slot]): + raise MemoryInvariantError("SelectedFrame.evidence_mask disagrees with Read.evidence_mask") + if frame.evidence_mask and not frame.valid_mask: + raise MemoryInvariantError("padding cannot be evidence") + if frame.valid_mask: + if frame.frame_index != int(read.frame_indices[slot]): + raise MemoryInvariantError("SelectedFrame.frame_index disagrees with Read.frame_indices") + try: + capture_step = _nonnegative_int( + frame.capture_step, + f"SelectedFrame[{slot}].capture_step", + ) + except ValueError as exc: + raise MemoryInvariantError(str(exc)) from exc + if capture_step > read_step: + raise MemoryInvariantError("SelectedFrame.capture_step is not causal") + if previous_capture is not None and capture_step < previous_capture: + raise MemoryInvariantError("SelectedFrame.capture_step must be nondecreasing across valid slots") + expected_time = np.asarray( + ( + capture_step / denominator, + (read_step - capture_step) / denominator, + 0.0 if previous_capture is None else (capture_step - previous_capture) / denominator, + ), + dtype=np.float32, + ) + _validate_temporal_values(frame, expected_time, slot=slot) + valid_indices.append(frame.frame_index) + previous_capture = capture_step + elif frame != SelectedFrame.padding(): + raise MemoryInvariantError("invalid Phase-A slots must use canonical padding metadata") + if valid_indices != sorted(set(valid_indices)): + raise MemoryInvariantError("Phase-A valid frames must be sorted and unique") + return frames + + +def _validate_temporal_values( + frame: SelectedFrame, + expected: np.ndarray, + *, + slot: int, +) -> None: + raw = (frame.absolute_time, frame.relative_age, frame.delta_prev) + names = ("absolute_time", "relative_age", "delta_prev") + for name, value in zip(names, raw, strict=True): + if isinstance(value, (bool, np.bool_)) or not isinstance( + value, + (int, float, np.integer, np.floating), + ): + raise MemoryInvariantError(f"SelectedFrame[{slot}].{name} must be numeric") + actual = np.asarray(raw, dtype=np.float64) + if not np.all(np.isfinite(actual)): + raise MemoryInvariantError(f"SelectedFrame[{slot}] temporal coordinates must be finite") + if np.any((actual < 0.0) | (actual > 1.0)): + raise MemoryInvariantError(f"SelectedFrame[{slot}] normalized temporal coordinates must be in [0, 1]") + + # SelectedFrame values originate as Python numerics while the host wire and + # model consume float32. The only accepted source-to-wire rounding is the + # local float32 cell that maps to the explicitly derived canonical value. + # A derived positive zero is stricter: the source must be numeric zero and + # its float32 wire form must have no sign bit. This prevents underflow drift + # and IEEE negative zero from changing observation bytes or hashes. + canonical_wire = np.asarray(raw, dtype=np.float32) + expected_bits = expected.view(np.uint32) + canonical_bits = canonical_wire.view(np.uint32) + for index, (name, value) in enumerate(zip(names, raw, strict=True)): + if expected_bits[index] == 0 and (value != 0.0 or canonical_bits[index] != 0): + raise MemoryInvariantError(f"SelectedFrame[{slot}].{name} must encode zero as canonical +0.0") + if not np.array_equal(canonical_wire, expected): + raise MemoryInvariantError(f"SelectedFrame[{slot}] temporal coordinates disagree with capture/read steps") + + +def _token_layout(frames: Sequence[SelectedFrame], reader_mode: ReaderMode) -> np.ndarray: + counts = np.full(FRAME_BUDGET, FIXED_TOKENS_PER_FRAME, dtype=np.int32) + if reader_mode is ReaderMode.FIXED16: + counts.setflags(write=False) + return counts + if reader_mode is not ReaderMode.VARIABLE64: + raise NotImplementedError(f"reader mode is not materialized: {reader_mode}") + + evidence = [index for index, frame in enumerate(frames) if frame.valid_mask and frame.evidence_mask] + if len(evidence) > MAX_VARIABLE_EVIDENCE: + raise MemoryInvariantError( + f"variable64 supports at most {MAX_VARIABLE_EVIDENCE} evidence frames, got {len(evidence)}" + ) + background = [index for index, frame in enumerate(frames) if not frame.evidence_mask] + low_resolution_count = 4 * len(evidence) + if low_resolution_count > len(background): + raise MemoryInvariantError("variable64 does not have enough background slots") + + # Spend the reduced-resolution quota on padding first. For a full read, + # preserve the initial/current/recent anchors when possible and downsample + # the oldest remaining background slots. This ordering is deterministic + # and depends only on the already-frozen visual plan. + valid_slots = [index for index, frame in enumerate(frames) if frame.valid_mask] + protected = set(valid_slots[:1] + valid_slots[-5:]) + low_resolution_order = sorted( + background, + key=lambda index: ( + frames[index].valid_mask, + index in protected, + frames[index].frame_index, + index, + ), + ) + low_resolution = set(low_resolution_order[:low_resolution_count]) + for index in evidence: + counts[index] = 64 + for index in low_resolution: + counts[index] = 4 + + expected_high_background = FRAME_BUDGET - 5 * len(evidence) + high_background = sum(1 for index in background if counts[index] == FIXED_TOKENS_PER_FRAME) + if high_background != expected_high_background: + raise MemoryInvariantError("variable64 high-resolution background geometry drift") + if int(counts.sum()) != TOKEN_BUDGET: + raise MemoryInvariantError("variable64 must materialize exactly 512 tokens") + counts.setflags(write=False) + return counts + + +def _intervene_metadata( + frames: Sequence[SelectedFrame], + mode: MetadataMode, + *, + seed: int, + read_step: int, +) -> dict[str, np.ndarray]: + valid = np.asarray([frame.valid_mask for frame in frames], dtype=np.bool_) + evidence = np.asarray([frame.evidence_mask for frame in frames], dtype=np.bool_) + frame_indices = np.asarray([frame.frame_index for frame in frames], dtype=np.int32) + capture = np.asarray([frame.capture_step for frame in frames], dtype=np.int32) + time = np.asarray( + [[frame.absolute_time, frame.relative_age, frame.delta_prev] for frame in frames], + dtype=np.float32, + ) + role = np.asarray([int(frame.role_id) for frame in frames], dtype=np.int32) + event = _bucket_ids( + [frame.event_id for frame in frames], + vocab_size=EVENT_VOCAB_SIZE, + label="event_id", + ) + ordinal = np.asarray( + [frame.event_ordinal + 1 if frame.event_ordinal >= 0 else 0 for frame in frames], + dtype=np.int32, + ) + contract = _bucket_ids( + [frame.contract_id for frame in frames], + vocab_size=CONTRACT_VOCAB_SIZE, + label="contract_id", + ) + status = _bucket_ids( + [frame.status_id for frame in frames], + vocab_size=STATUS_VOCAB_SIZE, + label="status_id", + ) + confidence = np.asarray([frame.confidence for frame in frames], dtype=np.float32) + time_mask = np.repeat(valid[:, None], TIME_CHANNELS, axis=1) + # Background and padding carry only normalized temporal coordinates. All + # task-aware categorical IDs and masks remain neutral by contract. + role_mask = evidence.copy() + categorical_mask = evidence.copy() + + background = valid & ~evidence + if ( + np.any(role[background] != 0) + or np.any(event[background] != 0) + or np.any(ordinal[background] != 0) + or np.any(contract[background] != 0) + or np.any(status[background] != 0) + or np.any(confidence[background] != 0) + ): + raise MemoryInvariantError("background slots must have neutral task-aware metadata") + + if np.any(ordinal >= EVENT_ORDINAL_VOCAB_SIZE): + raise MemoryInvariantError(f"event ordinal exceeds reader vocabulary {EVENT_ORDINAL_VOCAB_SIZE - 1}") + + if mode is MetadataMode.TIME_SHUFFLED: + slots = np.flatnonzero(valid) + if slots.size > 1: + permutation = _nonidentity_permutation( + slots.size, + seed=seed, + identity=(read_step, *frame_indices[valid].tolist()), + ) + source = slots[permutation] + capture[slots] = capture[source] + time[slots] = time[source] + elif mode is MetadataMode.ORDER_REVERSED: + slots = np.flatnonzero(evidence) + if slots.size > 1: + ordinal[slots] = ordinal[slots[::-1]] + elif mode is MetadataMode.ROLE_ONLY: + capture.fill(0) + time.fill(0) + time_mask.fill(False) + elif mode is MetadataMode.TIME_ONLY: + role.fill(0) + event.fill(0) + ordinal.fill(0) + contract.fill(0) + status.fill(0) + confidence.fill(0) + evidence.fill(False) + role_mask.fill(False) + categorical_mask.fill(False) + elif mode is MetadataMode.NEUTRAL: + capture.fill(0) + time.fill(0) + role.fill(0) + event.fill(0) + ordinal.fill(0) + contract.fill(0) + status.fill(0) + confidence.fill(0) + evidence.fill(False) + time_mask.fill(False) + role_mask.fill(False) + categorical_mask.fill(False) + elif mode is not MetadataMode.CORRECT: + raise ValueError(f"unsupported metadata mode: {mode}") + + # Padding is neutral for every mode. The invariant frame index/valid mask + # remain available for parity audits but are never made task-aware. + for value in (capture, role, event, ordinal, contract, status): + value[~valid] = 0 + time[~valid] = 0 + confidence[~valid] = 0 + evidence[~valid] = False + time_mask[~valid] = False + role_mask[~valid] = False + categorical_mask[~valid] = False + return { + "frame_indices": frame_indices, + "capture_steps": capture, + "time_values": time, + "time_mask": time_mask, + "role_ids": role, + "role_mask": role_mask, + "event_ids": event, + "event_ordinals": ordinal, + "contract_ids": contract, + "status_ids": status, + "categorical_mask": categorical_mask, + "confidence": confidence, + "evidence_mask": evidence, + "valid_mask": valid, + } + + +def _repeat_metadata( + values: Mapping[str, np.ndarray], + token_counts: np.ndarray, +) -> PhaseATokenMetadata: + repeated: dict[str, np.ndarray] = {} + for name, value in values.items(): + repeated_value = np.repeat(value, token_counts, axis=0) + if repeated_value.shape[0] != TOKEN_BUDGET: + raise MemoryInvariantError(f"{name} did not materialize exactly 512 tokens") + repeated_value.setflags(write=False) + repeated[name] = repeated_value + return PhaseATokenMetadata(**repeated) + + +def _bucket_ids(values: Sequence[str], *, vocab_size: int, label: str) -> np.ndarray: + if vocab_size <= 1: + raise ValueError("categorical vocabularies must reserve a neutral bucket") + buckets: dict[int, str] = {} + output = np.zeros(len(values), dtype=np.int32) + for index, value in enumerate(values): + if value == "": + continue + if not isinstance(value, str): + raise MemoryInvariantError(f"{label} must be a string") + digest = hashlib.sha256(f"picmem-phase-a:{label}:{value}".encode()).digest() + bucket = int.from_bytes(digest[:8], "big") % (vocab_size - 1) + 1 + collision = buckets.get(bucket) + if collision is not None and collision != value: + raise MemoryInvariantError(f"{label} hash collision within one Read: {collision!r} and {value!r}") + buckets[bucket] = value + output[index] = bucket + return output + + +def _nonidentity_permutation( + size: int, + *, + seed: int, + identity: tuple[int, ...], +) -> np.ndarray: + payload = ":".join(str(value) for value in (seed, *identity)).encode() + mixed_seed = int.from_bytes(hashlib.sha256(payload).digest()[:8], "big") + permutation = np.random.default_rng(mixed_seed).permutation(size) + if np.array_equal(permutation, np.arange(size)): + permutation = np.roll(permutation, 1) + return permutation + + +def _nonnegative_int(value: Any, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) < 0: + raise ValueError(f"{name} must be a non-negative integer") + return int(value) + + +__all__ = [ + "CONTRACT_VOCAB_SIZE", + "EVENT_ORDINAL_VOCAB_SIZE", + "EVENT_VOCAB_SIZE", + "FACTOR_FIELDS", + "FIXED_TOKENS_PER_FRAME", + "FRAME_BUDGET", + "MAX_VARIABLE_EVIDENCE", + "OBSERVATION_FIELDS", + "STATUS_VOCAB_SIZE", + "TIME_CHANNELS", + "TOKEN_BUDGET", + "PhaseAFactors", + "PhaseAFramePlan", + "PhaseATokenMetadata", + "materialize_phase_a_read", +] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_runtime.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..7f62d29a877100f65f5d47751594b6932ee465ac --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/picmem_phase_a_runtime.py @@ -0,0 +1,176 @@ +"""Online Phase-A ``RuntimeReadSession`` to RoboMME ``MemoryBuffer`` bridge. + +This adapter owns no event semantics and performs no online frame selection. +It accepts only the strict standalone runtime session, materializes its +policy-visible ``Read`` with the already-reviewed reader geometry, and gathers +the corresponding features from the live ``MemoryBuffer``. Formal rollout +workers can therefore use the same 512-token path as offline training without +reimplementing it in the simulator loop. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from typing import Any + +import numpy as np +from mme_vla_suite.shared.mem_buffer import MemoryBuffer +from mme_vla_suite.training.picmem_phase_a_reader import ( + PhaseAFactors, + PhaseAFramePlan, + PhaseATokenMetadata, + materialize_phase_a_read, +) + +from picmem.memory.contracts import SelectionMode +from picmem.memory.memory import Read +from picmem.provenance.runtime_reader import RuntimeReadError, RuntimeReadSession, read_sha256 + + +@dataclass(frozen=True) +class RuntimePhaseAObservation: + """One exact runtime read and its raw, pre-normalization host tensors.""" + + read: Read + plan: PhaseAFramePlan + image: np.ndarray + position: np.ndarray + state: np.ndarray + mask: np.ndarray + metadata: PhaseATokenMetadata + read_sha256: str + image_sha256: str + position_sha256: str + state_sha256: str + mask_sha256: str + + def feature_hashes(self) -> dict[str, str]: + return { + "read_sha256": self.read_sha256, + "image_sha256": self.image_sha256, + "position_sha256": self.position_sha256, + "state_sha256": self.state_sha256, + "mask_sha256": self.mask_sha256, + } + + +def materialize_runtime_observation( + session: RuntimeReadSession, + memory_buffer: Any, + *, + step: int, + factors: PhaseAFactors, + metadata_seed: int, +) -> RuntimePhaseAObservation: + """Gather one relevant online read through the real host buffer method. + + Selection counterfactuals for an evaluation cohort require a separately + frozen mutation plan. Until that plan is installed, this online boundary + accepts only the relevant selector and fails closed for the other four + selection modes. + """ + + if type(session) is not RuntimeReadSession: + raise RuntimeReadError("runtime host adapter requires the exact identity-bound RuntimeReadSession class") + preview_method = session.preview_read + commit_method = session.commit_read + if ( + getattr(preview_method, "__func__", None) is not RuntimeReadSession.preview_read + or getattr(preview_method, "__self__", None) is not session + or getattr(commit_method, "__func__", None) is not RuntimeReadSession.commit_read + or getattr(commit_method, "__self__", None) is not session + ): + raise RuntimeReadError("runtime host RuntimeReadSession methods were replaced") + if type(factors) is not PhaseAFactors: + raise RuntimeReadError("runtime host adapter requires the exact PhaseAFactors class") + if factors.manager_mode is not session.manager_mode: + raise RuntimeReadError( + "runtime Phase-A manager_mode differs from the identity-bound session" + ) + if factors.selection_mode is not SelectionMode.RELEVANT: + raise NotImplementedError("online selection counterfactuals require a frozen rollout mutation plan") + if isinstance(step, bool) or not isinstance(step, (int, np.integer)) or int(step) < 0: + raise RuntimeReadError("runtime host step must be a non-negative integer") + if type(memory_buffer) is not MemoryBuffer: + raise RuntimeReadError("runtime host requires the exact pinned MemoryBuffer class") + if memory_buffer.num_views != 1: + raise RuntimeReadError("runtime host requires a one-view Phase-A MemoryBuffer") + prepare_method = memory_buffer.prepare_phase_a_frame_sampling + gather_method = memory_buffer.default_history_feats_gather_fn + if ( + getattr(prepare_method, "__func__", None) is not MemoryBuffer.prepare_phase_a_frame_sampling + or getattr(prepare_method, "__self__", None) is not memory_buffer + or getattr(gather_method, "__func__", None) is not MemoryBuffer.default_history_feats_gather_fn + or getattr(gather_method, "__self__", None) is not memory_buffer + ): + raise RuntimeReadError("runtime host MemoryBuffer methods were replaced") + + # Session advancement is a two-phase operation. A malformed/missing host + # feature, dtype drift, or non-finite tensor must not consume the read step + # and thereby make a legitimate earlier event permanently late. + read = RuntimeReadSession.preview_read(session, int(step)) + plan = materialize_phase_a_read( + read, + factors, + metadata_seed=metadata_seed, + selection_applied=SelectionMode.RELEVANT, + ) + image, position, state, mask = MemoryBuffer.prepare_phase_a_frame_sampling( + memory_buffer, + int(step), + 512, + plan.frame_indices, + plan.valid_mask, + plan.token_counts, + MemoryBuffer.default_history_feats_gather_fn.__get__(memory_buffer, MemoryBuffer), + ) + tensors = tuple(np.asarray(value) for value in (image, position, state, mask)) + expected_shapes = ((512, 2048), (512, 768), (512, 8), (512,)) + if tuple(value.shape for value in tensors) != expected_shapes: + raise RuntimeReadError("runtime MemoryBuffer tensor geometry drift") + expected_dtypes = ("bfloat16", "float32", "float32", "bool") + actual_dtypes = tuple(value.dtype.name for value in tensors) + if actual_dtypes != expected_dtypes: + raise RuntimeReadError( + f"runtime MemoryBuffer tensor dtype drift: expected {expected_dtypes}, got {actual_dtypes}" + ) + if any(not bool(np.isfinite(value).all()) for value in tensors[:3]): + raise RuntimeReadError("runtime MemoryBuffer tensors must be finite") + metadata = plan.metadata + if not np.array_equal(tensors[3], metadata.valid_mask): + raise RuntimeReadError("runtime visual and metadata token masks disagree") + prepared_read_sha256 = read_sha256(read) + feature_hashes = tuple(_array_sha256(value) for value in tensors) + for value in tensors: + value.setflags(write=False) + committed_read = RuntimeReadSession.commit_read(session, read) + committed_read_sha256 = read_sha256(committed_read) + if committed_read_sha256 != prepared_read_sha256: + raise RuntimeReadError("runtime read changed during host materialization") + return RuntimePhaseAObservation( + read=committed_read, + plan=plan, + image=tensors[0], + position=tensors[1], + state=tensors[2], + mask=tensors[3], + metadata=metadata, + read_sha256=committed_read_sha256, + image_sha256=feature_hashes[0], + position_sha256=feature_hashes[1], + state_sha256=feature_hashes[2], + mask_sha256=feature_hashes[3], + ) + + +def _array_sha256(value: np.ndarray) -> str: + array = np.ascontiguousarray(value) + digest = hashlib.sha256() + digest.update(str(array.dtype).encode("ascii")) + digest.update(str(array.shape).encode("ascii")) + digest.update(array.tobytes()) + return digest.hexdigest() + + +__all__ = ["RuntimePhaseAObservation", "materialize_runtime_observation"] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/semantic_transition_reader.py b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/semantic_transition_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..70217de21054c1e34f639d7b4ae067d93dbcae62 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/src/mme_vla_suite/training/semantic_transition_reader.py @@ -0,0 +1,260 @@ +"""Strict RoboMME adapter for semantic-transition training targets. + +The canonical manifest and target construction live in :mod:`picmem`. This +small host adapter verifies one independently pinned manifest at dataset +startup and performs constant-time exact-key lookups for scalar training rows. +Manifest rows stay strict; an opt-in mixed-dataset mode emits masked neutral +metadata only for episode-step identities absent from the manifest. +""" + +from __future__ import annotations + +from numbers import Integral +from pathlib import Path + +import numpy as np +from picmem.data.semantic_transition import TRANSITION_CONTEXT_LENGTH +from picmem.data.semantic_transition import TRANSITION_CONTEXT_WIDTH +from picmem.data.semantic_transition import TransitionRowKey +from picmem.data.semantic_transition import TransitionSequenceManifest +from picmem.data.semantic_transition import load_transition_sequence_manifest + +TRANSITION_TRAINING_METADATA_FIELDS = frozenset( + { + "transition_span_target", + "transition_last_span_target", + "transition_status_valid", + "transition_last_span_valid", + "transition_context_action_delta", + "transition_context_state_delta", + "transition_context_relative_age", + "transition_context_valid_mask", + } +) + + +class SemanticTransitionReaderError(RuntimeError): + """Transition training configuration or row resolution failed closed.""" + + +class SemanticTransitionTrainingReader: + """Load one hash-pinned manifest and resolve exact RoboMME training rows.""" + + __slots__ = ( + "_allow_unlabeled_rows", + "_expected_sha256", + "_manifest", + "_manifest_path", + "_manifest_task_id_by_episode", + "_task_id_by_position", + ) + + def __init__( + self, + *, + manifest_path: str | Path | None, + expected_sha256: str | None, + allow_unlabeled_rows: bool = False, + ) -> None: + if type(allow_unlabeled_rows) is not bool: + raise TypeError("allow_unlabeled_rows must be bool") + if manifest_path is None or (isinstance(manifest_path, str) and not manifest_path.strip()): + raise SemanticTransitionReaderError("enabled transition training requires a manifest path") + if expected_sha256 is None or not isinstance(expected_sha256, str) or not expected_sha256.strip(): + raise SemanticTransitionReaderError( + "enabled transition training requires an independently supplied manifest SHA-256" + ) + + path = Path(manifest_path).expanduser() + try: + manifest = load_transition_sequence_manifest(path, expected_sha256=expected_sha256) + except (TypeError, ValueError) as exc: + raise SemanticTransitionReaderError(f"transition training manifest verification failed: {exc}") from exc + + self._manifest_path = path + self._expected_sha256 = expected_sha256 + self._manifest = manifest + self._allow_unlabeled_rows = allow_unlabeled_rows + manifest_task_id_by_episode: dict[int, str] = {} + for sequence in manifest.sequences: + episode_id = sequence.start_key.global_episode_id + task_id = sequence.start_key.task_id + existing_task_id = manifest_task_id_by_episode.setdefault( + episode_id, + task_id, + ) + if existing_task_id != task_id: + raise SemanticTransitionReaderError( + "transition manifest maps one global episode to multiple task ids: " + f"{episode_id}" + ) + self._manifest_task_id_by_episode = manifest_task_id_by_episode + task_id_by_position: dict[tuple[int, int], str] = {} + for row in manifest.training_rows(): + position = (row.key.global_episode_id, row.key.step_idx) + existing_task_id = task_id_by_position.setdefault(position, row.key.task_id) + if existing_task_id != row.key.task_id: + raise SemanticTransitionReaderError( + "transition manifest maps one episode-step to multiple task ids: " + f"{position}" + ) + self._task_id_by_position = task_id_by_position + + def __getstate__(self) -> tuple[Path, str, bool]: + return self._manifest_path, self._expected_sha256, self._allow_unlabeled_rows + + def __setstate__(self, state: tuple[Path, str, bool]) -> None: + manifest_path, expected_sha256, allow_unlabeled_rows = state + self.__init__( + manifest_path=manifest_path, + expected_sha256=expected_sha256, + allow_unlabeled_rows=allow_unlabeled_rows, + ) + + @property + def manifest_path(self) -> Path: + return self._manifest_path + + @property + def expected_sha256(self) -> str: + return self._expected_sha256 + + @property + def manifest(self) -> TransitionSequenceManifest: + return self._manifest + + @property + def allow_unlabeled_rows(self) -> bool: + return self._allow_unlabeled_rows + + def metadata_for( + self, + *, + task_id: str | None, + global_episode_id: int, + step_idx: int, + owner_sequence_id: str | None = None, + ) -> dict[str, np.ndarray]: + """Return the complete numeric contract for one exact logical row. + + Dataset adjacency is never consulted. An overlapping row must name + its owner sequence, and a target without its causal 48-step context is + rejected instead of being trained as an all-zero history. + """ + + position = _row_position(global_episode_id, step_idx) + position_is_labeled = position in self._task_id_by_position + if task_id is None: + if ( + self._allow_unlabeled_rows + and position[0] not in self._manifest_task_id_by_episode + ): + return runtime_only_zero_transition_metadata() + raise SemanticTransitionReaderError( + f"transition training requires a manifest task id for episode {global_episode_id}" + ) + key = _row_key(task_id, global_episode_id, step_idx) + if self._allow_unlabeled_rows and not position_is_labeled: + expected_task_id = self._manifest_task_id_by_episode.get(position[0]) + if expected_task_id is not None and task_id != expected_task_id: + raise SemanticTransitionReaderError( + "transition training task id does not match manifest episode " + f"{global_episode_id}: expected {expected_task_id!r}, got {task_id!r}" + ) + return runtime_only_zero_transition_metadata() + try: + training_row = self._manifest.row_target(key, owner_sequence_id=owner_sequence_id) + except KeyError as exc: + raise SemanticTransitionReaderError(f"transition training target is missing for exact row {key}") from exc + except (TypeError, ValueError) as exc: + raise SemanticTransitionReaderError(f"cannot resolve transition training row {key}: {exc}") from exc + + if training_row.target.realized_transition_context is None: + raise SemanticTransitionReaderError(f"transition training context is missing for exact row {key}") + + metadata = training_row.as_loader_metadata() + actual_fields = frozenset(metadata) + if actual_fields != TRANSITION_TRAINING_METADATA_FIELDS: + missing = sorted(TRANSITION_TRAINING_METADATA_FIELDS - actual_fields) + extra = sorted(actual_fields - TRANSITION_TRAINING_METADATA_FIELDS) + raise SemanticTransitionReaderError( + f"transition training metadata schema drift for exact row {key}: missing={missing}, extra={extra}" + ) + return metadata + + +def create_semantic_transition_training_reader( + *, + enabled: bool, + manifest_path: str | Path | None = None, + expected_sha256: str | None = None, + allow_unlabeled_rows: bool = False, +) -> SemanticTransitionTrainingReader | None: + """Create the one dataset-level reader, or ``None`` when training is off.""" + + if type(enabled) is not bool: + raise TypeError("enabled must be bool") + if not enabled: + return None + return SemanticTransitionTrainingReader( + manifest_path=manifest_path, + expected_sha256=expected_sha256, + allow_unlabeled_rows=allow_unlabeled_rows, + ) + + +def runtime_only_zero_transition_metadata() -> dict[str, np.ndarray]: + """Return neutral fields for inference or explicitly masked training rows. + + The legacy name is retained for existing callers. Strict training never + falls back to these values; the mixed reader uses them only for positions + absent from the manifest, with both supervision-valid flags false. + """ + + return { + "transition_span_target": np.asarray(0.0, dtype=np.float32), + "transition_last_span_target": np.asarray(0.0, dtype=np.float32), + "transition_status_valid": np.zeros((), dtype=np.bool_), + "transition_last_span_valid": np.zeros((), dtype=np.bool_), + "transition_context_action_delta": np.zeros( + (TRANSITION_CONTEXT_LENGTH, TRANSITION_CONTEXT_WIDTH), + dtype=np.float32, + ), + "transition_context_state_delta": np.zeros( + (TRANSITION_CONTEXT_LENGTH, TRANSITION_CONTEXT_WIDTH), + dtype=np.float32, + ), + "transition_context_relative_age": np.zeros(TRANSITION_CONTEXT_LENGTH, dtype=np.float32), + "transition_context_valid_mask": np.zeros(TRANSITION_CONTEXT_LENGTH, dtype=np.bool_), + } + + +def _row_key(task_id: str, global_episode_id: int, step_idx: int) -> TransitionRowKey: + episode, step = _row_position(global_episode_id, step_idx) + try: + return TransitionRowKey(task_id, episode, step) + except (TypeError, ValueError) as exc: + raise SemanticTransitionReaderError(f"invalid exact transition row key: {exc}") from exc + + +def _row_position(global_episode_id: int, step_idx: int) -> tuple[int, int]: + if isinstance(global_episode_id, bool) or not isinstance(global_episode_id, Integral): + raise SemanticTransitionReaderError("global_episode_id must be a non-negative integer") + if isinstance(step_idx, bool) or not isinstance(step_idx, Integral): + raise SemanticTransitionReaderError("step_idx must be a non-negative integer") + episode = int(global_episode_id) + step = int(step_idx) + if episode < 0 or step < 0: + raise SemanticTransitionReaderError( + "global_episode_id and step_idx must be non-negative" + ) + return episode, step + + +__all__ = [ + "TRANSITION_TRAINING_METADATA_FIELDS", + "SemanticTransitionReaderError", + "SemanticTransitionTrainingReader", + "create_semantic_transition_training_reader", + "runtime_only_zero_transition_metadata", +] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/transition_status_manifest.json b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/transition_status_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ccb128b93cd2ff2870e7a5367c1aa08f5da2e109 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/integrations/robomme/transition_status_manifest.json @@ -0,0 +1,67 @@ +{ + "schema_version": "picmem_robomme_transition_status_overlay_v1", + "overlay_id": "transition_status_v1", + "copied_files": [ + { + "path": "src/mme_vla_suite/models/config/robomme/perceptual-picmem-transition-v1-modul.yaml", + "preimage_sha256": null, + "postimage_sha256": "0691f21107e9746131d7ecefd380a1238b8beeeeee758da0ec440a5d97296827" + }, + { + "path": "src/mme_vla_suite/models/representation/transition_status.py", + "preimage_sha256": null, + "postimage_sha256": "f2820eb900e8b8badee27b0dabb8d09625b1a35ad96997d56de76ea26662f7e4" + }, + { + "path": "src/mme_vla_suite/policies/semantic_transition_runtime.py", + "preimage_sha256": null, + "postimage_sha256": "6945725b52b4a4a11b6cea748378fcac0ef502fece1632800794d35025126df6" + }, + { + "path": "src/mme_vla_suite/training/semantic_transition_reader.py", + "preimage_sha256": null, + "postimage_sha256": "232977ebfc6ebe948f22f62f917bf73a47c0e811fc26c44c9d403a13f37b198e" + } + ], + "host_patch": { + "path": "patches/transition_status_v1_host.patch", + "sha256": "a1f9042f777aabe1d720a6e7e5fa9774d77de2231cc770ce939eefc308479a70", + "files": [ + { + "path": "examples/robomme/eval.py", + "preimage_sha256": "2b51b942af18f7a3412814b66eca67a0fc4ff374794bceac5f44d87e1e367c41", + "postimage_sha256": "3c47df922604feb58e90200249762bd74f3bdba04131f1b81aa6d0b6349d354e" + }, + { + "path": "src/mme_vla_suite/models/integration/history_observation.py", + "preimage_sha256": "e510f75496770d418d770f3e2a56f6ddc9d972a5ff68b6cd14b7a15665ec39a8", + "postimage_sha256": "dedfd82ff19a83395f721c4bb8ed1c3b4600c9e3d234d6deaced8895f452d4e3" + }, + { + "path": "src/mme_vla_suite/models/integration/history_pi0.py", + "preimage_sha256": "9192bfc229ac1386a3d36835c6d1e220617431d44b462016b062bc3df07a337f", + "postimage_sha256": "b5c5d055bd923e02b3381b1da6007b75393fdf13fbd5dfdc9c85e82bb9852638" + }, + { + "path": "src/mme_vla_suite/policies/policy.py", + "preimage_sha256": "dc31fce752172e1861de4840445b6c300dfa2a675a797dedbee1b108f7f4e20d", + "postimage_sha256": "85552f440e644ab31c63fa8ddcb856522085a7e414fbacd87eff0ef89e9ba2a5" + }, + { + "path": "src/mme_vla_suite/policies/robomme_policy.py", + "preimage_sha256": "78dbf3393bac91a16096d02b17239ca0e14c38be7ce32042d88f96b1e89e35e2", + "postimage_sha256": "9cfe10577679189f2b3af345d41c7b40625cb0aef1b2b7077107b532565826cf" + }, + { + "path": "src/mme_vla_suite/training/config.py", + "preimage_sha256": "47041573dae2c48b99b56035763f4fd611f6cc5395e7875849dd6017227ce247", + "postimage_sha256": "152334f30e20ea529dffe7932fe5575a5c4a11f4f1514fb56718272d9d5ef6c2" + }, + { + "path": "src/mme_vla_suite/training/dataset.py", + "preimage_sha256": "62f867c89b0073f484ba15ff1e3a5f5554ec520bcae00b06cdcff3f19fbf0d3b", + "postimage_sha256": "db08b26dd964aed7da69f0fc02ed064b688c453777277a274614dd1f0dcbb34a" + } + ] + } +} diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/pyproject.toml b/checkpoints/r2/shuffle/baseline/step9000/code/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae6730909568143f8f5d28564ce1925497620641 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/pyproject.toml @@ -0,0 +1,128 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "picmem-dev" +version = "0.2.0" +description = "Bounded contract memory for long-horizon robot policies" +readme = "README.md" +requires-python = ">=3.10,<3.14" +license = { file = "LICENSE" } +dependencies = [ + "cryptography==45.0.7", + "numpy>=1.26", +] + +[project.optional-dependencies] +hdf5 = ["h5py>=3.13"] +lerobot = ["polars>=1.30"] +semantic-annotation = [ + "h5py>=3.13", + "openai>=2,<3", + "Pillow>=10.4", + "polars>=1.30", +] +model = [ + "flax==0.10.2", + "jax==0.5.3", + "jaxtyping==0.2.36", +] +counterfactual = ["jax==0.5.3"] +samplers = ["torch>=2.8,<2.9"] +training = [ + "jax==0.5.3", + "torch>=2.8,<2.9", +] +dev = [ + "flax==0.10.2", + "h5py>=3.13", + "jax==0.5.3", + "jaxtyping==0.2.36", + "omegaconf>=2.3", + "polars>=1.30", + "pytest>=8.3", + "ruff>=0.8", + "torch>=2.8,<2.9", +] + +[project.scripts] +picmem-audit = "picmem.cli.audit:main" +picmem-crosswalk-receipt = "picmem.cli.crosswalk_receipt:main" +picmem-dense-caption = "picmem.cli.dense_caption_v7:main" +picmem-dense-caption-all = "picmem.cli.dense_caption_v7_all:main" +picmem-semantic-annotate = "picmem.cli.semantic_annotate:main" +picmem-semantic-calibration = "picmem.cli.semantic_calibration:main" +picmem-stage1-archive = "picmem.cli.stage1_archive:main" +picmem-stage1-refine = "picmem.cli.stage1_refine:main" +picmem-stage2-task-semantics = "picmem.cli.stage2_task_semantics_v7:main" +picmem-stage3-temporal-mapping = "picmem.cli.stage3_temporal_mapping:main" +picmem-stage4-semantic-memory = "picmem.cli.stage4_semantic_memory:main" +picmem-vllm-server = "picmem.cli.vllm_server:main" +picmem-admit = "picmem.ops.admission:main" +picmem-amlt = "picmem.ops.amlt:main" +picmem-cadence = "picmem.ops.cadence:main" +picmem-checkpoint = "picmem.ops.checkpoint:main" +picmem-formal-runtime = "picmem.ops.formal_runtime:main" +picmem-ledger = "picmem.ops.scheduler:main" +picmem-registry = "picmem.ops.registry:main" +picmem-runtime-profile = "picmem.ops.runtime_profiles:main" +picmem-run084-order = "picmem.sampling.run084_sample_order:main" +picmem-sku-smoke-evidence = "picmem.ops.sku_smoke_evidence:main" +picmem-submit = "picmem.ops.submit:main" +picmem-supervisor = "picmem.ops.supervisor:main" +picmem-uv-cache = "picmem.ops.uv_cache:main" +picmem-watchdog = "picmem.ops.watchdog:main" + +[tool.hatch.build.targets.wheel] +packages = ["src/picmem"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["src", "."] + +[tool.ruff] +line-length = 120 +target-version = "py310" +# robomme/ is the vendored upstream RoboMME workspace, carried here so an +# experiment needs no second checkout. It ships its own ruff configuration and +# its own style history; linting it under PIC-Mem's rules would report ~1.5k +# pre-existing upstream findings that nobody here is entitled to "fix". +extend-exclude = ["robomme"] + +[tool.ruff.lint] +select = ["B", "E", "F", "I", "RUF", "SIM", "UP"] +ignore = ["F722"] + +# These two files are hash-pinned mirrors of the upstream RoboMME host. Keep +# its existing style debt isolated here instead of reformatting the reviewed +# overlay preimages; all PIC-Mem additions and the rest of the repository stay +# under the normal rule set. +[tool.ruff.lint.per-file-ignores] +"integrations/robomme/src/mme_vla_suite/shared/mem_buffer.py" = [ + "E401", + "E501", + "F403", + "F405", + "F541", + "I001", + "SIM108", + "UP035", +] +"integrations/robomme/src/mme_vla_suite/training/dataset.py" = [ + "B905", + "E501", + "RUF013", + "RUF046", + "SIM115", +] + +# The reviewed AzureML image is CUDA 12.6, so torch must come from the matching +# PyTorch index instead of the PyPI default, which publishes a cu128 build. +[[tool.uv.index]] +name = "pytorch-cu126" +url = "https://download.pytorch.org/whl/cu126" +explicit = true + +[tool.uv.sources] +torch = { index = "pytorch-cu126" } diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/LICENSE b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/__init__.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc1f76bc69e3f559bee6253b24fc93acee9e1f9 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/__init__.py @@ -0,0 +1 @@ +__version__ = "0.1.0" diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/action_chunk_broker.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/action_chunk_broker.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa9d83d023b7c0c60a1d05531343af01e72d09b --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/action_chunk_broker.py @@ -0,0 +1,50 @@ +from typing import Dict + +import numpy as np +import tree +from typing_extensions import override + +from openpi_client import base_policy as _base_policy + + +class ActionChunkBroker(_base_policy.BasePolicy): + """Wraps a policy to return action chunks one-at-a-time. + + Assumes that the first dimension of all action fields is the chunk size. + + A new inference call to the inner policy is only made when the current + list of chunks is exhausted. + """ + + def __init__(self, policy: _base_policy.BasePolicy, action_horizon: int): + self._policy = policy + self._action_horizon = action_horizon + self._cur_step: int = 0 + + self._last_results: Dict[str, np.ndarray] | None = None + + @override + def infer(self, obs: Dict) -> Dict: # noqa: UP006 + if self._last_results is None: + self._last_results = self._policy.infer(obs) + self._cur_step = 0 + + def slicer(x): + if isinstance(x, np.ndarray): + return x[self._cur_step, ...] + else: + return x + + results = tree.map_structure(slicer, self._last_results) + self._cur_step += 1 + + if self._cur_step >= self._action_horizon: + self._last_results = None + + return results + + @override + def reset(self) -> None: + self._policy.reset() + self._last_results = None + self._cur_step = 0 diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/base_policy.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/base_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2f4290651b1b7bab3bd9549b47876838f5b51629 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/base_policy.py @@ -0,0 +1,12 @@ +import abc +from typing import Dict + + +class BasePolicy(abc.ABC): + @abc.abstractmethod + def infer(self, obs: Dict) -> Dict: + """Infer actions from observations.""" + + def reset(self) -> None: + """Reset the policy to its initial state.""" + pass diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..7a971b9d5f6b1495fd6cdea202ffa607d8b34bf0 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools.py @@ -0,0 +1,58 @@ +import numpy as np +from PIL import Image + + +def convert_to_uint8(img: np.ndarray) -> np.ndarray: + """Converts an image to uint8 if it is a float image. + + This is important for reducing the size of the image when sending it over the network. + """ + if np.issubdtype(img.dtype, np.floating): + img = (255 * img).astype(np.uint8) + return img + + +def resize_with_pad(images: np.ndarray, height: int, width: int, method=Image.BILINEAR) -> np.ndarray: + """Replicates tf.image.resize_with_pad for multiple images using PIL. Resizes a batch of images to a target height. + + Args: + images: A batch of images in [..., height, width, channel] format. + height: The target height of the image. + width: The target width of the image. + method: The interpolation method to use. Default is bilinear. + + Returns: + The resized images in [..., height, width, channel]. + """ + # If the images are already the correct size, return them as is. + if images.shape[-3:-1] == (height, width): + return images + + original_shape = images.shape + + images = images.reshape(-1, *original_shape[-3:]) + resized = np.stack([_resize_with_pad_pil(Image.fromarray(im), height, width, method=method) for im in images]) + return resized.reshape(*original_shape[:-3], *resized.shape[-3:]) + + +def _resize_with_pad_pil(image: Image.Image, height: int, width: int, method: int) -> Image.Image: + """Replicates tf.image.resize_with_pad for one image using PIL. Resizes an image to a target height and + width without distortion by padding with zeros. + + Unlike the jax version, note that PIL uses [width, height, channel] ordering instead of [batch, h, w, c]. + """ + cur_width, cur_height = image.size + if cur_width == width and cur_height == height: + return image # No need to resize if the image is already the correct size. + + ratio = max(cur_width / width, cur_height / height) + resized_height = int(cur_height / ratio) + resized_width = int(cur_width / ratio) + resized_image = image.resize((resized_width, resized_height), resample=method) + + zero_image = Image.new(resized_image.mode, (width, height), 0) + pad_height = max(0, int((height - resized_height) / 2)) + pad_width = max(0, int((width - resized_width) / 2)) + zero_image.paste(resized_image, (pad_width, pad_height)) + assert zero_image.size == (width, height) + return zero_image diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools_test.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8d4b4b92030ea869712b312581e26243035aafba --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/image_tools_test.py @@ -0,0 +1,37 @@ +import numpy as np + +import openpi_client.image_tools as image_tools + + +def test_resize_with_pad_shapes(): + # Test case 1: Resize image with larger dimensions + images = np.zeros((2, 10, 10, 3), dtype=np.uint8) # Input images of shape (batch_size, height, width, channels) + height = 20 + width = 20 + resized_images = image_tools.resize_with_pad(images, height, width) + assert resized_images.shape == (2, height, width, 3) + assert np.all(resized_images == 0) + + # Test case 2: Resize image with smaller dimensions + images = np.zeros((3, 30, 30, 3), dtype=np.uint8) + height = 15 + width = 15 + resized_images = image_tools.resize_with_pad(images, height, width) + assert resized_images.shape == (3, height, width, 3) + assert np.all(resized_images == 0) + + # Test case 3: Resize image with the same dimensions + images = np.zeros((1, 50, 50, 3), dtype=np.uint8) + height = 50 + width = 50 + resized_images = image_tools.resize_with_pad(images, height, width) + assert resized_images.shape == (1, height, width, 3) + assert np.all(resized_images == 0) + + # Test case 3: Resize image with odd-numbered padding + images = np.zeros((1, 256, 320, 3), dtype=np.uint8) + height = 60 + width = 80 + resized_images = image_tools.resize_with_pad(images, height, width) + assert resized_images.shape == (1, height, width, 3) + assert np.all(resized_images == 0) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..007f755edf54565579376b077eec7f7f715e1b96 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy.py @@ -0,0 +1,57 @@ +"""Adds NumPy array support to msgpack. + +msgpack is good for (de)serializing data over a network for multiple reasons: +- msgpack is secure (as opposed to pickle/dill/etc which allow for arbitrary code execution) +- msgpack is widely used and has good cross-language support +- msgpack does not require a schema (as opposed to protobuf/flatbuffers/etc) which is convenient in dynamically typed + languages like Python and JavaScript +- msgpack is fast and efficient (as opposed to readable formats like JSON/YAML/etc); I found that msgpack was ~4x faster + than pickle for serializing large arrays using the below strategy + +The code below is adapted from https://github.com/lebedov/msgpack-numpy. The reason not to use that library directly is +that it falls back to pickle for object arrays. +""" + +import functools + +import msgpack +import numpy as np + + +def pack_array(obj): + if (isinstance(obj, (np.ndarray, np.generic))) and obj.dtype.kind in ("V", "O", "c"): + raise ValueError(f"Unsupported dtype: {obj.dtype}") + + if isinstance(obj, np.ndarray): + return { + b"__ndarray__": True, + b"data": obj.tobytes(), + b"dtype": obj.dtype.str, + b"shape": obj.shape, + } + + if isinstance(obj, np.generic): + return { + b"__npgeneric__": True, + b"data": obj.item(), + b"dtype": obj.dtype.str, + } + + return obj + + +def unpack_array(obj): + if b"__ndarray__" in obj: + return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"]) + + if b"__npgeneric__" in obj: + return np.dtype(obj[b"dtype"]).type(obj[b"data"]) + + return obj + + +Packer = functools.partial(msgpack.Packer, default=pack_array) +packb = functools.partial(msgpack.packb, default=pack_array) + +Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_array) +unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_array) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4c774ba468aa6948e154cb2008bac8f6128a4593 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py @@ -0,0 +1,45 @@ +import numpy as np +import pytest +import tree + +from openpi_client import msgpack_numpy + + +def _check(expected, actual): + if isinstance(expected, np.ndarray): + assert expected.shape == actual.shape + assert expected.dtype == actual.dtype + assert np.array_equal(expected, actual, equal_nan=expected.dtype.kind == "f") + else: + assert expected == actual + + +@pytest.mark.parametrize( + "data", + [ + 1, # int + 1.0, # float + "hello", # string + np.bool_(True), # boolean scalar + np.array([1, 2, 3])[0], # int scalar + np.str_("asdf"), # string scalar + [1, 2, 3], # list + {"key": "value"}, # dict + {"key": [1, 2, 3]}, # nested dict + np.array(1.0), # 0D array + np.array([1, 2, 3], dtype=np.int32), # 1D integer array + np.array(["asdf", "qwer"]), # string array + np.array([True, False]), # boolean array + np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32), # 2D float array + np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=np.int16), # 3D integer array + np.array([np.nan, np.inf, -np.inf]), # special float values + {"arr": np.array([1, 2, 3]), "nested": {"arr": np.array([4, 5, 6])}}, # nested dict with arrays + [np.array([1, 2]), np.array([3, 4])], # list of arrays + np.zeros((3, 4, 5), dtype=np.float32), # 3D zeros + np.ones((2, 3), dtype=np.float64), # 2D ones with double precision + ], +) +def test_pack_unpack(data): + packed = msgpack_numpy.packb(data) + unpacked = msgpack_numpy.unpackb(packed) + tree.map_structure(_check, data, unpacked) diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/agent.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c3ab66ef618ad9ecbff7b81ad9340a4604128c --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/agent.py @@ -0,0 +1,17 @@ +import abc + + +class Agent(abc.ABC): + """An Agent is the thing with agency, i.e. the entity that makes decisions. + + Agents receive observations about the state of the world, and return actions + to take in response. + """ + + @abc.abstractmethod + def get_action(self, observation: dict) -> dict: + """Query the agent for the next action.""" + + @abc.abstractmethod + def reset(self) -> None: + """Reset the agent to its initial state.""" diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..65227c44dae667d9b2743b6bc1026e791cec35c4 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py @@ -0,0 +1,18 @@ +from typing_extensions import override + +from openpi_client import base_policy as _base_policy +from openpi_client.runtime import agent as _agent + + +class PolicyAgent(_agent.Agent): + """An agent that uses a policy to determine actions.""" + + def __init__(self, policy: _base_policy.BasePolicy) -> None: + self._policy = policy + + @override + def get_action(self, observation: dict) -> dict: + return self._policy.infer(observation) + + def reset(self) -> None: + self._policy.reset() diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/environment.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..664ac4678aaaa3aecf52268a6a09d1d1fc974226 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/environment.py @@ -0,0 +1,32 @@ +import abc + + +class Environment(abc.ABC): + """An Environment represents the robot and the environment it inhabits. + + The primary contract of environments is that they can be queried for observations + about their state, and have actions applied to them to change that state. + """ + + @abc.abstractmethod + def reset(self) -> None: + """Reset the environment to its initial state. + + This will be called once before starting each episode. + """ + + @abc.abstractmethod + def is_episode_complete(self) -> bool: + """Allow the environment to signal that the episode is complete. + + This will be called after each step. It should return `True` if the episode is + complete (either successfully or unsuccessfully), and `False` otherwise. + """ + + @abc.abstractmethod + def get_observation(self) -> dict: + """Query the environment for the current state.""" + + @abc.abstractmethod + def apply_action(self, action: dict) -> None: + """Take an action in the environment.""" diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/runtime.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..9552be091a26e163d60cab8071df4716524bf2e8 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/runtime.py @@ -0,0 +1,92 @@ +import logging +import threading +import time + +from openpi_client.runtime import agent as _agent +from openpi_client.runtime import environment as _environment +from openpi_client.runtime import subscriber as _subscriber + + +class Runtime: + """The core module orchestrating interactions between key components of the system.""" + + def __init__( + self, + environment: _environment.Environment, + agent: _agent.Agent, + subscribers: list[_subscriber.Subscriber], + max_hz: float = 0, + num_episodes: int = 1, + max_episode_steps: int = 0, + ) -> None: + self._environment = environment + self._agent = agent + self._subscribers = subscribers + self._max_hz = max_hz + self._num_episodes = num_episodes + self._max_episode_steps = max_episode_steps + + self._in_episode = False + self._episode_steps = 0 + + def run(self) -> None: + """Runs the runtime loop continuously until stop() is called or the environment is done.""" + for _ in range(self._num_episodes): + self._run_episode() + + # Final reset, this is important for real environments to move the robot to its home position. + self._environment.reset() + + def run_in_new_thread(self) -> threading.Thread: + """Runs the runtime loop in a new thread.""" + thread = threading.Thread(target=self.run) + thread.start() + return thread + + def mark_episode_complete(self) -> None: + """Marks the end of an episode.""" + self._in_episode = False + + def _run_episode(self) -> None: + """Runs a single episode.""" + logging.info("Starting episode...") + self._environment.reset() + self._agent.reset() + for subscriber in self._subscribers: + subscriber.on_episode_start() + + self._in_episode = True + self._episode_steps = 0 + step_time = 1 / self._max_hz if self._max_hz > 0 else 0 + last_step_time = time.time() + + while self._in_episode: + self._step() + self._episode_steps += 1 + + # Sleep to maintain the desired frame rate + now = time.time() + dt = now - last_step_time + if dt < step_time: + time.sleep(step_time - dt) + last_step_time = time.time() + else: + last_step_time = now + + logging.info("Episode completed.") + for subscriber in self._subscribers: + subscriber.on_episode_end() + + def _step(self) -> None: + """A single step of the runtime loop.""" + observation = self._environment.get_observation() + action = self._agent.get_action(observation) + self._environment.apply_action(action) + + for subscriber in self._subscribers: + subscriber.on_step(observation, action) + + if self._environment.is_episode_complete() or ( + self._max_episode_steps > 0 and self._episode_steps >= self._max_episode_steps + ): + self.mark_episode_complete() diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/subscriber.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/subscriber.py new file mode 100644 index 0000000000000000000000000000000000000000..7c69edaa8e814dfcfe56b78b774578fe37f79428 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/runtime/subscriber.py @@ -0,0 +1,20 @@ +import abc + + +class Subscriber(abc.ABC): + """Subscribes to events in the runtime. + + Subscribers can be used to save data, visualize, etc. + """ + + @abc.abstractmethod + def on_episode_start(self) -> None: + """Called when an episode starts.""" + + @abc.abstractmethod + def on_step(self, observation: dict, action: dict) -> None: + """Append a step to the episode.""" + + @abc.abstractmethod + def on_episode_end(self) -> None: + """Called when an episode ends.""" diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/websocket_client_policy.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/websocket_client_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..5a3638a781c21bae30dfcf4557eae45e73aafdbb --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/packages/openpi-client/src/openpi_client/websocket_client_policy.py @@ -0,0 +1,81 @@ +import logging +import time +from typing import Dict, Optional, Tuple + +from typing_extensions import override +import websockets.sync.client + +from openpi_client import base_policy as _base_policy +from openpi_client import msgpack_numpy + +import numpy as np + +class WebsocketClientPolicy(_base_policy.BasePolicy): + """Implements the Policy interface by communicating with a server over websocket. + + See WebsocketPolicyServer for a corresponding server implementation. + """ + + def __init__(self, host: str = "0.0.0.0", port: Optional[int] = None, api_key: Optional[str] = None) -> None: + self._uri = f"ws://{host}" + if port is not None: + self._uri += f":{port}" + self._packer = msgpack_numpy.Packer() + self._api_key = api_key + self._ws, self._server_metadata = self._wait_for_server() + + def get_server_metadata(self) -> Dict: + return self._server_metadata + + def _wait_for_server(self) -> Tuple[websockets.sync.client.ClientConnection, Dict]: + logging.info(f"Waiting for server at {self._uri}...") + while True: + try: + headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None + conn = websockets.sync.client.connect( + self._uri, compression=None, max_size=None, additional_headers=headers, + ping_timeout=600, open_timeout=60, close_timeout=60 + ) + metadata = msgpack_numpy.unpackb(conn.recv()) + return conn, metadata + except ConnectionRefusedError: + logging.info("Still waiting for server...") + time.sleep(5) + + @override + def infer(self, obs: Dict) -> Dict: # noqa: UP006 + data = self._packer.pack(obs) + self._ws.send(data) + response = self._ws.recv() + if isinstance(response, str): + # we're expecting bytes; if the server sends a string, it's an error. + raise RuntimeError(f"Error in inference server:\n{response}") + return msgpack_numpy.unpackb(response) + + @override + def reset(self) -> None: + pass + +class MMEVLAWebsocketClientPolicy(WebsocketClientPolicy): + """ add reset method to the base policy""" + + def infer(self, obs: Dict) -> Dict: # noqa: UP006 + data = self._packer.pack(obs) + self._ws.send(data) + response = self._ws.recv() + if isinstance(response, str): + # we're expecting bytes; if the server sends a string, it's an error. + raise RuntimeError(f"Error in inference server:\n{response}") + return msgpack_numpy.unpackb(response) + + def reset(self) -> None: + data = self._packer.pack({"reset": True}) + self._ws.send(data) + response = self._ws.recv() + return msgpack_numpy.unpackb(response) + + def add_buffer(self, buffer: Dict): + data = self._packer.pack(buffer) + self._ws.send(data) + response = self._ws.recv() + return msgpack_numpy.unpackb(response) \ No newline at end of file diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/pyproject.toml b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..092ee3f14ab95e162c27d3d1a1f9df9b0b006028 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/pyproject.toml @@ -0,0 +1,155 @@ +[project] +name = "openpi" +version = "0.1.0" +description = "Physical Intelligence open source repo" +readme = "README.md" +requires-python = ">=3.10,<=3.12" +license = { file = "LICENSE" } +dependencies = [ + "augmax>=0.3.4", + "dm-tree>=0.1.8", + "einops>=0.8.0", + "equinox>=0.11.8", + "flatbuffers>=24.3.25", + "flax==0.10.2", + "fsspec[gcs]>=2024.6.0", + "gym-aloha>=0.1.1", + "imageio>=2.36.1", + "jax[cuda12]==0.5.3", + "jaxtyping==0.2.36", + "ml_collections==1.0.0", + "numpy>=1.22.4,<2.0.0", + "numpydantic>=1.6.6", + "opencv-python>=4.10.0.84", + "openpi-client", + "orbax-checkpoint==0.11.13", + "picmem-dev", + "pillow>=11.0.0", + "sentencepiece>=0.2.0", + "torch==2.8.0", + "tqdm-loggable>=0.2", + "typing-extensions>=4.12.2", + "tyro>=0.9.5", + "wandb>=0.19.1", + "filelock>=3.16.1", + "beartype==0.19.0", + "treescope>=0.1.7", + "transformers==4.53.2", + "rich>=14.0.0", + "polars>=1.30.0", + "mediapy>=1.2.4", + "loguru>=0.7.3", + "ffmpeg-python>=0.2.0", + "hydra-core>=1.3.2", + "h5py==3.13.0", + "pandas>=2.2,<3; python_version < '3.11'", + "pandas>=3.0.1; python_version >= '3.11'", + "flask>=3.1.3", +] + + +[project.urls] +Repository = "https://github.com/Physical-Intelligence/openpi" + +[dependency-groups] +dev = [ + "pytest>=8.3.4", + "ruff>=0.8.6", + "ipykernel>=6.29.5", + "ipywidgets>=8.1.5", + "matplotlib>=3.10.0", + "pynvml>=12.0.0", + "pytest-cov>=6.2.1", + "black>=25.1.0", + "mypy>=1.17.1", + "pre-commit>=4.3.0", +] +rlds = [ + "dlimp", + "tensorflow-cpu==2.15.0", + "tensorflow-datasets==4.9.9", +] + +[tool.uv] +override-dependencies = ["ml-dtypes==0.4.1", "tensorstore==0.1.74"] + +[tool.uv.sources] +openpi-client = { workspace = true } +picmem-dev = { path = "..", editable = true } +lerobot = { git = "https://github.com/huggingface/lerobot", rev = "0cf864870cf29f4738d3ade893e6fd13fbd7cdb5" } +dlimp = { git = "https://github.com/kvablack/dlimp", rev = "ad72ce3a9b414db2185bc0b38461d4101a65477a" } +torch = { index = "pytorch-cu126" } + +[[tool.uv.index]] +name = "pytorch-cu126" +url = "https://download.pytorch.org/whl/cu126" +explicit = true + +[tool.uv.workspace] +members = ["packages/*", "sandbox2/flash_attn_jax"] + +[tool.ruff] +line-length = 120 +target-version = "py310" +extend-exclude = ["docker", "third_party", "src/openpi/models_pytorch/transformers_replace/*"] + +[tool.ruff.lint] +# https://docs.astral.sh/ruff/rules/ +select = [ + "B", + "C4", + "DTZ", + "E4", + "E7", + "E9", + "F", + "FBT", + "FURB", + "I", + "ICN", + "ISC", + "LOG", + "N", + "PD", + "PERF", + "PIE", + "PLC", + "PLE", + "PLR1", + "PLR5", + "PLW", + "PT", + "Q", + "RET", + "RUF", + "SIM", + "SLF", + "T10", + "T20", + "UP", + "W", +] +ignore = [ + "F722", # Conflicts with array typing. + "T201", # We use print statements. + "PD008", # Lots of false positives. + "ISC001", # Disabling to support ruff format. + "LOG015", # Use logger.info. +] +unfixable = [ + "B905", # Fix defaults to strict=False, which is not what we want. +] + +[tool.ruff.lint.isort] +force-single-line = true +force-sort-within-sections = true +single-line-exclusions = ["collections.abc", "typing", "typing_extensions"] +known-third-party = ["wandb"] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.pytest.ini_options] +markers = ["manual: should be run manually."] +testpaths = ["src", "scripts", "packages"] diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/src/mme_vla_suite/__init__.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/src/mme_vla_suite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/src/mme_vla_suite/dataset_builder/build_robomme_dataset.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/src/mme_vla_suite/dataset_builder/build_robomme_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..79f9010092f356320d7b0c07791fa61848144faf --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/src/mme_vla_suite/dataset_builder/build_robomme_dataset.py @@ -0,0 +1,318 @@ +"""Preprocess raw HDF5 RoboMME data into training-ready format. + +Converts episodes to features, token-drop indices, and per-step pickle samples. +""" + +from __future__ import annotations + +import argparse +import json +import os +import pickle +import shutil +import time + +import cv2 +import h5py +import imageio +import numpy as np + +from mme_vla_suite.shared.mem_buffer import MemoryBuffer, create_dict + +from mme_vla_suite.dataset_builder.robomme_h5_utils import ( + first_execution_step, + remove_redundant_keyframes, + resolve_subgoal, +) + + +# Action and state +ACTION_CHUNK_HORIZON = 20 +JOINT_STATE_DIM = 8 + +# Token-dropping visualization (8x8 spatial grid, 32x32 patches) +NUM_SPATIAL_TOKENS = 64 +SPATIAL_GRID_SIZE = 8 +PATCH_HALF = 16 +DROPPED_TOKEN_ALPHA = 0.3 + +# Frame-sampling visualization +FRAME_SAMPLE_COUNT = 32 +VIS_FPS_ORIGINAL = 30 +VIS_FPS_SAMPLED = 2 +VIS_FPS_TOKENDROP = 10 + + +def get_action_chunk( + data: h5py.Group, idx: int, horizon: int = ACTION_CHUNK_HORIZON +) -> np.ndarray: + """Return (horizon, action_dim) chunk; pads with last valid action at end of episode.""" + chunk: list[np.ndarray] = [] + last_action: np.ndarray | None = None + for i in range(horizon): + try: + action = data[f"timestep_{idx + i}"]["action"]["joint_action"][()] + chunk.append(action) + last_action = action + except (KeyError, IndexError): + chunk.append(last_action) + return np.stack(chunk, axis=0) + + +def _apply_dropped_token_overlay( + img: np.ndarray, kept_per_frame: dict[int, tuple], frame_idx: int +) -> np.ndarray: + """Mask out dropped spatial tokens (white overlay) for one frame.""" + mask = np.zeros(img.shape[:2], dtype=np.uint8) + for spatial_idx in range(NUM_SPATIAL_TOKENS): + if spatial_idx in kept_per_frame[frame_idx][0]: + continue + h_center = spatial_idx // SPATIAL_GRID_SIZE * (PATCH_HALF * 2) + PATCH_HALF + w_center = spatial_idx % SPATIAL_GRID_SIZE * (PATCH_HALF * 2) + PATCH_HALF + cv2.rectangle( + mask, + (w_center - PATCH_HALF, h_center - PATCH_HALF), + (w_center + PATCH_HALF, h_center + PATCH_HALF), + 255, + -1, + ) + out = img.copy() + out[mask == 255] = out[mask == 255] * DROPPED_TOKEN_ALPHA + np.array([255, 255, 255]) * (1 - DROPPED_TOKEN_ALPHA) + return out + + +def visualize_token_dropping( + indices: list, + videos: list[np.ndarray], + output_dir: str, + exec_start_idx: int, + task_goal: str, +) -> None: + """Write two MP4s: annotated (frame idx + demo border) and raw with token-drop overlay.""" + kept_per_frame = create_dict(sorted(indices)) + images_anno: list[np.ndarray] = [] + images: list[np.ndarray] = [] + for frame_idx in kept_per_frame: + img = videos[frame_idx].copy() + img_anno = cv2.putText( + img.copy(), + str(frame_idx), + (img.shape[1] // 2, img.shape[0] // 2), + cv2.FONT_HERSHEY_SIMPLEX, + 1, + (0, 0, 255), + 1, + ) + img_anno = _apply_dropped_token_overlay(img_anno, kept_per_frame, frame_idx) + img_masked = _apply_dropped_token_overlay(img, kept_per_frame, frame_idx) + if frame_idx < exec_start_idx: + cv2.rectangle( + img_anno, (0, 0), (img_anno.shape[1], img_anno.shape[0]), (0, 0, 255), 4 + ) + images_anno.append(img_anno) + images.append(img_masked) + + def _save(name: str, frames: list[np.ndarray]) -> None: + path = os.path.join(output_dir, f"{name}_{task_goal}.mp4") + imageio.mimsave(path, frames, fps=VIS_FPS_TOKENDROP) + + _save("token_dropping_anno", images_anno) + _save("token_dropping", images) + + +def visualize_frame_sampling( + videos: list[np.ndarray], + output_dir: str, + exec_start_idx: int, + task_goal: str, + keyframe_idxs: list[int], +) -> None: + """Write original (demo border) and evenly sampled 8-frame MP4s.""" + with_border: list[np.ndarray] = [] + for i, img in enumerate(videos): + frame = img.copy() + if i < exec_start_idx: + cv2.rectangle( + frame, (0, 0), (frame.shape[1], frame.shape[0]), (255, 0, 0), 10 + ) + if i in keyframe_idxs: + cv2.rectangle( + frame, (0, 0), (frame.shape[1], frame.shape[0]), (0, 255, 0), 10 + ) + with_border.append(frame) + if i in keyframe_idxs: + for _ in range(3): # halt for a while to show the keyframe + with_border.append(frame) + + + imageio.mimsave( + os.path.join(output_dir, f"original_video_{task_goal}.mp4"), + with_border, + fps=VIS_FPS_ORIGINAL, + ) + indices = np.linspace(0, len(with_border) - 1, FRAME_SAMPLE_COUNT, dtype=np.int32) + sampled = [with_border[i] for i in indices] + imageio.mimsave( + os.path.join(output_dir, f"frame_sampling_{task_goal}.mp4"), + sampled, + fps=VIS_FPS_SAMPLED, + ) + + +class DatasetProcessor: + """Converts raw HDF5 episodes to preprocessed features, token-drop indices, and execution samples.""" + + def __init__( + self, + raw_data_path: str = "data/raw", + preprocessed_data_path: str = "data/preprocessed", + execution_horizon: int = 16, + visualize: bool = False, + max_episodes: int | None = None, + ) -> None: + self.raw_data_path = raw_data_path + self.dataset_path = preprocessed_data_path + self.execution_horizon = execution_horizon + self.visualize = visualize + self.max_episodes = max_episodes + if os.path.exists(self.dataset_path): + shutil.rmtree(self.dataset_path) + os.makedirs(self.dataset_path, exist_ok=True) + + self.feature_path = os.path.join(self.dataset_path, "features") + self.data_path = os.path.join(self.dataset_path, "data") + self.meta_path = os.path.join(self.dataset_path, "meta") + for p in (self.feature_path, self.data_path, self.meta_path): + os.makedirs(p, exist_ok=True) + + def run(self) -> None: + """Process all .h5 files; optionally cap episodes per file (default: process all).""" + global_episode_idx = 0 + mem_buffer = MemoryBuffer( + num_views=1, + compute_token_drop_score=True, + token_drop_stride=self.execution_horizon // 2, + prepare_buffer=True, + ) + exec_sample_id = 0 + total_sample_id = 0 + + for fname in os.listdir(self.raw_data_path): + if not fname.endswith(".h5"): + continue + print(f"Processing file: {fname}") + path = os.path.join(self.raw_data_path, fname) + with h5py.File(path, "r") as data: + episode_indices = sorted( + int(k.split("_")[1]) + for k in data.keys() + if k.startswith("episode_") + ) + if self.max_episodes is not None: + episode_indices = episode_indices[:self.max_episodes] + for episode_idx in episode_indices: + global_episode_idx, mem_buffer, exec_sample_id, total_sample_id = ( + self._process_episode( + data, episode_idx, global_episode_idx, + mem_buffer, exec_sample_id, total_sample_id, + ) + ) + + stats = {"execution_samples": exec_sample_id, "total_samples": total_sample_id} + with open(os.path.join(self.meta_path, "stats.json"), "w") as f: + json.dump(stats, f, indent=2) + + def _first_execution_step(self, episode_data: h5py.Group) -> int: + return first_execution_step(episode_data) + + def _remove_redundant_keyframes( + self, keyframe_idxs: list[int], exec_start_idx: int, threshold: int = 10 + ) -> list[int]: + return remove_redundant_keyframes(keyframe_idxs, exec_start_idx, threshold) + + def _process_episode( + self, + data: h5py.File, + episode_idx: int, + global_episode_idx: int, + mem_buffer: MemoryBuffer, + exec_sample_id: int, + total_sample_id: int, + ) -> tuple[int, MemoryBuffer, int, int]: + episode_data = data[f"episode_{episode_idx}"] + task_goal = episode_data["setup"]["task_goal"][()][0].decode() + num_timesteps = sum(1 for k in episode_data.keys() if k.startswith("timestep_")) + exec_start_idx = self._first_execution_step(episode_data) + + visualization_videos: list[np.ndarray] = [] + record_videos: list[np.ndarray] = [] + keyframe_idxs: list[int] = [] + + episode_feature_dir = os.path.join(self.feature_path, f"episode_{global_episode_idx}") + os.makedirs(episode_feature_dir, exist_ok=True) + + for step_idx in range(num_timesteps): + ts = episode_data[f"timestep_{step_idx}"] + action_chunk = get_action_chunk(episode_data, step_idx, horizon=ACTION_CHUNK_HORIZON) + joint_state = ts["obs"]["joint_state"][()] + gripper_state = ts["obs"]["gripper_state"][()] + state = np.concatenate([joint_state, gripper_state[:1]], axis=0, dtype=np.float32) + image = ts["obs"]["front_rgb"][()] + wrist_image = ts["obs"]["wrist_rgb"][()] + is_video_demo = step_idx < exec_start_idx + assert ts["info"]["is_video_demo"][()] == is_video_demo, "is_video_demo mismatch" + + if not ts['info']['is_completed'][()]: + simple_subgoal = ts["info"]["simple_subgoal"][()].decode() + grounded_subgoal = ts["info"]["grounded_subgoal"][()].decode() + simple_subgoal_online = ts["info"]["simple_subgoal_online"][()].decode() + grounded_subgoal_online = ts["info"]["grounded_subgoal_online"][()].decode() + + if ts["info"]["is_subgoal_boundary"][()]: + keyframe_idxs.append(step_idx) + + frame_dict = { + "image": image, + "wrist_image": wrist_image, + "state": state, + "actions": action_chunk, + "is_demo": np.array([is_video_demo], dtype=np.bool_), + "exec_start_idx": np.array([exec_start_idx], dtype=np.int32), + "step_idx": np.array([step_idx], dtype=np.int32), + "epis_idx": np.array([global_episode_idx], dtype=np.int32), + "prompt": task_goal.lower(), + "simple_subgoal": simple_subgoal.lower(), + "grounded_subgoal": grounded_subgoal.lower(), + "simple_subgoal_online": simple_subgoal_online.lower(), + "grounded_subgoal_online": grounded_subgoal_online.lower(), + } + + mem_buffer.add_buffer(image[None, None, ...], state[None, ...], [step_idx]) + feat_path = os.path.join(episode_feature_dir, f"token_emb_{step_idx}.npy") + np.save(feat_path, mem_buffer.get_history_feats(step_idx)) + + if not is_video_demo: + pkl_path = os.path.join(self.data_path, f"{exec_sample_id}.pkl") + assert not os.path.exists(pkl_path), f"Collision: {pkl_path}" + with open(pkl_path, "wb") as f: + pickle.dump(frame_dict, f) + exec_sample_id += 1 + total_sample_id += 1 + + visualization_videos.append(image.copy()) + record_videos.append(np.concatenate([image, wrist_image], axis=1)) + + kept_indices = mem_buffer.get_token_dropping_indices() + with open(os.path.join(episode_feature_dir, "kept_indices.json"), "w") as f: + json.dump(kept_indices, f) + + if self.visualize: + keyframe_idxs = self._remove_redundant_keyframes(keyframe_idxs, exec_start_idx) + visualize_frame_sampling(record_videos, episode_feature_dir, exec_start_idx, task_goal, keyframe_idxs) + visualize_token_dropping(kept_indices, visualization_videos, episode_feature_dir, exec_start_idx, task_goal) + + mem_buffer.clear() + print( + f"Episode {global_episode_idx}: timesteps={num_timesteps}, exec_start={exec_start_idx}, kept_indices={len(kept_indices)}, task_goal='{task_goal}'", + ) + return global_episode_idx + 1, mem_buffer, exec_sample_id, total_sample_id \ No newline at end of file diff --git a/checkpoints/r2/shuffle/baseline/step9000/code/robomme/src/mme_vla_suite/dataset_builder/build_vlm_subgoal_dataset_memer.py b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/src/mme_vla_suite/dataset_builder/build_vlm_subgoal_dataset_memer.py new file mode 100644 index 0000000000000000000000000000000000000000..0deed82c13baecdf0d83b78244d62ba6256f1a60 --- /dev/null +++ b/checkpoints/r2/shuffle/baseline/step9000/code/robomme/src/mme_vla_suite/dataset_builder/build_vlm_subgoal_dataset_memer.py @@ -0,0 +1,464 @@ +""" +Build VLM subgoal prediction dataset for MemER +""" + +import json +import os + +import cv2 +import h5py +import imageio +import numpy as np +import argparse + +from mme_vla_suite.dataset_builder.robomme_h5_utils import get_task_goal, get_timestep_indices +from mme_vla_suite.dataset_builder.vlm_subgoal_dataset_base import BaseVLMSubgoalDatasetBuilder + +np.set_printoptions(precision=4, suppress=True) + + +# ----------------------------------------------------------------------------- +# Keyframe detection (MemER-specific) +# ----------------------------------------------------------------------------- + + +def find_local_minima(episode_data, timestep_indexs, threshold=0.001, min_distance=5): + delta_actions = [] + for idx in timestep_indexs: + state = episode_data[f"timestep_{idx}"]["obs"]["joint_state"][()] + action = episode_data[f"timestep_{idx}"]["action"]["joint_action"][()][:7] + delta_action = action - state + delta_actions.append(np.linalg.norm(delta_action)) + delta_actions = np.array(delta_actions) + + minima_indices = [] + n = len(delta_actions) + + for i in range(1, n - 1): + if delta_actions[i] >= threshold: + continue + if delta_actions[i] >= delta_actions[i - 1] or delta_actions[i] >= delta_actions[i + 1]: + continue + if minima_indices and (i - minima_indices[-1] < min_distance): + continue + minima_indices.append(i) + + return minima_indices + + +def get_middle_point(frm_0, frm_1, num=1) -> list: + return np.linspace(frm_0, frm_1, num + 2)[1:-1].astype(int).tolist() + + +def merge(transition_idxs: list, local_minima_idx: list, exec_start_idx: int) -> list: + merged_idxs = transition_idxs + local_minima_idx + merged_idxs = sorted(list(set(merged_idxs))) + merged_idxs = [idx for idx in merged_idxs if idx >= exec_start_idx] + output = [merged_idxs[0]] + for i in range(1, len(merged_idxs)): + if abs(merged_idxs[i] - output[-1]) < 10: + output[-1] = (merged_idxs[i] + output[-1]) // 2 + else: + output.append(merged_idxs[i]) + return output + + +# ----------------------------------------------------------------------------- +# Text / image helpers (visualization) +# ----------------------------------------------------------------------------- + + +def wrap_text_opencv(text, font, font_scale, max_width, thickness=1): + """Wrap text to fit within max_width pixels.""" + words = text.split(" ") + lines = [] + current_line = "" + + for word in words: + test_line = f"{current_line} {word}".strip() + (w, h), _ = cv2.getTextSize(test_line, font, font_scale, thickness) + if w <= max_width: + current_line = test_line + else: + if current_line: + lines.append(current_line) + current_line = word + if current_line: + lines.append(current_line) + return lines + + +def put_wrapped_text(image, text, org, font, font_scale, color, thickness=1, line_spacing=20): + """Put wrapped text on image.""" + x, y = org + max_width = image.shape[1] - x - 10 + lines = wrap_text_opencv(text, font, font_scale, max_width, thickness) + for i, line in enumerate(lines): + cv2.putText(image, line, (x, y + i * line_spacing), font, font_scale, color, thickness) + return image, y + len(lines) * line_spacing + + +# ----------------------------------------------------------------------------- +# Prompts +# ----------------------------------------------------------------------------- + +SUBGOAL_SYSTEM_PROMPT = ( + "You are a robot program that predicts actions. The current input images from the front-view camera shows the most recent actions the robot has executed. " + "The past keyframes are selected frames of particular importance from all the actions the robot has executed so far. Based on these, output the current subtask the robot should execute and nothing else. " + "Some tasks may have a video input for initial setup, some may not.\n\n" + "Return a JSON with:\n" + "- current_subtask: the action that should be executed at the current timestep\n" + "- keyframe_positions: list of frame positions (1-indexed) from the current input images where actions change" +) + + +# ----------------------------------------------------------------------------- +# Dataset builder +# ----------------------------------------------------------------------------- + + +class DatasetBuilder(BaseVLMSubgoalDatasetBuilder): + def run(self) -> list: + results = super().run() + if results: + print(f"max_frame_len: {max(r or 0 for r in results)}") + return results + + # ------------------------------------------------------------------------- + # Prompt / text helpers (MemER-specific) + # ------------------------------------------------------------------------- + + def _wrap_keyframes(self, key_frame_paths: list) -> str: + return "; ".join( + [f"Past Keyframe {i+1}: " for i in range(len(key_frame_paths))] + ) + + def _wrap_execution_frames(self, execution_frame_paths: list) -> str: + return "; ".join( + [ + f"Executed Frame {i+1}: " + for i in range(len(execution_frame_paths)) + ] + ) + + def _wrap_images(self, image_paths: list) -> str: + if len(image_paths) == 0: + return "[]" + return "[" + ", ".join(["" for _ in image_paths]) + "]" + + # ------------------------------------------------------------------------- + # Simple subgoal data + # ------------------------------------------------------------------------- + + def make_simple_subgoal_data( + self, + task_goal: str, + subgoal: str, + execution_frame_paths: list, + key_frame_paths: list, + video_path: str | None = None, + candidate_frame_idx: int | None = None, + ) -> dict: + video_prefix = ( + "The task has a video input for initial setup: